From f7522bf6c870635e31ffae9a4658efcbe9cb0946 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Tue, 10 Jun 2025 17:21:28 +0530 Subject: [PATCH 01/27] docs snippets for publish-subscribe, presence, message-persistence, app-context, mobile-push, access-manager, channel-groups. --- docs-snippets/access-manager.ts | 226 ++++++++++++++ docs-snippets/basic-usage/access-manager.ts | 69 +++++ docs-snippets/basic-usage/app-context.ts | 280 ++++++++++++++++++ docs-snippets/basic-usage/channel-groups.ts | 68 +++++ docs-snippets/basic-usage/event-listener.ts | 45 +++ .../basic-usage/message-persistence.ts | 53 ++++ docs-snippets/basic-usage/mobile-push.ts | 159 ++++++++++ docs-snippets/basic-usage/presence.ts | 63 ++++ .../basic-usage/publish-subscribe.ts | 118 ++++++++ docs-snippets/event-listener.ts | 31 ++ docs-snippets/message-persistence.ts | 56 ++++ docs-snippets/mobile-push.ts | 37 +++ docs-snippets/presence.ts | 40 +++ docs-snippets/publish-subscribe.ts | 115 +++++++ docs-snippets/tsconfig.json | 21 ++ lib/types/index.d.ts | 4 +- src/core/pubnub-common.ts | 4 +- 17 files changed, 1385 insertions(+), 4 deletions(-) create mode 100644 docs-snippets/access-manager.ts create mode 100644 docs-snippets/basic-usage/access-manager.ts create mode 100644 docs-snippets/basic-usage/app-context.ts create mode 100644 docs-snippets/basic-usage/channel-groups.ts create mode 100644 docs-snippets/basic-usage/event-listener.ts create mode 100644 docs-snippets/basic-usage/message-persistence.ts create mode 100644 docs-snippets/basic-usage/mobile-push.ts create mode 100644 docs-snippets/basic-usage/presence.ts create mode 100644 docs-snippets/basic-usage/publish-subscribe.ts create mode 100644 docs-snippets/event-listener.ts create mode 100644 docs-snippets/message-persistence.ts create mode 100644 docs-snippets/mobile-push.ts create mode 100644 docs-snippets/presence.ts create mode 100644 docs-snippets/publish-subscribe.ts create mode 100644 docs-snippets/tsconfig.json diff --git a/docs-snippets/access-manager.ts b/docs-snippets/access-manager.ts new file mode 100644 index 000000000..ac67e2035 --- /dev/null +++ b/docs-snippets/access-manager.ts @@ -0,0 +1,226 @@ +import PubNub from '../lib/types'; + +// Initialize PubNub with demo keys +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId' + }); + +// snippet.grantTokenVariousResources +try { + const token = await pubnub.grantToken({ + ttl: 15, + authorized_uuid: "my-authorized-uuid", + resources: { + channels: { + "channel-a": { + read: true, + }, + "channel-b": { + read: true, + write: true, + }, + "channel-c": { + read: true, + write: true, + }, + "channel-d": { + read: true, + write: true, + }, + }, + groups: { + "channel-group-b": { + read: true, + }, + }, + uuids: { + "uuid-c": { + get: true, + }, + "uuid-d": { + get: true, + update: true, + }, + }, + }, + }); +} catch (status) { + console.log(status); +} +// snippet.end + +// snippet.grantTokenUsingRegEx +try { + const token = await pubnub.grantToken({ + ttl: 15, + authorized_uuid: "my-authorized-uuid", + patterns: { + channels: { + "^channel-[A-Za-z0-9]$": { + read: true, + }, + }, + }, + }); +} catch (status) { + console.log(status); +} +// snippet.end + +// snippet.grantTokenRegExAndResources +try { + const token = await pubnub.grantToken({ + ttl: 15, + authorized_uuid: "my-authorized-uuid", + resources: { + channels: { + "channel-a": { + read: true, + }, + "channel-b": { + read: true, + write: true, + }, + "channel-c": { + read: true, + write: true, + }, + "channel-d": { + read: true, + write: true, + }, + }, + groups: { + "channel-group-b": { + read: true, + }, + }, + uuids: { + "uuid-c": { + get: true, + }, + "uuid-d": { + get: true, + update: true, + }, + }, + }, + patterns: { + channels: { + "^channel-[A-Za-z0-9]$": { + read: true + }, + }, + }, + }); +} catch (status) { + console.log(status); +} +// snippet.end + +// snippet.grantTokenSpaceUserResources +try { + const token = await pubnub.grantToken({ + ttl: 15, + authorizedUserId: "my-authorized-userId", + resources: { + spaces: { + "space-a": { + read: true, + }, + "space-b": { + read: true, + write: true, + }, + "space-c": { + read: true, + write: true, + }, + "space-d": { + read: true, + write: true, + }, + }, + users: { + "userId-c": { + get: true, + }, + "userId-d": { + get: true, + update: true, + }, + }, + }, + }); +} catch (status) { + console.log(status); +} +// snippet.end + +// snippet.grantTokenSpaceUserRegEx +try { + const token = await pubnub.grantToken({ + ttl: 15, + authorizedUserId: "my-authorized-userId", + patterns: { + spaces: { + "^space-[A-Za-z0-9]$": { + read: true, + }, + }, + }, + }); +} catch (status) { + console.log(status); +} +// snippet.end + + +// snippet.grantTokenSpacesUserRegExResources +try { + const token = await pubnub.grantToken({ + ttl: 15, + authorizedUserId: "my-authorized-userId", + resources: { + spaces: { + "space-a": { + read: true, + }, + "space-b": { + read: true, + write: true, + }, + "space-c": { + read: true, + write: true, + }, + "space-d": { + read: true, + write: true, + }, + }, + users: { + "userId-c": { + get: true, + }, + "userId-d": { + get: true, + update: true, + }, + }, + }, + patterns: { + spaces: { + "^space-[A-Za-z0-9]$": { + read: true + }, + }, + }, + }); +} catch (status) { + console.log(status); +} +// snippet.end + diff --git a/docs-snippets/basic-usage/access-manager.ts b/docs-snippets/basic-usage/access-manager.ts new file mode 100644 index 000000000..448822d87 --- /dev/null +++ b/docs-snippets/basic-usage/access-manager.ts @@ -0,0 +1,69 @@ +import PubNub from '../../lib/types'; +// snippet.accessManagerBasicUsage +// import PubNub + +// Initialize PubNub with demo keys +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId' + }); + +// Function to use grantToken method +async function grantAccessToken() { + try { + const token = await pubnub.grantToken({ + ttl: 15, + authorized_uuid: "my-authorized-uuid", + resources: { + channels: { + "my-channel": { + read: true, + write: true + } + } + } + }); + console.log("Granted Token:", token); + } catch (status) { + console.log("Grant Token Error:", status); + } +} + +// Execute the function to grant a token +grantAccessToken(); +// snippet.end + +// snippet.grantTokenSpacesUserBasicUsage +try { + const token = await pubnub.grantToken({ + ttl: 15, + authorizedUserId: "my-authorized-userId", + resources: { + spaces: { + "my-space": { + read: true, + }, + }, + }, + }); +} catch (status) { + console.log(status); +} +// snippet.end + +// snippet.revokeTokenBasicUsage +try { + const response = await pubnub.revokeToken("p0AkFl043rhDdHRsple3KgQ3NwY6BDcENnctokenVzcqBDczaWdYIGOAeTyWGJI"); +} catch (status) { + console.log(status); +} +// snippet.end + +// snippet.parseTokenBasicUsage +pubnub.parseToken("p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI") +// snippet.end + +// snippet.setTokenBasicUsage +pubnub.setToken("p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI") +// snippet.end \ No newline at end of file diff --git a/docs-snippets/basic-usage/app-context.ts b/docs-snippets/basic-usage/app-context.ts new file mode 100644 index 000000000..edd805edd --- /dev/null +++ b/docs-snippets/basic-usage/app-context.ts @@ -0,0 +1,280 @@ +import PubNub from '../../lib/types'; +// snippet.getAllUUIDMetadataBasicUsage +// import PubNub +// Initialize PubNub with demo keys +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId' + }); + +// Function to get all UUID metadata +async function getAllUUIDMetadata() { + try { + const response = await pubnub.objects.getAllUUIDMetadata(); + console.log(`getAllUUIDMetadata response: ${response}`); + } catch (error) { + console.log(`getAllUUIDMetadata failed with error: ${error}`); + } +} + +// Execute the function to get UUID metadata +getAllUUIDMetadata(); +// snippet.end + +// snippet.getUUIDMetadataBasicUsage +// Using UUID from the config +try { + const response = await pubnub.objects.getUUIDMetadata(); + console.log(`getUUIDMetadata response: ${response}`); +} catch (status) { + console.log(`getUUIDMetadata failed with error: ${status}`); +} + +// Using the passed in UUID +try { + const response = await pubnub.objects.getUUIDMetadata({ + uuid: "myUuid", + }); + console.log(`getUUIDMetadata response: ${response}`); +} catch (status) { + console.log(`getUUIDMetadata failed with error: ${status}`); +} +// snippet.end + +// snippet.setUUIDMetadataBasicUsage +// Using UUID from the config +try { + const response = await pubnub.objects.setUUIDMetadata({ + data: { + name: "John Doe", + }, + }); +} catch (status) { + console.log(`setUUIDMetadata failed with error: ${status}`); +} + +// Using the passed in UUID +try { + const response = await pubnub.objects.setUUIDMetadata({ + uuid: "myUuid", + data: {}, + }); +} catch (status) { + console.log(`setUUIDMetadata failed with error: ${status}`); +} + +// snippet.end + +// snippet.removeUUIDMetadataBasicUsage +// Using UUID from the config +try { + const response = await pubnub.objects.removeUUIDMetadata(); +} catch (status) { + console.log(`removeUUIDMetadata failed with error: ${status}`); +} + +// Using the passed in UUID +try { + const response = await pubnub.objects.removeUUIDMetadata({ + uuid: "myUuid", + }); +} catch (status) { + console.log(`removeUUIDMetadata failed with error: ${status}`); +} +// snippet.end + +// snippet.getAllChannelMetadataBasicUsage +// Get the total number of channels +try { + const response = await pubnub.objects.getAllChannelMetadata({ + include: { + totalCount: true, + }, + }); +} catch (status) { + console.log(`getAllChannelMetadata failed with error: ${status}`); +} + +// Get all channels that have IDs starting with "pro." +try { + const response = await pubnub.objects.getAllChannelMetadata({ + filter: 'name LIKE "*Team"', + }); +} catch (status) { + console.log(`getAllChannelMetadata failed with error: ${status}`); +} +// snippet.end + +// snippet.getChannelMetadataBasicUsage +try { + const response = await pubnub.objects.getChannelMetadata({ + // `channel` is the `id` in the _metadata_, not `name` + channel: "team.blue", + }); +} catch (status) { + console.log(`getChannelMetadata failed with error: ${status}`); +} +// snippet.end + +// snippet.setChannelMetadataBasicUsage +try { + const response = await pubnub.objects.setChannelMetadata({ + channel: "team.red", + data: { + name: "Red Team", + description: "The channel for Red team and no other teams.", + custom: { + owner: "Red Leader", + }, + }, + include: { + customFields: false, + }, + }); +} catch (status) { + console.log(`setChannelMetadata failed with error: ${status}`); +} +// snippet.end + +// snippet.removeChannelMetadataBasicUsage +try { + const response = await pubnub.objects.removeChannelMetadata({ + channel: "team.red", + }); +} catch (status) { + console.log(`removeChannelMetadata failed with error: ${status}`); +} +// snippet.end + +// snippet.getMembershipBasicUsage +// Using UUID from the config +try { + const response = await pubnub.objects.getMemberships(); +} catch (status) { + console.log(`getMemberships failed with error: ${status}`); +} + +// Using the passed in UUID +try { + const response = await pubnub.objects.getMemberships({ + uuid: "myUuid", + include: { + channelFields: true, + }, + }); +} catch (status) { + console.log(`getMemberships failed with error: ${status}`); +} + +// Get all memberships that are starred by the user +try { + const response = await pubnub.objects.getMemberships({ + uuid: "myUuid", + filter: "custom.starred == true", + }); +} catch (status) { + console.log(`getMemberships failed with error: ${status}`); +} +// snippet.end + +// snippet.setMembershipBasicUsage +// Using UUID from the config +try { + const response = await pubnub.objects.setMemberships({ + channels: [ + "my-channel", + { id: "channel-with-status-type", custom: { hello: "World" }, status: 'helloStatus', type:'helloType'} + ] + }); +} catch (status) { + console.log(`setMemberships failed with error: ${status}`); +} + +// Using the passed in UUID +try { + const response = await pubnub.objects.setMemberships({ + uuid: "my-uuid", + channels: [ + "my-channel", + { id: "channel-with-status-type", custom: { hello: "World" }, status: 'helloStatus', type:'helloType'} + ], + include: { + // To include channel fields in response + channelFields: true, + }, + }); +} catch (status) { + console.log(`setMemberships failed with error: ${status}`); +} +// snippet.end + +// snippet.removeMembershipsBasicUsage +// Using UUID from the config +try { + const response = await pubnub.objects.removeMemberships({ + channels: ["ch-1", "ch-2"], + }); +} catch (status) { + console.log(`removeMemberships failed with error: ${status}`); +} + +// Using the passed in UUID +try { + const response = await pubnub.objects.removeMemberships({ + uuid: "myUuid", + channels: ["ch-1", "ch-2"], + }); +} catch (status) { + console.log(`removeMemberships failed with error: ${status}`); +} +// snippet.end + +// snippet.getChannelMembersBasicUsage +try { + const response = await pubnub.objects.getChannelMembers({ + channel: "myChannel", + include: { + UUIDFields: true, + }, + }); +} catch (status) { + console.log(`getChannelMembers failed with error: ${status}`); +} + +// Get all channel members with "admin" in the description +try { + const response = await pubnub.objects.getChannelMembers({ + channel: "myChannel", + filter: 'description LIKE "*admin*"', + }); +} catch (status) { + console.log(`getChannelMembers failed with error: ${status}`); +} +// snippet.end + +// snippet.setChannelMembersBasicUsage +try { + const response = await pubnub.objects.setChannelMembers({ + channel: "myChannel", + uuids: [ + "uuid-1", + "uuid-2", + { id: "uuid-3", custom: { role: "Super Admin" } }, + ], + }); +} catch (status) { + console.log(`setChannelMembers failed with error: ${status}`); +} +// snippet.end + +// snippet.removeChannelMembersBasicUsage +try { + const response = await pubnub.objects.removeChannelMembers({ + channel: "myChannel", + uuids: ["uuid-1", "uuid-2"], + }); +} catch (status) { + console.log(`removeChannelMembers failed with error: ${status}`); +} +// snippet.end diff --git a/docs-snippets/basic-usage/channel-groups.ts b/docs-snippets/basic-usage/channel-groups.ts new file mode 100644 index 000000000..9b8f83c81 --- /dev/null +++ b/docs-snippets/basic-usage/channel-groups.ts @@ -0,0 +1,68 @@ +import PubNub from '../../lib/types'; + +// snippet.addChannelsToGroupBasicUsage +// Initialize PubNub with demo keys +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId' +}); + +// Function to add channels to a channel group +async function addChannelsToGroup() { + try { + const response = await pubnub.channelGroups.addChannels({ + channels: ["ch1", "ch2"], + channelGroup: "myChannelGroup" + }); + console.log(`addChannels to Group response: ${response}`); + } catch (status) { + console.log(`addChannels to group failed with error: ${status}`); + } +} + +// Execute the function to add channels +addChannelsToGroup(); +// snippet.end + +// snippet.listChannelsInGroupBasicUsage +// assuming an intialized PubNub instance already exists +try { + const response = await pubnub.channelGroups.listChannels({ + channelGroup: "myChannelGroup", + }); + console.log("Listing push channels for the device"); + response.channels.forEach((channel: string) => { + console.log(channel); + }); +} catch (status) { + console.log(`listChannels of group failed with error: ${status}`); +} +// snippet.end + +// snippet.removeChannelsFromGroupBasicUsage +// assuming an initialized PubNub instance already exists +// and channel which is going to be removed from the group is aredaly added to the group to observe the removal +try { + const response = await pubnub.channelGroups.removeChannels({ + channels: ["son"], + channelGroup: "family", + }); + console.log(`removeChannels from group response: ${response}`); +} catch (status) { + console.log(`removeChannels from group failed with error: ${status}`); +} +// snippet.end + +// snippet.deleteChannelGroupBasicUsage +// assuming an initialized PubNub instance already exists +// and channel group which is getting deleted already exist to see the deletion effect. +try { + const response = await pubnub.channelGroups.deleteGroup({ + channelGroup: "family", + }); + console.log(`deleteChannelGroup response: ${response}`); +} catch (status) { + console.log(`deleteChannelGroup failed with error: ${status}`); +} +// snippet.end \ No newline at end of file diff --git a/docs-snippets/basic-usage/event-listener.ts b/docs-snippets/basic-usage/event-listener.ts new file mode 100644 index 000000000..62cfc95a7 --- /dev/null +++ b/docs-snippets/basic-usage/event-listener.ts @@ -0,0 +1,45 @@ +import PubNub from '../../lib/types'; + +// snippet.eventListenerBasicUsage +// Initialize PubNub with demo keys +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId', +}); + +// create a subscription from a channel entity +const channel = pubnub.channel('channel_1') +const subscription1 = channel.subscription({ receivePresenceEvents: true }); + +// create a subscription set with multiple channels +const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }); + +// add a status listener +pubnub.addListener({ + status: (s) => {console.log('Status', s.category) } +}); + +// add message and presence listeners +subscription1.addListener({ + // Messages + message: (m) => { console.log('Received message', m) }, + // Presence + presence: (p) => { console.log('Presence event', p) }, +}); + +// add event-specific message reactions listener +subscriptionSet1.onMessageAction = (p) => { + console.log('Message reaction event:', p); +}; + +subscription1.subscribe(); +subscriptionSet1.subscribe(); +// snippet.end + +// snippet.eventListenerAddConnectionStatusListenersBasicUsage +// add a status listener +pubnub.addListener({ + status: (s) => {console.log('Status', s.category) } +}); +// snippet.end \ No newline at end of file diff --git a/docs-snippets/basic-usage/message-persistence.ts b/docs-snippets/basic-usage/message-persistence.ts new file mode 100644 index 000000000..e499ef6cd --- /dev/null +++ b/docs-snippets/basic-usage/message-persistence.ts @@ -0,0 +1,53 @@ +// snippet.fetchMessagesBasicUsage +import PubNub from '../../lib/types'; + +// Initialize PubNub with demo keys +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId' +}); + +// Function to fetch message history +async function fetchHistory() { + try { + const result = await pubnub.fetchMessages({ + channels: ['my-channel'], + count: 1, // Number of messages to retrieve + includeCustomMessageType: true, // if you want to include custom message type in the response + start: 'replace-with-start-timetoken', // start timetoken + end: 'replace-with-end-timetoken' // end timetoken + }); + console.log('Fetched Messages:', result); + } catch (error) { + console.log('Fetch Failed:', error); + } +} + +// Execute the function to fetch message history +fetchHistory(); +// snippet.end + +// snippet.deleteMessagesBasicUsage +try { + const result = await pubnub.deleteMessages({ + channel: 'ch1', + start: 'replace-with-start-timetoken', + end: 'replace-with-end-timetoken', + }); +} catch (status) { + console.log(status); +} +// snippet.end + +// snippet.messageCountBasicUsage +try { + const result = await pubnub.messageCounts({ + channels: ["chats.room1", "chats.room2"], + channelTimetokens: ['replace-with-channel-timetoken-(optional)'], + }); +} catch (status) { + console.log(status); +} +// snippet.end + diff --git a/docs-snippets/basic-usage/mobile-push.ts b/docs-snippets/basic-usage/mobile-push.ts new file mode 100644 index 000000000..b327e2dc4 --- /dev/null +++ b/docs-snippets/basic-usage/mobile-push.ts @@ -0,0 +1,159 @@ +// snippet.addDeciveToChannelBasicUsage +import PubNub from '../../lib/types'; + +// Initialize PubNub with demo keys +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId' +}); + +// Function to add a device to a channel for APNs2 +async function addDeviceToChannelAPNs2() { + try { + const result = await pubnub.push.addChannels({ + channels: ["a", "b"], + device: "niceDevice", + pushGateway: "apns2", + environment: "production", + topic: "com.example.bundle_id" + }); + console.log("Operation done for APNs2!"); + console.log("Response:", result); + } catch (error) { + console.log("Operation failed with error for APNs2:", error); + } +} + +// Function to add a device to a channel for FCM +async function addDeviceToChannelFCM() { + try { + const result = await pubnub.push.addChannels({ + channels: ["a", "b"], + device: "niceDevice", + pushGateway: "gcm" + }); + console.log("Operation done for FCM!"); + console.log("Response:", result); + } catch (error) { + console.log("Operation failed with error for FCM:", error); + } +} + +// Execute the functions to add the device to channels +addDeviceToChannelAPNs2(); +addDeviceToChannelFCM(); + +// snippet.end + +// snippet.listChannelsForDeviceBasicUsage +// for APNs2 +try { + const response = await pubnub.push.listChannels({ + device: "niceDevice", + pushGateway: "apns2", + environment: "production", + topic: "com.example.bundle_id" + }); + console.log(`listing channels for device response: ${response}`); + response.channels.forEach((channel: string) => { + console.log(channel); + }); +} catch (status) { + console.log(`listing channels for device failed with error: ${status}`); +} + +// for FCM +try { + const response = await pubnub.push.listChannels({ + device: "niceDevice", + pushGateway: "gcm" + }); + + console.log(`listing channels for device response: ${response}`); + + response.channels.forEach((channel: string) => { + console.log(channel); + }); +} catch (status) { + console.log(`listing channels for device failed with error: ${status}`); +} +// snippet.end + +// snippet.removeDeviceFromChannelBasicUsage +// for APNs2 +try { + const response = await pubnub.push.removeChannels({ + channels: ["a", "b"], + device: "niceDevice", + pushGateway: "apns2", + environment: "production", + topic: "com.example.bundle_id" + }); + + console.log(`removing device from channel response: ${response}`); + +} catch (status) { + console.log(`removing device from channel failed with error: ${status}`); +} + +// for FCM +try { + const response = await pubnub.push.removeChannels({ + channels: ["a", "b"], + device: "niceDevice", + pushGateway: "gcm" + }); + + console.log(`removing device from channel response: ${response}`); +} catch (status) { + console.log(`removing device from channel failed with error: ${status}`); +} +// snippet.end + +// snippet.removeAllMobilePushNotificationsBasicUsage + +// for APNs2 +try { + const response = await pubnub.push.deleteDevice({ + device: "niceDevice", + pushGateway: "apns2", + environment: "production", + topic: "com.example.bundle_id" + }); + + console.log(`deleteDevice response: ${response}`); + +} catch (status) { + console.log(`deleteDevice failed with error: ${status}`); +} + +// for FCM +try { + const response = await pubnub.push.deleteDevice({ + device: "niceDevice", + pushGateway: "gcm" + }); + + console.log(`deleteDevice response: ${response}`); +} catch (status) { + console.log(`deleteDevice failed with error: ${status}`); +} + +// snippet.end + +// snippet.buildNotificationPayloadBasicUsage + +let builder = PubNub.notificationPayload('Chat invitation', + 'You have been invited to \'quiz\' chat'); +let messagePayload = builder.buildPayload(['apns2', 'fcm']); +// add required fields to the payload + +const response = await pubnub.publish({ + message: messagePayload, + channel: 'chat-bot', +}); + +console.log(`publish response: ${response}`); + +// snippet.end \ No newline at end of file diff --git a/docs-snippets/basic-usage/presence.ts b/docs-snippets/basic-usage/presence.ts new file mode 100644 index 000000000..b1eaf5c3f --- /dev/null +++ b/docs-snippets/basic-usage/presence.ts @@ -0,0 +1,63 @@ +// snippet.hereNowBasicUsage +import PubNub from '../../lib/types'; + +// Initialize PubNub with demo keys +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId' + }); + + // Function to get presence information for a channel + async function getHereNow() { + try { + const result = await pubnub.hereNow({ + channels: ["ch1"], + channelGroups: ["cg1"], + includeUUIDs: true, + includeState: true, + }); + console.log(`Here Now Result: ${result}`); + } catch (error) { + console.log(`Here Now failed with error: ${error}`); + } + } + + // Execute the function to get presence information + getHereNow(); + +// snippet.end + +// snippet.whereNowBasicUsage +try { + const response = await pubnub.whereNow({ + uuid: "uuid", + }); +} catch (status) { + console.log(status); +} +// snippet.end + +// snippet.setStateBasicUsage +try { + const response = await pubnub.setState({ + state: { status: "online" }, + channels: ["ch1"], + channelGroups: ["cg1"], + }); +} catch (status) { + console.log(status); +} +// snippet.end + +// snippet.getStateBasicUsage +try { + const response = await pubnub.getState({ + uuid: "uuid", + channels: ["ch1"], + channelGroups: ["cg1"], + }); +} catch (status) { + console.log(status); +} +// snippet.end \ No newline at end of file diff --git a/docs-snippets/basic-usage/publish-subscribe.ts b/docs-snippets/basic-usage/publish-subscribe.ts new file mode 100644 index 000000000..7ec473e3a --- /dev/null +++ b/docs-snippets/basic-usage/publish-subscribe.ts @@ -0,0 +1,118 @@ +import PubNub from '../../lib/types'; + +// snippet.publishBasicUsage +// Initialize PubNub with demo keys +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId', +}); + +// Function to publish a message +async function publishMessage() { + try { + const response = await pubnub.publish({ + message: { text: 'Hello World' }, + channel: 'my_channel', + sendByPost: false, + storeInHistory: true, + meta: { sender: 'user123' }, + customMessageType: 'text-message', + }); + console.log('Publish Success:', response); + } catch (error) { + console.log('Publish Failed:', error); + } +} + +// Execute the function to publish the message +publishMessage(); +// snippet.end + +// snippet.signalBasicUsage +// Initialize PubNub with demo keys + try { + const response = await pubnub.signal({ + message: "hello", + channel: "foo", + customMessageType: "text-message", + }); + console.log(response); + } catch (status) { + // handle error + console.log(status); + } + // snippet.end + + // snippet.fireBasicUsage +// Initialize PubNub with your keys + try { + const response = await pubnub.fire({ + message: { + such: "object", + }, + channel: "my_channel", + sendByPost: false, // true to send via post + meta: { + cool: "meta", + }, // fire extra meta with the request + }); + + console.log(`message published with timetoken: ${response.timetoken}`); + } catch (status) { + // handle error + console.log(status); + } + // snippet.end + + // snippet.createChannelBasicUsage +// Initialize PubNub with demo keys + const channel = pubnub.channel('my_channel'); + // snippet.end + + + // snippet.createChannelGroupBasicUsage +// Initialize PubNub with demo keys + const channelGroup = pubnub.channelGroup('channelGroup_1'); + // snippet.end + + // snippet.createChannelMetadataBasicUsage +// Initialize PubNub with demo keys + + const channelMetadata = pubnub.channelMetadata('channel_1'); + // snippet.end + +// snippet.createUserMetadataBasicUsage +// Initialize PubNub with demo keys + + const userMetadata = pubnub.userMetadata('user_meta1'); + // snippet.end + + // snippet.unsubscribeBasicUsage + // create a subscription from a channel entity + const channel1 = pubnub.channel('channel_1') + const subscription1 = channel1.subscription({ receivePresenceEvents: true }); + + // create a subscription set with multiple channels + const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }); + + subscription1.subscribe(); + subscriptionSet1.subscribe(); + + subscription1.unsubscribe(); + subscriptionSet1.unsubscribe(); + // snippet.end + +// snippet.unsubscribeAllBasicUsage +// create a subscription set with multiple channels +const subscriptionSet = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }); +subscriptionSet.subscribe(); + +// create a subscription from a channel entity +const channelGroup1 = pubnub.channelGroup('channelGroup_1') +const groupSubscription1 = channelGroup1.subscription({ receivePresenceEvents: true }); +groupSubscription1.subscribe(); + +// unsubscribe all active subscriptions +pubnub.unsubscribeAll(); +// snippet.end \ No newline at end of file diff --git a/docs-snippets/event-listener.ts b/docs-snippets/event-listener.ts new file mode 100644 index 000000000..f6c425d23 --- /dev/null +++ b/docs-snippets/event-listener.ts @@ -0,0 +1,31 @@ +import PubNub from '../lib/types'; + + +// Initialize PubNub with demo keys +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId', +}); + +// snippet.eventListenerAddListeners + +// create a subscription from a channel entity +const channel = pubnub.channel('channel_1'); +const subscription = channel.subscription(); + +// Event-specific listeners +subscription.onMessage = (message) => { console.log("Message event: ", message); }; +subscription.onPresence = (presence) => { console.log("Presence event: ", presence); }; +subscription.onSignal = (signal) => { console.log("Signal event: ", signal); }; +subscription.onObjects = (objectsEvent) => { console.log("Objects event: ", objectsEvent); }; +subscription.onMessageAction = (messageActionEvent) => { console.log("Message Reaction event: ", messageActionEvent); }; +subscription.onFile = (fileEvent) => { console.log("File event: ", fileEvent); }; + +// snippet.end + +// snippet.AddConnectionStatusListener +pubnub.addListener({ + status: (s) => s.category +}) +// snippet.end \ No newline at end of file diff --git a/docs-snippets/message-persistence.ts b/docs-snippets/message-persistence.ts new file mode 100644 index 000000000..a538b24a5 --- /dev/null +++ b/docs-snippets/message-persistence.ts @@ -0,0 +1,56 @@ +import PubNub from '../lib/types'; + +// Initialize PubNub with demo keys +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId' + }); + +// snippet.fetchMessagesWithMetaActions + try { + const response = await pubnub.fetchMessages( + { + channels: ['my_channel'], + stringifiedTimeToken: true, + includeMeta: true, + includeMessageActions: true, + includeCustomMessageType: true + }); + console.log(`fetch messages response: ${response}`); + } catch (status) { + console.log(`fetch messages failed with error: ${status}`); + } +// snippet.end + +// snippet.deleteSpecificMessages + try { + const response = await pubnub.deleteMessages( + { + channel: 'ch1', + start: '15526611838554309', + end: '15526611838554310' + }); + console.log(`delete messages response: ${response}`); + } catch (error) { + console.log(`delete messages failed with error: ${error}`); + } +// snippet.end + +// snippet.messageCountTimetokensForChannels +try { + const response = await pubnub.messageCounts({ + channels: ['ch1', 'ch2', 'ch3'], + channelTimetokens: [ + 'replace-with-channel-timetoken-ch1', // timetoken for channel ch1 + 'replace-with-channel-timetoken-ch2', // timetoken for channel ch2 + 'replace-with-channel-timetoken-ch3', // timetoken for channel ch3 + ], + }); + console.log(`message count response: ${response}`); +} catch (status) { + console.log(`message count failed with error: ${status}`); +} +// snippet.end + + diff --git a/docs-snippets/mobile-push.ts b/docs-snippets/mobile-push.ts new file mode 100644 index 000000000..463a636fb --- /dev/null +++ b/docs-snippets/mobile-push.ts @@ -0,0 +1,37 @@ +import PubNub from '../lib/types'; + +// Initialize PubNub with demo keys +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId', +}); + +// snippet.simpleNotificationPayloadFCMandAPNS +let builder = PubNub.notificationPayload('Chat invitation', "You have been invited to 'quiz' chat"); +builder.sound = 'default'; + +console.log(JSON.stringify(builder.buildPayload(['apns', 'fcm']), null, 2)); +// snippet.end + +// snippet.simpleNotificationPayloadFCMandAPNSH/2 +let payloadBuilder = PubNub.notificationPayload('Chat invitation', "You have been invited to 'quiz' chat"); +payloadBuilder.apns.configurations = [{ targets: [{ topic: 'com.meetings.chat.app' }] }]; +payloadBuilder.sound = 'default'; + +console.log(JSON.stringify(payloadBuilder.buildPayload(['apns2', 'fcm']), null, 2)); +// snippet.end + +// snippet.simpleNotificationPayloadFCMandAPNSH/2CustomConfiguration +let configuration = [ + { + collapseId: 'invitations', + expirationDate: new Date(Date.now() + 10000), + targets: [{ topic: 'com.meetings.chat.app' }], + }, +]; +let customConfigurationBuilder = PubNub.notificationPayload('Chat invitation', "You have been invited to 'quiz' chat"); +customConfigurationBuilder.apns.configurations = configuration; + +console.log(JSON.stringify(customConfigurationBuilder.buildPayload(['apns2', 'fcm']), null, 2)); +// snippet.end diff --git a/docs-snippets/presence.ts b/docs-snippets/presence.ts new file mode 100644 index 000000000..7ffc9f452 --- /dev/null +++ b/docs-snippets/presence.ts @@ -0,0 +1,40 @@ +import PubNub from '../lib/types'; + +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'userId', +}); + +// snippet.hereNowWithState +try { + const response = await pubnub.hereNow({ + channels: ["my_channel"], + includeState: true, + }); +} catch (status) { + console.log(status); +} +// snippet.end + +// snippet.hereNowFetchOccupancyOnly +try { + const response = await pubnub.hereNow({ + channels: ["my_channel"], + includeUUIDs: false, + }); +} catch (status) { + console.log(status); +} +// snippet.end + + +// snippet.hereNowChannelGroup +try { + const response = await pubnub.hereNow({ + channelGroups: ["my_channel_group"] + }); +} catch (status) { + console.log(status); +} +// snippet.end \ No newline at end of file diff --git a/docs-snippets/publish-subscribe.ts b/docs-snippets/publish-subscribe.ts new file mode 100644 index 000000000..187200e4f --- /dev/null +++ b/docs-snippets/publish-subscribe.ts @@ -0,0 +1,115 @@ +import PubNub from '../lib/types'; + +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'userId', +}); + + +// snippet.publishJsonSerialisedMessage +const newMessage = { + text: 'Hi There!', + }; + + try { + const response = await pubnub.publish({ + message: newMessage, + channel: 'my_channel', + customMessageType: 'text-message', + }); + + console.log(`message published with server response: ${response}`); + } catch (status) { + console.log(`publishing failed with status: ${status}`); + } + // snippet.end + + // snippet.publishStoreThePublishedMessagefor10Hours + try { + const response = await pubnub.publish({ + message: 'hello!', + channel: 'my_channel', + storeInHistory: true, + ttl: 10, + customMessageType: 'text-message', + }); + + console.log(`message published with server response: ${response}`); + } catch (status) { + console.log(`publishing failed with status: ${status}`); + } + // snippet.end + + // snippet.publishSuccessfull + const response = await pubnub.publish({ + message: "hello world!", + channel: "ch1", + }); + + console.log(response); // {timetoken: "14920301569575101"} + // end.snippet + + // snippet.publishUnsuccessfulByNetworkDown + try { + const response = await pubnub.publish({ + message: "hello world!", + channel: "ch1", + }); + } catch (status) { + console.log(status); // {error: true, operation: "PNPublishOperation", errorData: Error, category: "PNNetworkIssuesCategory"} + } + // snippet.end + + // snippet.publishUnsuccessfulWithoutPublishKey + try { + const result = await pubnub.publish({ + message: "hello world!", + channel: "ch1", + }); + } catch (status) { + console.log(status); // {error: true, operation: "PNPublishOperation", statusCode: 400, errorData: Error, category: "PNBadRequestCategory"} + } + // snippet.end + + // // snippet.publishUnsuccessfulMissingChannel + // try { + // const result = await pubnub.publish({ + // message: "hello world!", + // }); + // } catch (status) { + // console.log(status); // {message: "Missing Channel", type: "validationError", error: true} + // } + // // snippet.end + + // // snippet.publishUnsuccessfulMissingMessage + // try { + // const result = await pubnub.publish({ + // channel: "ch1", + // }); + // } catch (status) { + // console.log(status); // {message: "Missing Message", type: "validationError", error: true} + // } + // // snippet.end + +// snippet.createSubscription +const channel = pubnub.channel('my_channel'); + +const subscriptionOptions = { receivePresenceEvents: true }; +channel.subscription(subscriptionOptions); +// snippet.end + +const subscription = pubnub.channel('channel_1').subscription(); +const subscriptionSet = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }) +// snippet.ubsubscribe +// `subscription` is an active subscription object +subscription.unsubscribe() + +// `subscriptionSet` is an active subscription set object +subscriptionSet.unsubscribe() +// snippet.end + + +// snippet.ubsubscribeAll +pubnub.unsubscribeAll() +// snippet.end \ No newline at end of file diff --git a/docs-snippets/tsconfig.json b/docs-snippets/tsconfig.json new file mode 100644 index 000000000..439175763 --- /dev/null +++ b/docs-snippets/tsconfig.json @@ -0,0 +1,21 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "module": "esnext", + "target": "es2017", + "outDir": "./docs", + "rootDir": "..", + "noEmit": true, + "skipLibCheck": true, + "resolveJsonModule": true, + "esModuleInterop": true, + + "baseUrl": "..", + }, + "include": [ + "**/*.ts" + ], + "exclude": [ + "node_modules" + ] + } \ No newline at end of file diff --git a/lib/types/index.d.ts b/lib/types/index.d.ts index 1c15350a1..b64f602fc 100644 --- a/lib/types/index.d.ts +++ b/lib/types/index.d.ts @@ -661,7 +661,7 @@ declare class PubNubCore< * @param callback - Request completion handler callback. */ grantToken( - parameters: PubNub.PAM.GrantTokenParameters, + parameters: PubNub.PAM.GrantTokenParameters | PubNub.PAM.ObjectsGrantTokenParameters, callback: PubNub.ResultCallback, ): void; /** @@ -673,7 +673,7 @@ declare class PubNubCore< * * @returns Asynchronous grant token response. */ - grantToken(parameters: PubNub.PAM.GrantTokenParameters): Promise; + grantToken(parameters: PubNub.PAM.GrantTokenParameters | PubNub.PAM.ObjectsGrantTokenParameters): Promise; /** * Revoke token permission. * diff --git a/src/core/pubnub-common.ts b/src/core/pubnub-common.ts index 6eb7023cf..6f09ba6d8 100644 --- a/src/core/pubnub-common.ts +++ b/src/core/pubnub-common.ts @@ -2785,7 +2785,7 @@ export class PubNubCore< * @param parameters - Request configuration parameters. * @param callback - Request completion handler callback. */ - public grantToken(parameters: PAM.GrantTokenParameters, callback: ResultCallback): void; + public grantToken(parameters: PAM.GrantTokenParameters | PAM.ObjectsGrantTokenParameters, callback: ResultCallback): void; /** * Grant token permission. @@ -2796,7 +2796,7 @@ export class PubNubCore< * * @returns Asynchronous grant token response. */ - public async grantToken(parameters: PAM.GrantTokenParameters): Promise; + public async grantToken(parameters: PAM.GrantTokenParameters | PAM.ObjectsGrantTokenParameters): Promise; /** * Grant token permission. From b88f9857f3fda9bfab4e0fe14602836bbac557b8 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Tue, 10 Jun 2025 18:26:21 +0530 Subject: [PATCH 02/27] fix: lint issue. --- src/core/pubnub-common.ts | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/core/pubnub-common.ts b/src/core/pubnub-common.ts index 6f09ba6d8..82ad102fe 100644 --- a/src/core/pubnub-common.ts +++ b/src/core/pubnub-common.ts @@ -2785,7 +2785,10 @@ export class PubNubCore< * @param parameters - Request configuration parameters. * @param callback - Request completion handler callback. */ - public grantToken(parameters: PAM.GrantTokenParameters | PAM.ObjectsGrantTokenParameters, callback: ResultCallback): void; + public grantToken( + parameters: PAM.GrantTokenParameters | PAM.ObjectsGrantTokenParameters, + callback: ResultCallback, + ): void; /** * Grant token permission. @@ -2796,7 +2799,9 @@ export class PubNubCore< * * @returns Asynchronous grant token response. */ - public async grantToken(parameters: PAM.GrantTokenParameters | PAM.ObjectsGrantTokenParameters): Promise; + public async grantToken( + parameters: PAM.GrantTokenParameters | PAM.ObjectsGrantTokenParameters, + ): Promise; /** * Grant token permission. From 64ba5f0effcdd0bd96811457b1e2d0cb5eed69be Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Sun, 15 Jun 2025 22:38:42 +0530 Subject: [PATCH 03/27] removed deprecation from deleteMessages() --- lib/types/index.d.ts | 2 -- 1 file changed, 2 deletions(-) diff --git a/lib/types/index.d.ts b/lib/types/index.d.ts index b64f602fc..305c185f5 100644 --- a/lib/types/index.d.ts +++ b/lib/types/index.d.ts @@ -522,8 +522,6 @@ declare class PubNubCore< * @param parameters - Request configuration parameters. * * @returns Asynchronous delete messages response. - * - * @deprecated */ deleteMessages(parameters: PubNub.History.DeleteMessagesParameters): Promise; /** From 42ba1de12b0de7420ea0cf4e00eae29179084c21 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Sun, 15 Jun 2025 22:39:19 +0530 Subject: [PATCH 04/27] code snippets for documentation. A separate file for impot and initialisation. --- docs-snippets/access-manager.ts | 1 - docs-snippets/basic-usage/access-manager.ts | 4 +- docs-snippets/basic-usage/app-context.ts | 22 ++- docs-snippets/basic-usage/channel-groups.ts | 6 +- .../basic-usage/download-file-web.ts | 24 +++ docs-snippets/basic-usage/event-listener.ts | 10 +- docs-snippets/basic-usage/file-sharing.ts | 92 +++++++++++ docs-snippets/basic-usage/message-actions.ts | 57 +++++++ .../basic-usage/message-persistence.ts | 3 +- docs-snippets/basic-usage/miscellaneous.ts | 62 +++++++ docs-snippets/basic-usage/mobile-push.ts | 155 +++++++++--------- docs-snippets/basic-usage/presence.ts | 61 ++++--- .../basic-usage/publish-subscribe.ts | 140 +++++++++------- docs-snippets/event-listener.ts | 4 +- docs-snippets/file-sharing.ts | 35 ++++ docs-snippets/import-pubnub.ts | 16 ++ docs-snippets/message-persistence.ts | 79 +++++---- docs-snippets/mobile-push.ts | 1 - docs-snippets/publish-subscribe.ts | 89 +++++++++- docs-snippets/tsconfig.json | 6 +- 20 files changed, 623 insertions(+), 244 deletions(-) create mode 100644 docs-snippets/basic-usage/download-file-web.ts create mode 100644 docs-snippets/basic-usage/file-sharing.ts create mode 100644 docs-snippets/basic-usage/message-actions.ts create mode 100644 docs-snippets/basic-usage/miscellaneous.ts create mode 100644 docs-snippets/file-sharing.ts create mode 100644 docs-snippets/import-pubnub.ts diff --git a/docs-snippets/access-manager.ts b/docs-snippets/access-manager.ts index ac67e2035..347d4548c 100644 --- a/docs-snippets/access-manager.ts +++ b/docs-snippets/access-manager.ts @@ -1,6 +1,5 @@ import PubNub from '../lib/types'; -// Initialize PubNub with demo keys const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', diff --git a/docs-snippets/basic-usage/access-manager.ts b/docs-snippets/basic-usage/access-manager.ts index 448822d87..a521e4b46 100644 --- a/docs-snippets/basic-usage/access-manager.ts +++ b/docs-snippets/basic-usage/access-manager.ts @@ -1,14 +1,12 @@ import PubNub from '../../lib/types'; -// snippet.accessManagerBasicUsage -// import PubNub -// Initialize PubNub with demo keys const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId' }); +// snippet.accessManagerBasicUsage // Function to use grantToken method async function grantAccessToken() { try { diff --git a/docs-snippets/basic-usage/app-context.ts b/docs-snippets/basic-usage/app-context.ts index edd805edd..da411a484 100644 --- a/docs-snippets/basic-usage/app-context.ts +++ b/docs-snippets/basic-usage/app-context.ts @@ -1,14 +1,14 @@ import PubNub from '../../lib/types'; -// snippet.getAllUUIDMetadataBasicUsage -// import PubNub -// Initialize PubNub with demo keys + const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId' }); + // snippet.getAllUUIDMetadataBasicUsage // Function to get all UUID metadata +// to get some data in response, add user metadata using setUUIDMetadata method async function getAllUUIDMetadata() { try { const response = await pubnub.objects.getAllUUIDMetadata(); @@ -23,7 +23,7 @@ getAllUUIDMetadata(); // snippet.end // snippet.getUUIDMetadataBasicUsage -// Using UUID from the config +// Using UUID from the config - default when uuid is not passed in the method try { const response = await pubnub.objects.getUUIDMetadata(); console.log(`getUUIDMetadata response: ${response}`); @@ -43,7 +43,7 @@ try { // snippet.end // snippet.setUUIDMetadataBasicUsage -// Using UUID from the config +// Using UUID from the config - default when uuid is not passed in the method try { const response = await pubnub.objects.setUUIDMetadata({ data: { @@ -60,6 +60,7 @@ try { uuid: "myUuid", data: {}, }); + console.log(`setUUIDMetadata response: ${response}`); } catch (status) { console.log(`setUUIDMetadata failed with error: ${status}`); } @@ -67,7 +68,7 @@ try { // snippet.end // snippet.removeUUIDMetadataBasicUsage -// Using UUID from the config +// Using UUID from the config - default when uuid is not passed in the method try { const response = await pubnub.objects.removeUUIDMetadata(); } catch (status) { @@ -85,7 +86,7 @@ try { // snippet.end // snippet.getAllChannelMetadataBasicUsage -// Get the total number of channels +// Get the total number of channels included in the response. try { const response = await pubnub.objects.getAllChannelMetadata({ include: { @@ -96,11 +97,12 @@ try { console.log(`getAllChannelMetadata failed with error: ${status}`); } -// Get all channels that have IDs starting with "pro." +// Get all channels with the filter option. To get all channel which has Id ending 'Team'. try { const response = await pubnub.objects.getAllChannelMetadata({ filter: 'name LIKE "*Team"', }); + console.log(`getAllChannelMetadata response: ${response}`); } catch (status) { console.log(`getAllChannelMetadata failed with error: ${status}`); } @@ -204,6 +206,7 @@ try { channelFields: true, }, }); + console.log(`setMemberships response: ${response}`); } catch (status) { console.log(`setMemberships failed with error: ${status}`); } @@ -238,6 +241,7 @@ try { UUIDFields: true, }, }); + console.log(`getChannelMembers response: ${response}`); } catch (status) { console.log(`getChannelMembers failed with error: ${status}`); } @@ -248,6 +252,7 @@ try { channel: "myChannel", filter: 'description LIKE "*admin*"', }); + console.log(`getChannelMembers response: ${response}`); } catch (status) { console.log(`getChannelMembers failed with error: ${status}`); } @@ -263,6 +268,7 @@ try { { id: "uuid-3", custom: { role: "Super Admin" } }, ], }); + console.log(`setChannelMembers response: ${response}`); } catch (status) { console.log(`setChannelMembers failed with error: ${status}`); } diff --git a/docs-snippets/basic-usage/channel-groups.ts b/docs-snippets/basic-usage/channel-groups.ts index 9b8f83c81..f53487136 100644 --- a/docs-snippets/basic-usage/channel-groups.ts +++ b/docs-snippets/basic-usage/channel-groups.ts @@ -1,13 +1,12 @@ import PubNub from '../../lib/types'; -// snippet.addChannelsToGroupBasicUsage -// Initialize PubNub with demo keys const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId' }); +// snippet.addChannelsToGroupBasicUsage // Function to add channels to a channel group async function addChannelsToGroup() { try { @@ -27,11 +26,12 @@ addChannelsToGroup(); // snippet.listChannelsInGroupBasicUsage // assuming an intialized PubNub instance already exists +// to get some data in response, first add some channels to the group using addChannels() method. try { const response = await pubnub.channelGroups.listChannels({ channelGroup: "myChannelGroup", }); - console.log("Listing push channels for the device"); + console.log(`Listing push channels for the device: ${response}`); response.channels.forEach((channel: string) => { console.log(channel); }); diff --git a/docs-snippets/basic-usage/download-file-web.ts b/docs-snippets/basic-usage/download-file-web.ts new file mode 100644 index 000000000..0c1ec8eb9 --- /dev/null +++ b/docs-snippets/basic-usage/download-file-web.ts @@ -0,0 +1,24 @@ +import PubNub from '../../src/web/index'; + +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId', +}); + +// snippet.downloadFileWebBasicUsage +// In browser +// download the intended file +const file = await pubnub.downloadFile({ + channel: 'my_channel', + id: '...', + name: 'cat_picture.jpg', +}); + +// have proper html element to display the file +const myImageTag = document.createElement('img'); +myImageTag.src = URL.createObjectURL(await file.toFile()); + +// attach the file content to the html element +document.body.appendChild(myImageTag); +// snippet.end diff --git a/docs-snippets/basic-usage/event-listener.ts b/docs-snippets/basic-usage/event-listener.ts index 62cfc95a7..2391955f2 100644 --- a/docs-snippets/basic-usage/event-listener.ts +++ b/docs-snippets/basic-usage/event-listener.ts @@ -1,13 +1,12 @@ import PubNub from '../../lib/types'; -// snippet.eventListenerBasicUsage -// Initialize PubNub with demo keys const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId', }); +// snippet.eventListenerBasicUsage // create a subscription from a channel entity const channel = pubnub.channel('channel_1') const subscription1 = channel.subscription({ receivePresenceEvents: true }); @@ -28,9 +27,9 @@ subscription1.addListener({ presence: (p) => { console.log('Presence event', p) }, }); -// add event-specific message reactions listener +// add event-specific message actions listener subscriptionSet1.onMessageAction = (p) => { - console.log('Message reaction event:', p); + console.log('Message action event:', p); }; subscription1.subscribe(); @@ -42,4 +41,5 @@ subscriptionSet1.subscribe(); pubnub.addListener({ status: (s) => {console.log('Status', s.category) } }); -// snippet.end \ No newline at end of file +// snippet.end + diff --git a/docs-snippets/basic-usage/file-sharing.ts b/docs-snippets/basic-usage/file-sharing.ts new file mode 100644 index 000000000..02a238371 --- /dev/null +++ b/docs-snippets/basic-usage/file-sharing.ts @@ -0,0 +1,92 @@ +import PubNub from '../../lib/types'; +import fs from 'fs'; + +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId', +}); + +// snippet.sendFileBasicUsage +// Function to send a file to a channel +async function sendFileToChannel() { + try { + const myFile = fs.createReadStream('./cat_picture.jpg'); + + const response = await pubnub.sendFile({ + channel: 'my_channel', + file: { stream: myFile, name: 'cat_picture.jpg', mimeType: 'image/jpeg' }, + customMessageType: 'file-message', + }); + + console.log(`File sent successfully: ${response}`); + } catch (error) { + console.log(`Error sending file: ${error}`); + } +} + +// Execute the function to send the file +sendFileToChannel(); +// snippet.end + +// snippet.listFilesBasicUsage +try { + const response = await pubnub.listFiles({ channel: 'my_channel' }); + console.log(`Files listed successfully: ${response}`); +} catch (error) { + console.log(`Error listing files: ${error}`); +} +// snippet.end + +// snippet.getFileUrlBasicUsage +const response = pubnub.getFileUrl({ channel: 'my_channel', id: '...', name: '...' }); +// snippet.end + +// snippet.downloadFileNodeBasicUsage +// In Node.js using streams: +// import fs from 'fs' + +const downloadFileResponse = await pubnub.downloadFile({ + channel: 'my_channel', + id: '...', + name: 'cat_picture.jpg', +}); + +const output = fs.createWriteStream('./cat_picture.jpg'); +const fileStream = await downloadFileResponse.toStream(); + +fileStream.pipe(output); + +output.once('end', () => { + console.log('File saved to ./cat_picture.jpg'); +}); +// snippet.end + +// snippet.downloadFileReactNativeBasicUsage +// in React and React Native +const file = await pubnub.downloadFile({ + channel: 'awesomeChannel', + id: 'imageId', + name: 'cat_picture.jpg' +}); + +let fileContent = await file.toBlob(); +// snippet.end + +// snippet.deleteFileBasicUsage +const deleteFileResponse = await pubnub.deleteFile({ + channel: "my_channel", + id: "...", + name: "cat_picture.jpg", +}); +// snippet.end + +// snippet.publishFileMessageBasicUsage +const fileMessageResponse = await pubnub.publishFile({ + channel: "my_channel", + fileId: "...", + fileName: "cat_picture.jpg", + message: { field: "value" }, + customMessageType: 'file-message', +}); +// snippet.end \ No newline at end of file diff --git a/docs-snippets/basic-usage/message-actions.ts b/docs-snippets/basic-usage/message-actions.ts new file mode 100644 index 000000000..7dc8b2d48 --- /dev/null +++ b/docs-snippets/basic-usage/message-actions.ts @@ -0,0 +1,57 @@ +import PubNub from '../../lib/types'; + +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId', +}); + +// snippet.addMessageActionBasicUsage +// first publish a message using publish() method to get the message timetoken +async function addReactionToMessage() { + try { + const response = await pubnub.addMessageAction({ + channel: 'channel_name', + messageTimetoken: 'replace_with_message_timetoken', // Replace with actual message timetoken + action: { + type: 'reaction', + value: 'smiley_face', + }, + }); + console.log(`Message reaction added successfully: ${response}`); + } catch (error) { + console.log(`Error adding reaction: ${error}`); + } +} + +// Execute the function to add a message action +addReactionToMessage(); +// snippet.end + +// snippet.removeMessageActionBasicUsage +try { + const response = await pubnub.removeMessageAction({ + channel: 'channel_name', + messageTimetoken: 'replace_with_message_timetoken', + actionTimetoken: 'replace_with_action_timetoken', + }); + console.log(`Message action removed successfully: ${response}`); +} catch (error) { + console.log(`Error removing message action: ${error}`); +} +// snippet.end + +// snippet.getMessageActionsBasicUsage +// to get some data in response, first publish a message and then add a message action using addMessageAction() method. +try { + const response = await pubnub.getMessageActions({ + channel: 'channel_name', + start: 'replace_with_start_timetoken', + end: 'replace_with_end_timetoken', + limit: 100, + }); + console.log(`Message actions retrieved successfully: ${response}`); +} catch (error) { + console.log(`Error retrieving message actions: ${error}`); +} +// snippet.end diff --git a/docs-snippets/basic-usage/message-persistence.ts b/docs-snippets/basic-usage/message-persistence.ts index e499ef6cd..465a00964 100644 --- a/docs-snippets/basic-usage/message-persistence.ts +++ b/docs-snippets/basic-usage/message-persistence.ts @@ -1,13 +1,12 @@ -// snippet.fetchMessagesBasicUsage import PubNub from '../../lib/types'; -// Initialize PubNub with demo keys const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId' }); +// snippet.fetchMessagesBasicUsage // Function to fetch message history async function fetchHistory() { try { diff --git a/docs-snippets/basic-usage/miscellaneous.ts b/docs-snippets/basic-usage/miscellaneous.ts new file mode 100644 index 000000000..bd1344332 --- /dev/null +++ b/docs-snippets/basic-usage/miscellaneous.ts @@ -0,0 +1,62 @@ +import PubNub from '../../lib/types'; +import fs from 'fs'; + +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId', + }); + +// snippet.encryptMessageBasicUsage +// Create a crypto module instance with AES-CBC encryption +const cryptoModule = PubNub.CryptoModule.aesCbcCryptoModule({ + cipherKey: "pubnubenigma" + }); + + // Function to encrypt a message + function encryptMessage() { + const msgContent = "This is the data I wish to encrypt."; + console.log(`Original Message: ${msgContent}`); + + // Encrypt the message + const encryptedMessage = cryptoModule.encrypt(JSON.stringify(msgContent)); + console.log(`Encrypted Message: ${encryptedMessage}`); + } + + // Execute the function to encrypt the message + encryptMessage(); +// snippet.end + +// snippet.encryptFileBasicUsage + +// Node.js example +// import fs from 'fs'; + +const fileBuffer = fs.readFileSync('./cat_picture.jpg'); + +const file = pubnub.File.create({ data: fileBuffer, name: 'cat_picture.jpg', mimeType: 'image/jpeg' }); + +const encryptedFile = await pubnub.encryptFile(file); +// snippet.end + +let encrypted = '..'; +// snippet.decryptBasicUsage +var decrypted = pubnub.decrypt(encrypted); // Pass the encrypted data as the first parameter in decrypt Method +// snippet.end + +// snippet.decryptFileBasicUsage + +const fileBufferData = fs.readFileSync('./cat_picture_encrypted.jpg'); + +const fileData = pubnub.File.create({ data: fileBuffer, name: 'cat_picture.jpg', mimeType: 'image/jpeg' }); + +const decryptedFile = await pubnub.decryptFile(fileData); +// snippet.end + +// snippet.setProxyBasicUsage +pubnub.setProxy({ + hostname: 'YOUR_HOSTNAME', + port: 8080, + protocol: 'YOUR_PROTOCOL' +}); +// snippet.end diff --git a/docs-snippets/basic-usage/mobile-push.ts b/docs-snippets/basic-usage/mobile-push.ts index b327e2dc4..297f64dbe 100644 --- a/docs-snippets/basic-usage/mobile-push.ts +++ b/docs-snippets/basic-usage/mobile-push.ts @@ -1,27 +1,27 @@ -// snippet.addDeciveToChannelBasicUsage import PubNub from '../../lib/types'; // Initialize PubNub with demo keys const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', - userId: 'myUniqueUserId' + userId: 'myUniqueUserId', }); +// snippet.addDeciveToChannelBasicUsage // Function to add a device to a channel for APNs2 async function addDeviceToChannelAPNs2() { try { const result = await pubnub.push.addChannels({ - channels: ["a", "b"], - device: "niceDevice", - pushGateway: "apns2", - environment: "production", - topic: "com.example.bundle_id" + channels: ['a', 'b'], + device: 'niceDevice', + pushGateway: 'apns2', + environment: 'production', + topic: 'com.example.bundle_id', }); - console.log("Operation done for APNs2!"); - console.log("Response:", result); + console.log('Operation done for APNs2!'); + console.log('Response:', result); } catch (error) { - console.log("Operation failed with error for APNs2:", error); + console.log('Operation failed with error for APNs2:', error); } } @@ -29,14 +29,14 @@ async function addDeviceToChannelAPNs2() { async function addDeviceToChannelFCM() { try { const result = await pubnub.push.addChannels({ - channels: ["a", "b"], - device: "niceDevice", - pushGateway: "gcm" + channels: ['a', 'b'], + device: 'niceDevice', + pushGateway: 'gcm', }); - console.log("Operation done for FCM!"); - console.log("Response:", result); + console.log('Operation done for FCM!'); + console.log('Response:', result); } catch (error) { - console.log("Operation failed with error for FCM:", error); + console.log('Operation failed with error for FCM:', error); } } @@ -49,65 +49,64 @@ addDeviceToChannelFCM(); // snippet.listChannelsForDeviceBasicUsage // for APNs2 try { - const response = await pubnub.push.listChannels({ - device: "niceDevice", - pushGateway: "apns2", - environment: "production", - topic: "com.example.bundle_id" - }); - console.log(`listing channels for device response: ${response}`); - response.channels.forEach((channel: string) => { - console.log(channel); - }); + const response = await pubnub.push.listChannels({ + device: 'niceDevice', + pushGateway: 'apns2', + environment: 'production', + topic: 'com.example.bundle_id', + }); + console.log(`listing channels for device response: ${response}`); + response.channels.forEach((channel: string) => { + console.log(channel); + }); } catch (status) { - console.log(`listing channels for device failed with error: ${status}`); + console.log(`listing channels for device failed with error: ${status}`); } // for FCM try { - const response = await pubnub.push.listChannels({ - device: "niceDevice", - pushGateway: "gcm" - }); - - console.log(`listing channels for device response: ${response}`); - - response.channels.forEach((channel: string) => { - console.log(channel); - }); + const response = await pubnub.push.listChannels({ + device: 'niceDevice', + pushGateway: 'gcm', + }); + + console.log(`listing channels for device response: ${response}`); + + response.channels.forEach((channel: string) => { + console.log(channel); + }); } catch (status) { - console.log(`listing channels for device failed with error: ${status}`); + console.log(`listing channels for device failed with error: ${status}`); } // snippet.end // snippet.removeDeviceFromChannelBasicUsage // for APNs2 try { - const response = await pubnub.push.removeChannels({ - channels: ["a", "b"], - device: "niceDevice", - pushGateway: "apns2", - environment: "production", - topic: "com.example.bundle_id" - }); - - console.log(`removing device from channel response: ${response}`); - + const response = await pubnub.push.removeChannels({ + channels: ['a', 'b'], + device: 'niceDevice', + pushGateway: 'apns2', + environment: 'production', + topic: 'com.example.bundle_id', + }); + + console.log(`removing device from channel response: ${response}`); } catch (status) { - console.log(`removing device from channel failed with error: ${status}`); + console.log(`removing device from channel failed with error: ${status}`); } // for FCM try { - const response = await pubnub.push.removeChannels({ - channels: ["a", "b"], - device: "niceDevice", - pushGateway: "gcm" - }); - - console.log(`removing device from channel response: ${response}`); + const response = await pubnub.push.removeChannels({ + channels: ['a', 'b'], + device: 'niceDevice', + pushGateway: 'gcm', + }); + + console.log(`removing device from channel response: ${response}`); } catch (status) { - console.log(`removing device from channel failed with error: ${status}`); + console.log(`removing device from channel failed with error: ${status}`); } // snippet.end @@ -115,45 +114,43 @@ try { // for APNs2 try { - const response = await pubnub.push.deleteDevice({ - device: "niceDevice", - pushGateway: "apns2", - environment: "production", - topic: "com.example.bundle_id" - }); - - console.log(`deleteDevice response: ${response}`); - + const response = await pubnub.push.deleteDevice({ + device: 'niceDevice', + pushGateway: 'apns2', + environment: 'production', + topic: 'com.example.bundle_id', + }); + + console.log(`deleteDevice response: ${response}`); } catch (status) { - console.log(`deleteDevice failed with error: ${status}`); + console.log(`deleteDevice failed with error: ${status}`); } // for FCM try { - const response = await pubnub.push.deleteDevice({ - device: "niceDevice", - pushGateway: "gcm" - }); - - console.log(`deleteDevice response: ${response}`); + const response = await pubnub.push.deleteDevice({ + device: 'niceDevice', + pushGateway: 'gcm', + }); + + console.log(`deleteDevice response: ${response}`); } catch (status) { - console.log(`deleteDevice failed with error: ${status}`); + console.log(`deleteDevice failed with error: ${status}`); } // snippet.end // snippet.buildNotificationPayloadBasicUsage -let builder = PubNub.notificationPayload('Chat invitation', - 'You have been invited to \'quiz\' chat'); +let builder = PubNub.notificationPayload('Chat invitation', "You have been invited to 'quiz' chat"); let messagePayload = builder.buildPayload(['apns2', 'fcm']); // add required fields to the payload const response = await pubnub.publish({ - message: messagePayload, - channel: 'chat-bot', + message: messagePayload, + channel: 'chat-bot', }); console.log(`publish response: ${response}`); -// snippet.end \ No newline at end of file +// snippet.end diff --git a/docs-snippets/basic-usage/presence.ts b/docs-snippets/basic-usage/presence.ts index b1eaf5c3f..c03cff11c 100644 --- a/docs-snippets/basic-usage/presence.ts +++ b/docs-snippets/basic-usage/presence.ts @@ -1,37 +1,36 @@ -// snippet.hereNowBasicUsage import PubNub from '../../lib/types'; -// Initialize PubNub with demo keys const pubnub = new PubNub({ - publishKey: 'demo', - subscribeKey: 'demo', - userId: 'myUniqueUserId' - }); - - // Function to get presence information for a channel - async function getHereNow() { - try { - const result = await pubnub.hereNow({ - channels: ["ch1"], - channelGroups: ["cg1"], - includeUUIDs: true, - includeState: true, - }); - console.log(`Here Now Result: ${result}`); - } catch (error) { - console.log(`Here Now failed with error: ${error}`); - } + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId', +}); + +// snippet.hereNowBasicUsage +// Function to get presence information for a channel +async function getHereNow() { + try { + const result = await pubnub.hereNow({ + channels: ['ch1'], + channelGroups: ['cg1'], + includeUUIDs: true, + includeState: true, + }); + console.log(`Here Now Result: ${result}`); + } catch (error) { + console.log(`Here Now failed with error: ${error}`); } - - // Execute the function to get presence information - getHereNow(); +} + +// Execute the function to get presence information +getHereNow(); // snippet.end // snippet.whereNowBasicUsage try { const response = await pubnub.whereNow({ - uuid: "uuid", + uuid: 'uuid', }); } catch (status) { console.log(status); @@ -41,9 +40,9 @@ try { // snippet.setStateBasicUsage try { const response = await pubnub.setState({ - state: { status: "online" }, - channels: ["ch1"], - channelGroups: ["cg1"], + state: { status: 'online' }, + channels: ['ch1'], + channelGroups: ['cg1'], }); } catch (status) { console.log(status); @@ -53,11 +52,11 @@ try { // snippet.getStateBasicUsage try { const response = await pubnub.getState({ - uuid: "uuid", - channels: ["ch1"], - channelGroups: ["cg1"], + uuid: 'uuid', + channels: ['ch1'], + channelGroups: ['cg1'], }); } catch (status) { console.log(status); } -// snippet.end \ No newline at end of file +// snippet.end diff --git a/docs-snippets/basic-usage/publish-subscribe.ts b/docs-snippets/basic-usage/publish-subscribe.ts index 7ec473e3a..035ee2d75 100644 --- a/docs-snippets/basic-usage/publish-subscribe.ts +++ b/docs-snippets/basic-usage/publish-subscribe.ts @@ -1,13 +1,12 @@ import PubNub from '../../lib/types'; -// snippet.publishBasicUsage -// Initialize PubNub with demo keys const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', userId: 'myUniqueUserId', }); +// snippet.publishBasicUsage // Function to publish a message async function publishMessage() { try { @@ -30,78 +29,75 @@ publishMessage(); // snippet.end // snippet.signalBasicUsage -// Initialize PubNub with demo keys - try { +try { const response = await pubnub.signal({ - message: "hello", - channel: "foo", - customMessageType: "text-message", + message: 'hello', + channel: 'foo', + customMessageType: 'text-message', }); - console.log(response); - } catch (status) { - // handle error - console.log(status); - } - // snippet.end - - // snippet.fireBasicUsage + console.log(`signal response: ${response}`); +} catch (status) { + // handle error + console.log(`signal failed with error: ${status}`); +} +// snippet.end + +// snippet.fireBasicUsage // Initialize PubNub with your keys - try { - const response = await pubnub.fire({ - message: { - such: "object", - }, - channel: "my_channel", - sendByPost: false, // true to send via post - meta: { - cool: "meta", - }, // fire extra meta with the request - }); - - console.log(`message published with timetoken: ${response.timetoken}`); - } catch (status) { - // handle error - console.log(status); - } - // snippet.end +try { + const response = await pubnub.fire({ + message: { + such: 'object', + }, + channel: 'my_channel', + sendByPost: false, // true to send via post + meta: { + cool: 'meta', + }, // fire extra meta with the request + }); - // snippet.createChannelBasicUsage -// Initialize PubNub with demo keys - const channel = pubnub.channel('my_channel'); - // snippet.end + console.log(`message published with timetoken: ${response.timetoken}`); +} catch (status) { + // handle error + console.log(`fire failed with error: ${status}`); +} +// snippet.end +// snippet.createChannelBasicUsage +const channel = pubnub.channel('my_channel'); +// snippet.end - // snippet.createChannelGroupBasicUsage +// snippet.createChannelGroupBasicUsage // Initialize PubNub with demo keys - const channelGroup = pubnub.channelGroup('channelGroup_1'); - // snippet.end +const channelGroup = pubnub.channelGroup('channelGroup_1'); +// snippet.end - // snippet.createChannelMetadataBasicUsage +// snippet.createChannelMetadataBasicUsage // Initialize PubNub with demo keys - const channelMetadata = pubnub.channelMetadata('channel_1'); - // snippet.end +const channelMetadata = pubnub.channelMetadata('channel_1'); +// snippet.end // snippet.createUserMetadataBasicUsage // Initialize PubNub with demo keys - - const userMetadata = pubnub.userMetadata('user_meta1'); - // snippet.end - - // snippet.unsubscribeBasicUsage - // create a subscription from a channel entity - const channel1 = pubnub.channel('channel_1') - const subscription1 = channel1.subscription({ receivePresenceEvents: true }); - - // create a subscription set with multiple channels - const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }); - - subscription1.subscribe(); - subscriptionSet1.subscribe(); - - subscription1.unsubscribe(); - subscriptionSet1.unsubscribe(); - // snippet.end + +const userMetadata = pubnub.userMetadata('user_meta1'); +// snippet.end + +// snippet.unsubscribeBasicUsage +// create a subscription from a channel entity +const channel1 = pubnub.channel('channel_1'); +const subscription1 = channel1.subscription({ receivePresenceEvents: true }); + +// create a subscription set with multiple channels +const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }); + +subscription1.subscribe(); +subscriptionSet1.subscribe(); + +subscription1.unsubscribe(); +subscriptionSet1.unsubscribe(); +// snippet.end // snippet.unsubscribeAllBasicUsage // create a subscription set with multiple channels @@ -109,10 +105,28 @@ const subscriptionSet = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }); subscriptionSet.subscribe(); // create a subscription from a channel entity -const channelGroup1 = pubnub.channelGroup('channelGroup_1') +const channelGroup1 = pubnub.channelGroup('channelGroup_1'); const groupSubscription1 = channelGroup1.subscription({ receivePresenceEvents: true }); groupSubscription1.subscribe(); // unsubscribe all active subscriptions pubnub.unsubscribeAll(); -// snippet.end \ No newline at end of file +// snippet.end + + +// *********** OLD SYNTAX *********** +// snippet.OLDsubscribeBasicUsage +pubnub.subscribe({ + channels: ["my_channel"], +}); +// snippet.end + +// snippet.OLDUnsubscribeBasicUsage +pubnub.unsubscribe({ + channels: ["my_channel"], +}); +// snippet.end + +// snippet.OLDUnsubscribeAllBasicUsage +pubnub.unsubscribeAll(); +// snippet.end \ No newline at end of file diff --git a/docs-snippets/event-listener.ts b/docs-snippets/event-listener.ts index f6c425d23..9a7fa6d93 100644 --- a/docs-snippets/event-listener.ts +++ b/docs-snippets/event-listener.ts @@ -1,7 +1,5 @@ import PubNub from '../lib/types'; - -// Initialize PubNub with demo keys const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', @@ -28,4 +26,4 @@ subscription.onFile = (fileEvent) => { console.log("File event: ", fileEvent); } pubnub.addListener({ status: (s) => s.category }) -// snippet.end \ No newline at end of file +// snippet.end diff --git a/docs-snippets/file-sharing.ts b/docs-snippets/file-sharing.ts new file mode 100644 index 000000000..afbad9a7e --- /dev/null +++ b/docs-snippets/file-sharing.ts @@ -0,0 +1,35 @@ +import PubNub from '../lib/types'; + +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId', +}); + +// snippet.sendFileCustomCipherKey +// in Node.js +import fs from 'fs'; + +try { + const myFile = fs.readFileSync('./cat_picture.jpg'); + + const response = await pubnub.sendFile({ + channel: 'my_channel', + message: 'Look at this picture!', + file: { data: myFile, name: 'cat_picture.jpg', mimeType: 'application/json' }, + cipherKey: 'myCipherKey', + }); + console.log(`File sent successfully: ${response}`); +} catch (error) { + console.error('Error sending file:', error); +} +// snippet.end + +// snippet.downloadFileCustomCipherKey +const file = await pubnub.downloadFile({ + channel: "my_channel", + id: "...", + name: "cat_picture.jpg", + cipherKey: "myCipherKey", +}); +// snippet.end \ No newline at end of file diff --git a/docs-snippets/import-pubnub.ts b/docs-snippets/import-pubnub.ts new file mode 100644 index 000000000..1d502f053 --- /dev/null +++ b/docs-snippets/import-pubnub.ts @@ -0,0 +1,16 @@ +// snippet.importPubNub +import PubNub from 'pubnub'; +// snippet.end + +// snippet.importFS +import fs from 'fs'; +// snippet.end + +// snippet.PubNubinitBasicUsage +// Initialize PubNub with your keys +const pubnub = new PubNub({ + publishKey: 'YOUR_PUBLISH_KEY', + subscribeKey: 'YOUR_SUBSCRIBE_KEY', + userId: 'YOUR_USER_ID', + }); +// snippet.end diff --git a/docs-snippets/message-persistence.ts b/docs-snippets/message-persistence.ts index a538b24a5..57675b49a 100644 --- a/docs-snippets/message-persistence.ts +++ b/docs-snippets/message-persistence.ts @@ -1,56 +1,51 @@ import PubNub from '../lib/types'; -// Initialize PubNub with demo keys const pubnub = new PubNub({ - publishKey: 'demo', - subscribeKey: 'demo', - userId: 'myUniqueUserId' - }); + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId', +}); // snippet.fetchMessagesWithMetaActions - try { - const response = await pubnub.fetchMessages( - { - channels: ['my_channel'], - stringifiedTimeToken: true, - includeMeta: true, - includeMessageActions: true, - includeCustomMessageType: true - }); - console.log(`fetch messages response: ${response}`); - } catch (status) { - console.log(`fetch messages failed with error: ${status}`); - } +try { + const response = await pubnub.fetchMessages({ + channels: ['my_channel'], + stringifiedTimeToken: true, + includeMeta: true, + includeMessageActions: true, + includeCustomMessageType: true, + }); + console.log(`fetch messages response: ${response}`); +} catch (status) { + console.log(`fetch messages failed with error: ${status}`); +} // snippet.end - + // snippet.deleteSpecificMessages - try { - const response = await pubnub.deleteMessages( - { - channel: 'ch1', - start: '15526611838554309', - end: '15526611838554310' - }); - console.log(`delete messages response: ${response}`); - } catch (error) { - console.log(`delete messages failed with error: ${error}`); - } +try { + const response = await pubnub.deleteMessages({ + channel: 'ch1', + start: 'replace-with-start-timetoken', + end: 'replace-with-end-timetoken', + }); + console.log(`delete messages response: ${response}`); +} catch (error) { + console.log(`delete messages failed with error: ${error}`); +} // snippet.end // snippet.messageCountTimetokensForChannels try { - const response = await pubnub.messageCounts({ - channels: ['ch1', 'ch2', 'ch3'], - channelTimetokens: [ - 'replace-with-channel-timetoken-ch1', // timetoken for channel ch1 - 'replace-with-channel-timetoken-ch2', // timetoken for channel ch2 - 'replace-with-channel-timetoken-ch3', // timetoken for channel ch3 - ], - }); - console.log(`message count response: ${response}`); + const response = await pubnub.messageCounts({ + channels: ['ch1', 'ch2', 'ch3'], + channelTimetokens: [ + 'replace-with-channel-timetoken-ch1', // timetoken for channel ch1 + 'replace-with-channel-timetoken-ch2', // timetoken for channel ch2 + 'replace-with-channel-timetoken-ch3', // timetoken for channel ch3 + ], + }); + console.log(`message count response: ${response}`); } catch (status) { - console.log(`message count failed with error: ${status}`); + console.log(`message count failed with error: ${status}`); } // snippet.end - - diff --git a/docs-snippets/mobile-push.ts b/docs-snippets/mobile-push.ts index 463a636fb..d683402b5 100644 --- a/docs-snippets/mobile-push.ts +++ b/docs-snippets/mobile-push.ts @@ -1,6 +1,5 @@ import PubNub from '../lib/types'; -// Initialize PubNub with demo keys const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', diff --git a/docs-snippets/publish-subscribe.ts b/docs-snippets/publish-subscribe.ts index 187200e4f..686b7301c 100644 --- a/docs-snippets/publish-subscribe.ts +++ b/docs-snippets/publish-subscribe.ts @@ -6,7 +6,6 @@ const pubnub = new PubNub({ userId: 'userId', }); - // snippet.publishJsonSerialisedMessage const newMessage = { text: 'Hi There!', @@ -71,7 +70,7 @@ const newMessage = { console.log(status); // {error: true, operation: "PNPublishOperation", statusCode: 400, errorData: Error, category: "PNBadRequestCategory"} } // snippet.end - + // *********** Compilation Error due to wrong code ***************** // // snippet.publishUnsuccessfulMissingChannel // try { // const result = await pubnub.publish({ @@ -112,4 +111,90 @@ subscriptionSet.unsubscribe() // snippet.ubsubscribeAll pubnub.unsubscribeAll() +// snippet.end + +// *************** OLD SUBSCRIBE SYNTAX *************** +// snippet.OLDsubscribeMultipleChannels +pubnub.subscribe({ + channels: ['my_channel_1', 'my_channel_2', 'my_channel_3'] +}); +// snippet.end + +// snippet.OLDsubscribeWithPresence +pubnub.subscribe({ + channels: ["my_channel"], + withPresence: true, +}); +// snippet.end + +// snippet.OLDsubscribeWithWildCardChannels +pubnub.subscribe({ + channels: ["ab.*"], +}); +// snippet.end + +// snippet.OLDsubscribeWithState +pubnub.addListener({ + status: async (statusEvent) => { + if (statusEvent.category === "PNConnectedCategory") { + try { + await pubnub.setState({ + state: { + some: "state", + }, + }); + } catch (status) { + // handle setState error + } + } + }, + message: (messageEvent) => { + // handle message + }, + presence: (presenceEvent) => { + // handle presence + }, +}); + +pubnub.subscribe({ + channels: ["ch1", "ch2", "ch3"], +}); +// snippet.end + +// snippet.OLDsubscribeChannelGroup +pubnub.subscribe({ + channelGroups: ["my_channelGroup"], +}); +// snippet.end + +// snippet.OLDsubscribeChannelGroupWithPresence +pubnub.subscribe({ + channelGroups: ["family"], + withPresence: true, +}); +// snippet.end + +// snippet.OLDsubscribeMultipleChannelGroup +pubnub.subscribe({ + channelGroups: ["my_channelGroup1", "my_channelGroup2", "my_channelGroup3"], +}); +// snippet.end + +// snippet.OLDsubscribeChannelGroupAndChannels +pubnub.subscribe({ + channels: ["my_channel"], + channelGroups: ["my_channelGroup"], +}); +// snippet.end + +// snippet.OLDUnsubscribeMultipleChannels +pubnub.unsubscribe({ + channels: ["chan1", "chan2", "chan3"], +}); +// snippet.end + +// snippet.OLDUnsubscribeMultipleChannelGroup +pubnub.unsubscribe({ + channelGroups: ["demo_group1", "demo_group2"], +}); // snippet.end \ No newline at end of file diff --git a/docs-snippets/tsconfig.json b/docs-snippets/tsconfig.json index 439175763..4dee2f901 100644 --- a/docs-snippets/tsconfig.json +++ b/docs-snippets/tsconfig.json @@ -9,8 +9,12 @@ "skipLibCheck": true, "resolveJsonModule": true, "esModuleInterop": true, - + "allowSyntheticDefaultImports": true, + "moduleResolution": "node", "baseUrl": "..", + "paths": { + "pubnub": ["lib/node/index.js"] + } }, "include": [ "**/*.ts" From 92af28f66a346ab6952330e93e6077b340c0cc04 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 16 Jun 2025 14:56:25 +0530 Subject: [PATCH 05/27] configuration code snippets --- docs-snippets/basic-usage/configuration.ts | 34 ++++++++++++++ docs-snippets/configuration.ts | 54 ++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 docs-snippets/basic-usage/configuration.ts create mode 100644 docs-snippets/configuration.ts diff --git a/docs-snippets/basic-usage/configuration.ts b/docs-snippets/basic-usage/configuration.ts new file mode 100644 index 000000000..31d5c2d8a --- /dev/null +++ b/docs-snippets/basic-usage/configuration.ts @@ -0,0 +1,34 @@ +import PubNub from '../../src/web/index'; + +// snippet.configurationBasicUsageSubscriptionWorkerUrl +var pubnub = new PubNub({ + subscribeKey: "demo", + publishKey: "demo", + userId: "unique-user-id", + // using PubNub JS SDK v9.6.0, make sure the versions match + subscriptionWorkerUrl: 'https://www.my-domain.com/static/js/pubnub.worker.9.6.0.js' + }); +// snippet.end + +// snippet.setAuthKeyBasicUsage +pubnub.setAuthKey("my_authkey"); +// snippet.end + +// snippet.setFilterExpressionBasicUsage +pubnub.setFilterExpression("such=wow"); +// snippet.end + +// snippet.configurationBasicUsage +// Initialize PubNub with your keys +var pubnub = new PubNub({ + subscribeKey: 'YOUR_SUBSCRIBE_KEY', + publishKey: 'YOUR_PUBLISH_KEY', + userId: 'YOUR_USER_ID', + cryptoModule: PubNub.CryptoModule?.aesCbcCryptoModule({ cipherKey: 'YOUR_CIPHER_KEY' }), + authKey: 'accessMangerToken', + logLevel: PubNub.LogLevel.Debug, + ssl: true, + presenceTimeout: 130 + }); + +// snippet.end \ No newline at end of file diff --git a/docs-snippets/configuration.ts b/docs-snippets/configuration.ts new file mode 100644 index 000000000..d2b7e0772 --- /dev/null +++ b/docs-snippets/configuration.ts @@ -0,0 +1,54 @@ +import PubNub from '../lib/types'; + +// snippet.configurationCryptoModule +// encrypts using 256-bit AES-CBC cipher (recommended) +// decrypts data encrypted with the legacy and the 256 bit AES-CBC ciphers +var pubnub = new PubNub({ + subscribeKey: 'YOUR_SUBSCRIBE_KEY', + userId: 'YOUR_USER_ID', + cryptoModule: PubNub.CryptoModule.aesCbcCryptoModule({cipherKey: 'pubnubenigma'}) + }); + + // encrypts with 128-bit cipher key entropy (legacy) + // decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers +var pubnub = new PubNub({ + subscribeKey: 'YOUR_SUBSCRIBE_KEY', + userId: 'YOUR_USER_ID', + cryptoModule: PubNub.CryptoModule.legacyCryptoModule({cipherKey: 'pubnubenigma'}) + }); +// snippet.end + +// snippet.configurationServerOpertaion +var pubnub = new PubNub({ + subscribeKey: "mySubscribeKey", + publishKey: "myPublishKey", + userId: "myUniqueUserId", + secretKey: "secretKey", + heartbeatInterval: 0 +}); +// snippet.end + +// snippet.configurationRealOnlyClient +// Initialize for Read Only Client + +var pubnub = new PubNub({ + subscribeKey: "mySubscribeKey", + userId: "myUniqueUserId" +}); +// snippet.end + +// snippet.configurationSSLEnabled +var pubnub = new PubNub({ + subscribeKey: "mySubscribeKey", + publishKey: "myPublishKey", + cryptoModule: PubNub.CryptoModule.aesCbcCryptoModule({cipherKey: 'pubnubenigma'}), + authKey: "myAuthKey", + logLevel: PubNub.LogLevel.Debug, + userId: "myUniqueUserId", + ssl: true +}); +// snippet.end + +// snippet.generateUUIDdeprected +var uuid = PubNub.generateUUID(); +// snippet.end From 3146b47937d848d5d427ea3a057942882dfe983e Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 16 Jun 2025 14:57:03 +0530 Subject: [PATCH 06/27] script to compile check the code snippets --- .github/workflows/run-tests.yml | 2 ++ package.json | 1 + 2 files changed, 3 insertions(+) diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 5432edf8b..8819df0ce 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -50,6 +50,8 @@ jobs: run: | npm install npm run ${{ matrix.env }} + - name: Test docs snippets syntax + run: npm run test:snippets - name: Cancel workflow runs for commit on error if: failure() uses: ./.github/.release/actions/actions/utils/fast-jobs-failure diff --git a/package.json b/package.json index 8d8234d22..b153671bd 100644 --- a/package.json +++ b/package.json @@ -13,6 +13,7 @@ "test:node": "TS_NODE_PROJECT='./tsconfig.json' mocha --project tsconfig.mocha.json", "clean": "rimraf lib dist upload", "lint": "eslint \"src/**/*\" --config .eslintrc.cjs", + "test:snippets": "tsc --project docs-snippets/tsconfig.json --noEmit", "ci": "npm run clean && npm run build && npm run lint && npm run test", "ci:web": "npm run clean && npm run build:web && npm run lint && npm run test:web", "ci:node": "npm run clean && npm run build:node && npm run lint && npm run test:node", From c29a0215edab423d5efabf5904ea17c2513f9b0e Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 16 Jun 2025 15:10:37 +0530 Subject: [PATCH 07/27] fix: snippet compilation for lowest node version and build generated before snippet compilation happens --- .github/workflows/run-tests.yml | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 8819df0ce..c1b6bbffe 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -51,6 +51,7 @@ jobs: npm install npm run ${{ matrix.env }} - name: Test docs snippets syntax + if: matrix.node == '18.18.0' && matrix.env == 'ci:node' run: npm run test:snippets - name: Cancel workflow runs for commit on error if: failure() From 83fc5841bf6be449a898f4b62e4c99b09bcf53ca Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Thu, 19 Jun 2025 15:40:05 +0530 Subject: [PATCH 08/27] added missing iterativelyUpdateExistingMetadata --- docs-snippets/app-context.ts | 59 ++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 docs-snippets/app-context.ts diff --git a/docs-snippets/app-context.ts b/docs-snippets/app-context.ts new file mode 100644 index 000000000..a8c33e626 --- /dev/null +++ b/docs-snippets/app-context.ts @@ -0,0 +1,59 @@ +import PubNub from '../lib/types'; + +const pubnub = new PubNub({ + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId' + }); + +// snippet.iterativelyUpdateExistingMetadata +const channel = 'team.red'; +const name = 'Red Team'; +const description = 'The channel for Red team.'; +const customField = { visible: 'team' }; + +// Function to set and then update channel metadata +const updateChannelMetadata = async () => { + try { + let response = await pubnub.objects.setChannelMetadata({ + channel: channel, + data: { + name: name, + description: description, + custom: customField + } + }); + console.log('The channel has been created with name and description.\n'); + + // Fetch current object with custom fields + let currentObjectResponse = await pubnub.objects.getChannelMetadata({ + channel: channel, + include: { + customFields: true + } + }); + let currentObject = currentObjectResponse.data; + + // Initialize the custom field object + let custom = currentObject.custom || {}; + + // Add or update the field + custom['edit'] = 'admin'; + + // Writing the updated object back to the server + let setResponse = await pubnub.objects.setChannelMetadata({ + channel: channel, + data: { + name: currentObject.name || '', + description: currentObject.description || '', + custom: custom + } + }); + console.log(`Object has been updated ${setResponse}`); + } catch (error) { + console.error(error); + } +}; + +updateChannelMetadata(); +// snippet.end \ No newline at end of file From d2c73dbc7c0f0b5cd8798d52ebd7c1a628f6f197 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Thu, 19 Jun 2025 16:03:02 +0530 Subject: [PATCH 09/27] example with promises syntax demo --- docs-snippets/basic-usage/presence.ts | 14 ++++++++++++++ docs-snippets/presence.ts | 9 ++++++--- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/docs-snippets/basic-usage/presence.ts b/docs-snippets/basic-usage/presence.ts index c03cff11c..0fa63c7e3 100644 --- a/docs-snippets/basic-usage/presence.ts +++ b/docs-snippets/basic-usage/presence.ts @@ -60,3 +60,17 @@ try { console.log(status); } // snippet.end + + +// snippet.basicUsageWithPromises +pubnub.hereNow({ + channels: ["ch1"], + channelGroups : ["cg1"], + includeUUIDs: true, + includeState: true +}).then((response) => { + console.log(response) +}).catch((error) => { + console.log(error) +}); +// snippet.end \ No newline at end of file diff --git a/docs-snippets/presence.ts b/docs-snippets/presence.ts index 7ffc9f452..2edc08b5e 100644 --- a/docs-snippets/presence.ts +++ b/docs-snippets/presence.ts @@ -12,8 +12,9 @@ try { channels: ["my_channel"], includeState: true, }); + console.log(`hereNow response: ${response}`); } catch (status) { - console.log(status); + console.log(`hereNow failed with error: ${status}`); } // snippet.end @@ -23,8 +24,9 @@ try { channels: ["my_channel"], includeUUIDs: false, }); + console.log(`hereNow response: ${response}`); } catch (status) { - console.log(status); + console.log(`hereNow failed with error: ${status}`); } // snippet.end @@ -34,7 +36,8 @@ try { const response = await pubnub.hereNow({ channelGroups: ["my_channel_group"] }); + console.log(`hereNow response: ${response}`); } catch (status) { - console.log(status); + console.log(`hereNow failed with error: ${status}`); } // snippet.end \ No newline at end of file From e23870d2b789a39e5bdc755120a85d43a30d7d75 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Thu, 19 Jun 2025 16:38:48 +0530 Subject: [PATCH 10/27] missing SubscriptionSet subscribe() basic usage example --- docs-snippets/basic-usage/publish-subscribe.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/docs-snippets/basic-usage/publish-subscribe.ts b/docs-snippets/basic-usage/publish-subscribe.ts index 035ee2d75..e74896dd8 100644 --- a/docs-snippets/basic-usage/publish-subscribe.ts +++ b/docs-snippets/basic-usage/publish-subscribe.ts @@ -99,6 +99,11 @@ subscription1.unsubscribe(); subscriptionSet1.unsubscribe(); // snippet.end +// snippet.subscriptionSetSubscribeBasicUsage +const channelsSubscriptionSet = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }); +channelsSubscriptionSet.subscribe(); +// snippet.end + // snippet.unsubscribeAllBasicUsage // create a subscription set with multiple channels const subscriptionSet = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }); From 3f03362547e88e609c0c35c1c081f3d7afd64376 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Thu, 19 Jun 2025 16:54:42 +0530 Subject: [PATCH 11/27] added missing subscriptionSet example code snippets --- docs-snippets/publish-subscribe.ts | 45 +++++++++++++++++++++++++++++- lib/types/index.d.ts | 2 +- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/docs-snippets/publish-subscribe.ts b/docs-snippets/publish-subscribe.ts index 686b7301c..cf6101f06 100644 --- a/docs-snippets/publish-subscribe.ts +++ b/docs-snippets/publish-subscribe.ts @@ -197,4 +197,47 @@ pubnub.unsubscribe({ pubnub.unsubscribe({ channelGroups: ["demo_group1", "demo_group2"], }); -// snippet.end \ No newline at end of file +// snippet.end + +{ + // snippet.subscriptionSetFrom2IndividualSubscriptions + // create a subscription from a channel entity + const channel = pubnub.channel('channel_1') + const subscription1 = channel.subscription({ receivePresenceEvents: true }); + + // create a subscription from a channel group entity + const channelGroup = pubnub.channelGroup('channelGroup_1') + const subscription2 = channelGroup.subscription(); + + // add 2 subscriptions to create a subscription set + const subscriptionSet = subscription1.addSubscription(subscription2); + + // add another subscription to the set + const subscription3 = pubnub.channel('channel_3').subscription({ receivePresenceEvents: false }); + subscriptionSet.addSubscription(subscription3); + + // remove a subscription from a subscription set + subscriptionSet.removeSubscription(subscription3); + + subscriptionSet.subscribe(); + // snippet.end +} + +{ +// snippet.SubscriptionSetFrom2Sets +// create a subscription set with multiple channels +const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }); + +// create a subscription set with multiple channel groups and options +const subscriptionSet2 = pubnub.subscriptionSet({ + channels: ['ch1', 'ch2'], + subscriptionOptions: { receivePresenceEvents: true } +}); + +// create a new subscription set from 2 sets +const subscriptionSet3 = subscriptionSet1.addSubscriptionSet(subscriptionSet2); + +// you can also remove sets +const subscriptionSetWithChannelsOnly = subscriptionSet3.removeSubscriptionSet(subscriptionSet2); +// snippet.end +} \ No newline at end of file diff --git a/lib/types/index.d.ts b/lib/types/index.d.ts index 305c185f5..c108c9366 100644 --- a/lib/types/index.d.ts +++ b/lib/types/index.d.ts @@ -4767,7 +4767,7 @@ declare namespace PubNub { * * @param subscriptionSet - Other entities' subscription set, which should be joined. */ - addSubscriptionSet(subscriptionSet: SubscriptionSet): void; + addSubscriptionSet(subscriptionSet: SubscriptionSet): SubscriptionSet; /** * Subtract another {@link SubscriptionSet} object. * From 1e3d2fb6461ca930961a9a237064a1e71184b460 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 23 Jun 2025 11:57:04 +0530 Subject: [PATCH 12/27] added getFilterExpresssionBasicusage --- docs-snippets/basic-usage/configuration.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/docs-snippets/basic-usage/configuration.ts b/docs-snippets/basic-usage/configuration.ts index 31d5c2d8a..f842a8acd 100644 --- a/docs-snippets/basic-usage/configuration.ts +++ b/docs-snippets/basic-usage/configuration.ts @@ -18,6 +18,14 @@ pubnub.setAuthKey("my_authkey"); pubnub.setFilterExpression("such=wow"); // snippet.end +// snippet.getFilterExpressionBasicUsage +pubnub.getFilterExpression(); +// snippet.end + +// snippet.generateUUIDBasicUsage(deprecated) +PubNub.generateUUID(); +// snippet.end + // snippet.configurationBasicUsage // Initialize PubNub with your keys var pubnub = new PubNub({ From d7a28c731f0461a4e98b19ba128b6ce6d574fee4 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 23 Jun 2025 13:06:50 +0530 Subject: [PATCH 13/27] revert changes of providing return type for addSubscriptionSet() method on subscriptionSet entity --- docs-snippets/publish-subscribe.ts | 8 ++++---- lib/types/index.d.ts | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/docs-snippets/publish-subscribe.ts b/docs-snippets/publish-subscribe.ts index cf6101f06..65b6bc435 100644 --- a/docs-snippets/publish-subscribe.ts +++ b/docs-snippets/publish-subscribe.ts @@ -234,10 +234,10 @@ const subscriptionSet2 = pubnub.subscriptionSet({ subscriptionOptions: { receivePresenceEvents: true } }); -// create a new subscription set from 2 sets -const subscriptionSet3 = subscriptionSet1.addSubscriptionSet(subscriptionSet2); +// add a subscription set to another subscription set +subscriptionSet1.addSubscriptionSet(subscriptionSet2); -// you can also remove sets -const subscriptionSetWithChannelsOnly = subscriptionSet3.removeSubscriptionSet(subscriptionSet2); +// remove a subscription set from another subscription set +subscriptionSet1.removeSubscriptionSet(subscriptionSet2); // snippet.end } \ No newline at end of file diff --git a/lib/types/index.d.ts b/lib/types/index.d.ts index c108c9366..305c185f5 100644 --- a/lib/types/index.d.ts +++ b/lib/types/index.d.ts @@ -4767,7 +4767,7 @@ declare namespace PubNub { * * @param subscriptionSet - Other entities' subscription set, which should be joined. */ - addSubscriptionSet(subscriptionSet: SubscriptionSet): SubscriptionSet; + addSubscriptionSet(subscriptionSet: SubscriptionSet): void; /** * Subtract another {@link SubscriptionSet} object. * From 7e9e949c13ec1c38cc173b110c9464f1eb370068 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 23 Jun 2025 17:44:31 +0530 Subject: [PATCH 14/27] added getting started code snippets --- docs-snippets/getting-started-example.ts | 93 ++++++++++++++++++++++++ docs-snippets/getting-started.ts | 82 +++++++++++++++++++++ 2 files changed, 175 insertions(+) create mode 100644 docs-snippets/getting-started-example.ts create mode 100644 docs-snippets/getting-started.ts diff --git a/docs-snippets/getting-started-example.ts b/docs-snippets/getting-started-example.ts new file mode 100644 index 000000000..ccf9ddcd7 --- /dev/null +++ b/docs-snippets/getting-started-example.ts @@ -0,0 +1,93 @@ +import PubNub from '../lib/types'; + +// snippet.gettingStartedCompleteExample +// Save this file as index.js/.ts + +// 1. Import pubnub +// import PubNub from 'pubnub'; + +// 2. Initialize PubNub with demo keys and a random user ID +const pubnub = new PubNub({ + publishKey: 'YOUR_PUBLISH_KEY', + subscribeKey: 'YOUR_SUBSCRIBE_KEY', + userId: 'YOUR_USER_ID', +}); + +// 3. Add listener to handle messages, presence events, and connection status +pubnub.addListener({ + // Handle incoming messages + message: function (event) { + // Handle message event + console.log('New message:', event.message); + // Format and display received message + let displayText; + if (typeof event.message === 'object' && event.message && 'text' in event.message) { + const messageObj = event.message as { text?: string; sender?: string }; + displayText = `${messageObj.sender || 'User'}: ${messageObj.text}`; + } else { + displayText = `Message: ${JSON.stringify(event.message)}`; + } + console.log(displayText); + }, + + // Handle presence events (join, leave, timeout) + presence: function (event) { + // Handle presence event + console.log('Presence event:', event); + console.log('Action:', event.action); // join, leave, timeout + console.log('Channel:', event.channel); + }, + + // Handle connection status events + status: function (event) { + // Handle status event + if (event.category === 'PNConnectedCategory') { + console.log('Connected to PubNub chat!'); + console.log('Your user ID is:', pubnub.userId); + } else if (event.category === 'PNNetworkIssuesCategory') { + console.log('Connection lost. Attempting to reconnect...'); + } + }, +}); + +// 4. Create a channel entity and subscription with presence +const channel = pubnub.channel('hello_world'); +const subscription = channel.subscription({ + receivePresenceEvents: true, // to receive presence events +}); + +// 5. Subscribe to the channel +subscription.subscribe(); + +// 6. Function to publish messages +async function publishMessage(text: string) { + if (!text.trim()) return; + + try { + // Create a message object with text, timestamp, and sender ID + const message = { + text: text, + time: new Date().toISOString(), + sender: pubnub.userId, + }; + + // Publish the message to the channel + const response = await pubnub.publish({ + message: message, + channel: 'hello_world', + storeInHistory: true, // Save this message in history + }); + + // Success message (timetoken is the unique ID for this message) + console.log(`\nMessage sent successfully!`); + } catch (error) { + // Handle publish errors + console.error(`\n❌ Failed to send message: ${error}`); + } +} + +// 7. define the message and Publish that message. +const text_message = 'Hello, world!'; +publishMessage(text_message); + +// snippet.end diff --git a/docs-snippets/getting-started.ts b/docs-snippets/getting-started.ts new file mode 100644 index 000000000..b9ce0fffa --- /dev/null +++ b/docs-snippets/getting-started.ts @@ -0,0 +1,82 @@ +import PubNub, { Subscription } from '../lib/types'; + +// snippet.gettingStartedInitPubnub +const pubnub = new PubNub({ + publishKey: 'YOUR_PUBLISH_KEY', + subscribeKey: 'YOUR_SUBSCRIBE_KEY', + userId: 'YOUR_USER_ID' +}); +// snippet.end + +// snippet.gettingStartedEventListeners +// Add listener to handle messages, presence events, and connection status +pubnub.addListener({ + message: function(event: Subscription.Message) { + // Handle message event + console.log("New message:", event.message); + // Format and display received message + let displayText; + if (typeof event.message === 'object' && event.message && 'text' in event.message) { + const messageObj = event.message as { text?: string; sender?: string }; + displayText = `${messageObj.sender || 'User'}: ${messageObj.text}`; + } else { + displayText = `Message: ${JSON.stringify(event.message)}`; + } + console.log(displayText); + }, + presence: function(event: Subscription.Presence) { + // Handle presence event + console.log("Presence event:", event); + console.log("Action:", event.action); // join, leave, timeout + console.log("Channel:", event.channel); + }, + status: function(event) { + // Handle status event + if (event.category === "PNConnectedCategory") { + console.log("Connected to PubNub chat!"); + } else if (event.category === "PNNetworkIssuesCategory") { + console.log("Connection lost. Attempting to reconnect..."); + } + } +}); +// snippet.end + +// snippet.gettingStartedCreateSubscription +// Create a channel entity +const channel = pubnub.channel('hello_world'); + +// Create a subscription +const subscription = channel.subscription({ + receivePresenceEvents: true // to receive presence events +}); + +// Subscribe +subscription.subscribe(); +// snippet.end + +// snippet.gettingStartedPublishMessages +// Function to publish a message +async function publishMessage(text: string) { + if (!text.trim()) return; + + try { + const result = await pubnub.publish({ + message: { + text: text, + sender: pubnub.userId, + time: new Date().toISOString() + }, + channel: 'hello_world' + }); + console.log(`Message published with timetoken: ${result.timetoken}`); + console.log(`You: ${text}`); + } catch (error) { + console.error(`Publish failed: ${error}`); + } +} + +// Example: publish a message +const text_message = "Hello, world!"; +publishMessage(text_message); + +// snippet.end From 5f1cfb329910065ea7834e6a31436f489b6efd08 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Mon, 23 Jun 2025 19:54:55 +0530 Subject: [PATCH 15/27] added missing generic listener syntax example --- docs-snippets/event-listener.ts | 54 +++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/docs-snippets/event-listener.ts b/docs-snippets/event-listener.ts index 9a7fa6d93..70e4993b8 100644 --- a/docs-snippets/event-listener.ts +++ b/docs-snippets/event-listener.ts @@ -20,6 +20,60 @@ subscription.onObjects = (objectsEvent) => { console.log("Objects event: ", obje subscription.onMessageAction = (messageActionEvent) => { console.log("Message Reaction event: ", messageActionEvent); }; subscription.onFile = (fileEvent) => { console.log("File event: ", fileEvent); }; +// Generic listeners +subscription.addListener({ + // Messages + message: function (m) { + const channelName = m.channel; // Channel on which the message was published + const channelGroup = m.subscription; // Channel group or wildcard subscription match (if exists) + const pubTT = m.timetoken; // Publish timetoken + const msg = m.message; // Message payload + const publisher = m.publisher; // Message publisher + }, + // Presence + // requires a subscription with presence + presence: function (p) { + const action = p.action; // Can be join, leave, timeout, state-change, or interval + const channelName = p.channel; // Channel to which the message belongs + const channelGroup = p.subscription; // Channel group or wildcard subscription match, if any + const publishTime = p.timestamp; // Publish timetoken + const timetoken = p.timetoken; // Current timetoken + }, + // Signals + signal: function (s) { + const channelName = s.channel; // Channel to which the signal belongs + const channelGroup = s.subscription; // Channel group or wildcard subscription match, if any + const pubTT = s.timetoken; // Publish timetoken + const msg = s.message; // Payload + const publisher = s.publisher; // Message publisher + }, + // App Context + objects: (objectEvent) => { + const channel = objectEvent.channel; // Channel to which the event belongs + const channelGroup = objectEvent.subscription; // Channel group + const timetoken = objectEvent.timetoken; // Event timetoken + const event = objectEvent.message.data.type; // Event name + }, + // Message Actions + messageAction: function (ma) { + const channelName = ma.channel; // Channel to which the message belongs + const publisher = ma.data.uuid; // Message publisher + const event = ma.event; // Message action added or removed + const type = ma.data.type; // Message action type + const value = ma.data.value; // Message action value + const messageTimetoken = ma.data.messageTimetoken; // Timetoken of the original message + const actionTimetoken = ma.data.actionTimetoken; // Timetoken of the message action + }, + // File Sharing + file: function (event) { + const channelName = event.channel; // Channel to which the file belongs + const channelGroup = event.subscription; // Channel group or wildcard subscription match (if exists) + const publisher = event.publisher; // File publisher + const timetoken = event.timetoken; // Event timetoken + const message = event.message; // Optional message attached to the file + } +}); + // snippet.end // snippet.AddConnectionStatusListener From f97d77f511d06aac9de6687598e9d8ad9bc434d2 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Tue, 24 Jun 2025 18:21:50 +0530 Subject: [PATCH 16/27] fix snippets indentation, GrantToken type fix by removing objects syntax support, Error handling refactor in code snippets --- docs-snippets/access-manager.ts | 321 +++++--------- docs-snippets/app-context.ts | 98 ++-- docs-snippets/basic-usage/access-manager.ts | 85 ++-- docs-snippets/basic-usage/app-context.ts | 419 +++++++++++------- docs-snippets/basic-usage/channel-groups.ts | 88 ++-- docs-snippets/basic-usage/configuration.ts | 39 +- .../basic-usage/download-file-web.ts | 22 +- docs-snippets/basic-usage/file-sharing.ts | 136 +++--- docs-snippets/basic-usage/message-actions.ts | 50 ++- .../basic-usage/message-persistence.ts | 72 +-- docs-snippets/basic-usage/miscellaneous.ts | 40 +- docs-snippets/basic-usage/presence.ts | 85 ++-- .../basic-usage/publish-subscribe.ts | 32 +- src/core/pubnub-common.ts | 9 +- 14 files changed, 781 insertions(+), 715 deletions(-) diff --git a/docs-snippets/access-manager.ts b/docs-snippets/access-manager.ts index 347d4548c..e020460b8 100644 --- a/docs-snippets/access-manager.ts +++ b/docs-snippets/access-manager.ts @@ -1,225 +1,128 @@ -import PubNub from '../lib/types'; +import PubNub, { PubNubError } from '../lib/types'; const pubnub = new PubNub({ - publishKey: 'demo', - subscribeKey: 'demo', - userId: 'myUniqueUserId' - }); + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId', +}); -// snippet.grantTokenVariousResources +// snippet.grantTokenVariousResources try { - const token = await pubnub.grantToken({ - ttl: 15, - authorized_uuid: "my-authorized-uuid", - resources: { - channels: { - "channel-a": { - read: true, - }, - "channel-b": { - read: true, - write: true, - }, - "channel-c": { - read: true, - write: true, - }, - "channel-d": { - read: true, - write: true, - }, - }, - groups: { - "channel-group-b": { - read: true, - }, - }, - uuids: { - "uuid-c": { - get: true, - }, - "uuid-d": { - get: true, - update: true, - }, - }, - }, - }); -} catch (status) { - console.log(status); + const token = await pubnub.grantToken({ + ttl: 15, + authorized_uuid: 'my-authorized-uuid', + resources: { + channels: { + 'channel-a': { + read: true, + }, + 'channel-b': { + read: true, + write: true, + }, + 'channel-c': { + read: true, + write: true, + }, + 'channel-d': { + read: true, + write: true, + }, + }, + groups: { + 'channel-group-b': { + read: true, + }, + }, + uuids: { + 'uuid-c': { + get: true, + }, + 'uuid-d': { + get: true, + update: true, + }, + }, + }, + }); +} catch (error) { + console.error( + `Grant token error: ${error}.${(error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''}`, + ); } // snippet.end // snippet.grantTokenUsingRegEx try { - const token = await pubnub.grantToken({ - ttl: 15, - authorized_uuid: "my-authorized-uuid", - patterns: { - channels: { - "^channel-[A-Za-z0-9]$": { - read: true, - }, - }, - }, - }); -} catch (status) { - console.log(status); + const token = await pubnub.grantToken({ + ttl: 15, + authorized_uuid: 'my-authorized-uuid', + patterns: { + channels: { + '^channel-[A-Za-z0-9]$': { + read: true, + }, + }, + }, + }); +} catch (error) { + console.error( + `Grant token error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end // snippet.grantTokenRegExAndResources try { - const token = await pubnub.grantToken({ - ttl: 15, - authorized_uuid: "my-authorized-uuid", - resources: { - channels: { - "channel-a": { - read: true, - }, - "channel-b": { - read: true, - write: true, - }, - "channel-c": { - read: true, - write: true, - }, - "channel-d": { - read: true, - write: true, - }, - }, - groups: { - "channel-group-b": { - read: true, - }, - }, - uuids: { - "uuid-c": { - get: true, - }, - "uuid-d": { - get: true, - update: true, - }, - }, - }, - patterns: { - channels: { - "^channel-[A-Za-z0-9]$": { - read: true - }, - }, - }, - }); -} catch (status) { - console.log(status); -} -// snippet.end - -// snippet.grantTokenSpaceUserResources -try { - const token = await pubnub.grantToken({ - ttl: 15, - authorizedUserId: "my-authorized-userId", - resources: { - spaces: { - "space-a": { - read: true, - }, - "space-b": { - read: true, - write: true, - }, - "space-c": { - read: true, - write: true, - }, - "space-d": { - read: true, - write: true, - }, - }, - users: { - "userId-c": { - get: true, - }, - "userId-d": { - get: true, - update: true, - }, - }, - }, - }); -} catch (status) { - console.log(status); -} -// snippet.end - -// snippet.grantTokenSpaceUserRegEx -try { - const token = await pubnub.grantToken({ - ttl: 15, - authorizedUserId: "my-authorized-userId", - patterns: { - spaces: { - "^space-[A-Za-z0-9]$": { - read: true, - }, - }, - }, - }); -} catch (status) { - console.log(status); -} -// snippet.end - - -// snippet.grantTokenSpacesUserRegExResources -try { - const token = await pubnub.grantToken({ - ttl: 15, - authorizedUserId: "my-authorized-userId", - resources: { - spaces: { - "space-a": { - read: true, - }, - "space-b": { - read: true, - write: true, - }, - "space-c": { - read: true, - write: true, - }, - "space-d": { - read: true, - write: true, - }, - }, - users: { - "userId-c": { - get: true, - }, - "userId-d": { - get: true, - update: true, - }, - }, - }, - patterns: { - spaces: { - "^space-[A-Za-z0-9]$": { - read: true - }, - }, - }, - }); -} catch (status) { - console.log(status); + const token = await pubnub.grantToken({ + ttl: 15, + authorized_uuid: 'my-authorized-uuid', + resources: { + channels: { + 'channel-a': { + read: true, + }, + 'channel-b': { + read: true, + write: true, + }, + 'channel-c': { + read: true, + write: true, + }, + 'channel-d': { + read: true, + write: true, + }, + }, + groups: { + 'channel-group-b': { + read: true, + }, + }, + uuids: { + 'uuid-c': { + get: true, + }, + 'uuid-d': { + get: true, + update: true, + }, + }, + }, + patterns: { + channels: { + '^channel-[A-Za-z0-9]$': { + read: true, + }, + }, + }, + }); +} catch (error) { + console.error( + `Grant token error: ${error}.${(error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''}`, + ); } // snippet.end - diff --git a/docs-snippets/app-context.ts b/docs-snippets/app-context.ts index a8c33e626..935f33159 100644 --- a/docs-snippets/app-context.ts +++ b/docs-snippets/app-context.ts @@ -1,10 +1,10 @@ -import PubNub from '../lib/types'; +import PubNub, { PubNubError } from '../lib/types'; const pubnub = new PubNub({ - publishKey: 'demo', - subscribeKey: 'demo', - userId: 'myUniqueUserId' - }); + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId', +}); // snippet.iterativelyUpdateExistingMetadata const channel = 'team.red'; @@ -13,47 +13,47 @@ const description = 'The channel for Red team.'; const customField = { visible: 'team' }; // Function to set and then update channel metadata -const updateChannelMetadata = async () => { - try { - let response = await pubnub.objects.setChannelMetadata({ - channel: channel, - data: { - name: name, - description: description, - custom: customField - } - }); - console.log('The channel has been created with name and description.\n'); - - // Fetch current object with custom fields - let currentObjectResponse = await pubnub.objects.getChannelMetadata({ - channel: channel, - include: { - customFields: true - } - }); - let currentObject = currentObjectResponse.data; - - // Initialize the custom field object - let custom = currentObject.custom || {}; - - // Add or update the field - custom['edit'] = 'admin'; - - // Writing the updated object back to the server - let setResponse = await pubnub.objects.setChannelMetadata({ - channel: channel, - data: { - name: currentObject.name || '', - description: currentObject.description || '', - custom: custom - } - }); - console.log(`Object has been updated ${setResponse}`); - } catch (error) { - console.error(error); - } -}; - -updateChannelMetadata(); -// snippet.end \ No newline at end of file +try { + let response = await pubnub.objects.setChannelMetadata({ + channel: channel, + data: { + name: name, + description: description, + custom: customField, + }, + }); + console.log('The channel has been created with name and description.\n'); + + // Fetch current object with custom fields + let currentObjectResponse = await pubnub.objects.getChannelMetadata({ + channel: channel, + include: { + customFields: true, + }, + }); + let currentObject = currentObjectResponse.data; + + // Initialize the custom field object + let custom = currentObject.custom || {}; + + // Add or update the field + custom['edit'] = 'admin'; + + // Writing the updated object back to the server + let setResponse = await pubnub.objects.setChannelMetadata({ + channel: channel, + data: { + name: currentObject.name || '', + description: currentObject.description || '', + custom: custom, + }, + }); + console.log('Object has been updated', setResponse); +} catch (error) { + console.error( + `Set channel metadata error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); +} +// snippet.end diff --git a/docs-snippets/basic-usage/access-manager.ts b/docs-snippets/basic-usage/access-manager.ts index a521e4b46..aa9a66227 100644 --- a/docs-snippets/basic-usage/access-manager.ts +++ b/docs-snippets/basic-usage/access-manager.ts @@ -1,67 +1,56 @@ -import PubNub from '../../lib/types'; +import PubNub, { PubNubError } from '../../lib/types'; const pubnub = new PubNub({ - publishKey: 'demo', - subscribeKey: 'demo', - userId: 'myUniqueUserId' - }); + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId', +}); // snippet.accessManagerBasicUsage // Function to use grantToken method -async function grantAccessToken() { - try { - const token = await pubnub.grantToken({ - ttl: 15, - authorized_uuid: "my-authorized-uuid", - resources: { - channels: { - "my-channel": { - read: true, - write: true - } - } - } - }); - console.log("Granted Token:", token); - } catch (status) { - console.log("Grant Token Error:", status); - } -} - -// Execute the function to grant a token -grantAccessToken(); -// snippet.end - -// snippet.grantTokenSpacesUserBasicUsage try { - const token = await pubnub.grantToken({ - ttl: 15, - authorizedUserId: "my-authorized-userId", - resources: { - spaces: { - "my-space": { - read: true, - }, - }, + const token = await pubnub.grantToken({ + ttl: 15, + authorized_uuid: 'my-authorized-uuid', + resources: { + channels: { + 'my-channel': { + read: true, + write: true, }, - }); -} catch (status) { - console.log(status); + }, + }, + }); + console.log('Granted Token:', token); +} catch (error) { + console.error( + `Grant token error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end // snippet.revokeTokenBasicUsage try { - const response = await pubnub.revokeToken("p0AkFl043rhDdHRsple3KgQ3NwY6BDcENnctokenVzcqBDczaWdYIGOAeTyWGJI"); -} catch (status) { - console.log(status); + const response = await pubnub.revokeToken('p0AkFl043rhDdHRsple3KgQ3NwY6BDcENnctokenVzcqBDczaWdYIGOAeTyWGJI'); +} catch (error) { + console.error( + `Revoke token error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end // snippet.parseTokenBasicUsage -pubnub.parseToken("p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI") +pubnub.parseToken( + 'p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI', +); // snippet.end // snippet.setTokenBasicUsage -pubnub.setToken("p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI") -// snippet.end \ No newline at end of file +pubnub.setToken( + 'p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI', +); +// snippet.end diff --git a/docs-snippets/basic-usage/app-context.ts b/docs-snippets/basic-usage/app-context.ts index da411a484..ab29dc9db 100644 --- a/docs-snippets/basic-usage/app-context.ts +++ b/docs-snippets/basic-usage/app-context.ts @@ -1,20 +1,24 @@ -import PubNub from '../../lib/types'; +import PubNub, { PubNubError } from '../../lib/types'; const pubnub = new PubNub({ - publishKey: 'demo', - subscribeKey: 'demo', - userId: 'myUniqueUserId' - }); + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId', +}); - // snippet.getAllUUIDMetadataBasicUsage +// snippet.getAllUUIDMetadataBasicUsage // Function to get all UUID metadata // to get some data in response, add user metadata using setUUIDMetadata method async function getAllUUIDMetadata() { try { const response = await pubnub.objects.getAllUUIDMetadata(); - console.log(`getAllUUIDMetadata response: ${response}`); + console.log('getAllUUIDMetadata response:', response); } catch (error) { - console.log(`getAllUUIDMetadata failed with error: ${error}`); + console.error( + `Get all UUID metadata error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } } @@ -25,262 +29,351 @@ getAllUUIDMetadata(); // snippet.getUUIDMetadataBasicUsage // Using UUID from the config - default when uuid is not passed in the method try { - const response = await pubnub.objects.getUUIDMetadata(); - console.log(`getUUIDMetadata response: ${response}`); -} catch (status) { - console.log(`getUUIDMetadata failed with error: ${status}`); + const response = await pubnub.objects.getUUIDMetadata(); + console.log('getUUIDMetadata response:', response); +} catch (error) { + console.error( + `Get UUID metadata error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // Using the passed in UUID try { - const response = await pubnub.objects.getUUIDMetadata({ - uuid: "myUuid", - }); - console.log(`getUUIDMetadata response: ${response}`); -} catch (status) { - console.log(`getUUIDMetadata failed with error: ${status}`); + const response = await pubnub.objects.getUUIDMetadata({ + uuid: 'myUuid', + }); + console.log('getUUIDMetadata response:', response); +} catch (error) { + console.error( + `Get UUID metadata error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end // snippet.setUUIDMetadataBasicUsage // Using UUID from the config - default when uuid is not passed in the method try { - const response = await pubnub.objects.setUUIDMetadata({ - data: { - name: "John Doe", - }, - }); -} catch (status) { - console.log(`setUUIDMetadata failed with error: ${status}`); + const response = await pubnub.objects.setUUIDMetadata({ + data: { + name: 'John Doe', + }, + }); + console.log('setUUIDMetadata response:', response); +} catch (error) { + console.error( + `Set UUID metadata error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // Using the passed in UUID try { - const response = await pubnub.objects.setUUIDMetadata({ - uuid: "myUuid", - data: {}, - }); - console.log(`setUUIDMetadata response: ${response}`); -} catch (status) { - console.log(`setUUIDMetadata failed with error: ${status}`); + const response = await pubnub.objects.setUUIDMetadata({ + uuid: 'myUuid', + data: { + email: 'john.doe@example.com', + }, + }); + console.log('setUUIDMetadata response:', response); +} catch (error) { + console.error( + `Set UUID metadata error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } - // snippet.end // snippet.removeUUIDMetadataBasicUsage // Using UUID from the config - default when uuid is not passed in the method try { - const response = await pubnub.objects.removeUUIDMetadata(); -} catch (status) { - console.log(`removeUUIDMetadata failed with error: ${status}`); + const response = await pubnub.objects.removeUUIDMetadata(); +} catch (error) { + console.error( + `Remove UUID metadata error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // Using the passed in UUID try { - const response = await pubnub.objects.removeUUIDMetadata({ - uuid: "myUuid", - }); -} catch (status) { - console.log(`removeUUIDMetadata failed with error: ${status}`); + const response = await pubnub.objects.removeUUIDMetadata({ + uuid: 'myUuid', + }); +} catch (error) { + console.error( + `Remove UUID metadata error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end // snippet.getAllChannelMetadataBasicUsage // Get the total number of channels included in the response. try { - const response = await pubnub.objects.getAllChannelMetadata({ - include: { - totalCount: true, - }, - }); -} catch (status) { - console.log(`getAllChannelMetadata failed with error: ${status}`); + const response = await pubnub.objects.getAllChannelMetadata({ + include: { + totalCount: true, + }, + }); +} catch (error) { + console.error( + `Get all channel metadata error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // Get all channels with the filter option. To get all channel which has Id ending 'Team'. try { - const response = await pubnub.objects.getAllChannelMetadata({ - filter: 'name LIKE "*Team"', - }); - console.log(`getAllChannelMetadata response: ${response}`); -} catch (status) { - console.log(`getAllChannelMetadata failed with error: ${status}`); + const response = await pubnub.objects.getAllChannelMetadata({ + filter: 'name LIKE "*Team"', + }); + console.log('Get all channel metadata response:', response); +} catch (error) { + console.error( + `Get all channel metadata error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end // snippet.getChannelMetadataBasicUsage try { - const response = await pubnub.objects.getChannelMetadata({ - // `channel` is the `id` in the _metadata_, not `name` - channel: "team.blue", - }); -} catch (status) { - console.log(`getChannelMetadata failed with error: ${status}`); + const response = await pubnub.objects.getChannelMetadata({ + // `channel` is the `id` in the _metadata_, not `name` + channel: 'team.blue', + }); + console.log('Get channel metadata response:', response); +} catch (error) { + console.error( + `Get channel metadata error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end // snippet.setChannelMetadataBasicUsage try { - const response = await pubnub.objects.setChannelMetadata({ - channel: "team.red", - data: { - name: "Red Team", - description: "The channel for Red team and no other teams.", - custom: { - owner: "Red Leader", - }, - }, - include: { - customFields: false, - }, - }); -} catch (status) { - console.log(`setChannelMetadata failed with error: ${status}`); + const response = await pubnub.objects.setChannelMetadata({ + channel: 'team.red', + data: { + name: 'Red Team', + description: 'The channel for Red team and no other teams.', + custom: { + owner: 'Red Leader', + }, + }, + include: { + customFields: false, + }, + }); + console.log('Set channel metadata response:', response); +} catch (error) { + console.error( + `Set channel metadata error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end // snippet.removeChannelMetadataBasicUsage try { - const response = await pubnub.objects.removeChannelMetadata({ - channel: "team.red", - }); -} catch (status) { - console.log(`removeChannelMetadata failed with error: ${status}`); + const response = await pubnub.objects.removeChannelMetadata({ + channel: 'team.red', + }); +} catch (error) { + console.error( + `Remove channel metadata error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end // snippet.getMembershipBasicUsage // Using UUID from the config try { - const response = await pubnub.objects.getMemberships(); -} catch (status) { - console.log(`getMemberships failed with error: ${status}`); + const response = await pubnub.objects.getMemberships(); +} catch (error) { + console.error( + `Get memberships error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // Using the passed in UUID try { - const response = await pubnub.objects.getMemberships({ - uuid: "myUuid", - include: { - channelFields: true, - }, - }); -} catch (status) { - console.log(`getMemberships failed with error: ${status}`); + const response = await pubnub.objects.getMemberships({ + uuid: 'myUuid', + include: { + channelFields: true, + }, + }); +} catch (error) { + console.error( + `Get memberships with channels fields included error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // Get all memberships that are starred by the user try { - const response = await pubnub.objects.getMemberships({ - uuid: "myUuid", - filter: "custom.starred == true", - }); -} catch (status) { - console.log(`getMemberships failed with error: ${status}`); + const response = await pubnub.objects.getMemberships({ + uuid: 'myUuid', + filter: 'custom.starred == true', + }); +} catch (error) { + console.error( + `Get filtered memberships error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end // snippet.setMembershipBasicUsage // Using UUID from the config try { - const response = await pubnub.objects.setMemberships({ - channels: [ - "my-channel", - { id: "channel-with-status-type", custom: { hello: "World" }, status: 'helloStatus', type:'helloType'} - ] - }); -} catch (status) { - console.log(`setMemberships failed with error: ${status}`); + const response = await pubnub.objects.setMemberships({ + channels: [ + 'my-channel', + { id: 'channel-with-status-type', custom: { hello: 'World' }, status: 'helloStatus', type: 'helloType' }, + ], + }); + console.log('Set memberships response:', response); +} catch (error) { + console.error( + `Set memberships error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // Using the passed in UUID try { - const response = await pubnub.objects.setMemberships({ - uuid: "my-uuid", - channels: [ - "my-channel", - { id: "channel-with-status-type", custom: { hello: "World" }, status: 'helloStatus', type:'helloType'} - ], - include: { - // To include channel fields in response - channelFields: true, - }, - }); - console.log(`setMemberships response: ${response}`); -} catch (status) { - console.log(`setMemberships failed with error: ${status}`); + const response = await pubnub.objects.setMemberships({ + uuid: 'my-uuid', + channels: [ + 'my-channel', + { id: 'channel-with-status-type', custom: { hello: 'World' }, status: 'helloStatus', type: 'helloType' }, + ], + include: { + // To include channel fields in response + channelFields: true, + }, + }); + console.log('Set memberships response:', response); +} catch (error) { + console.error( + `Set memberships error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end // snippet.removeMembershipsBasicUsage // Using UUID from the config try { - const response = await pubnub.objects.removeMemberships({ - channels: ["ch-1", "ch-2"], - }); -} catch (status) { - console.log(`removeMemberships failed with error: ${status}`); + const response = await pubnub.objects.removeMemberships({ + channels: ['ch-1', 'ch-2'], + }); +} catch (error) { + console.error( + `Remove memberships error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // Using the passed in UUID try { - const response = await pubnub.objects.removeMemberships({ - uuid: "myUuid", - channels: ["ch-1", "ch-2"], - }); -} catch (status) { - console.log(`removeMemberships failed with error: ${status}`); + const response = await pubnub.objects.removeMemberships({ + uuid: 'myUuid', + channels: ['ch-1', 'ch-2'], + }); +} catch (error) { + console.error( + `Remove memberships for given uuids error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end // snippet.getChannelMembersBasicUsage try { - const response = await pubnub.objects.getChannelMembers({ - channel: "myChannel", - include: { - UUIDFields: true, - }, - }); - console.log(`getChannelMembers response: ${response}`); -} catch (status) { - console.log(`getChannelMembers failed with error: ${status}`); + const response = await pubnub.objects.getChannelMembers({ + channel: 'myChannel', + include: { + UUIDFields: true, + }, + }); + console.log('getChannelMembers response:', response); +} catch (error) { + console.error( + `Get channel members error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // Get all channel members with "admin" in the description try { - const response = await pubnub.objects.getChannelMembers({ - channel: "myChannel", - filter: 'description LIKE "*admin*"', - }); - console.log(`getChannelMembers response: ${response}`); -} catch (status) { - console.log(`getChannelMembers failed with error: ${status}`); + const response = await pubnub.objects.getChannelMembers({ + channel: 'myChannel', + filter: 'description LIKE "*admin*"', + }); + console.log('getChannelMembers response:', response); +} catch (error) { + console.error( + `Get channel members error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end // snippet.setChannelMembersBasicUsage try { - const response = await pubnub.objects.setChannelMembers({ - channel: "myChannel", - uuids: [ - "uuid-1", - "uuid-2", - { id: "uuid-3", custom: { role: "Super Admin" } }, - ], - }); - console.log(`setChannelMembers response: ${response}`); -} catch (status) { - console.log(`setChannelMembers failed with error: ${status}`); + const response = await pubnub.objects.setChannelMembers({ + channel: 'myChannel', + uuids: ['uuid-1', 'uuid-2', { id: 'uuid-3', custom: { role: 'Super Admin' } }], + }); + console.log('setChannelMembers response:', response); +} catch (error) { + console.error( + `Set channel members error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end // snippet.removeChannelMembersBasicUsage try { - const response = await pubnub.objects.removeChannelMembers({ - channel: "myChannel", - uuids: ["uuid-1", "uuid-2"], - }); -} catch (status) { - console.log(`removeChannelMembers failed with error: ${status}`); + const response = await pubnub.objects.removeChannelMembers({ + channel: 'myChannel', + uuids: ['uuid-1', 'uuid-2'], + }); +} catch (error) { + console.error( + `Remove channel members error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end diff --git a/docs-snippets/basic-usage/channel-groups.ts b/docs-snippets/basic-usage/channel-groups.ts index f53487136..35380414a 100644 --- a/docs-snippets/basic-usage/channel-groups.ts +++ b/docs-snippets/basic-usage/channel-groups.ts @@ -1,42 +1,44 @@ -import PubNub from '../../lib/types'; +import PubNub, { PubNubError } from '../../lib/types'; const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', - userId: 'myUniqueUserId' + userId: 'myUniqueUserId', }); // snippet.addChannelsToGroupBasicUsage -// Function to add channels to a channel group -async function addChannelsToGroup() { - try { - const response = await pubnub.channelGroups.addChannels({ - channels: ["ch1", "ch2"], - channelGroup: "myChannelGroup" - }); - console.log(`addChannels to Group response: ${response}`); - } catch (status) { - console.log(`addChannels to group failed with error: ${status}`); - } +try { + const response = await pubnub.channelGroups.addChannels({ + channels: ['ch1', 'ch2'], + channelGroup: 'myChannelGroup', + }); + console.log('addChannels to Group response:', response); +} catch (error) { + console.error( + `Add channels to group error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } - -// Execute the function to add channels -addChannelsToGroup(); // snippet.end // snippet.listChannelsInGroupBasicUsage // assuming an intialized PubNub instance already exists // to get some data in response, first add some channels to the group using addChannels() method. try { - const response = await pubnub.channelGroups.listChannels({ - channelGroup: "myChannelGroup", - }); - console.log(`Listing push channels for the device: ${response}`); - response.channels.forEach((channel: string) => { - console.log(channel); - }); -} catch (status) { - console.log(`listChannels of group failed with error: ${status}`); + const response = await pubnub.channelGroups.listChannels({ + channelGroup: 'myChannelGroup', + }); + console.log('Listing push channels for the device:', response); + response.channels.forEach((channel: string) => { + console.log(channel); + }); +} catch (error) { + console.error( + `List channels of group error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end @@ -44,13 +46,17 @@ try { // assuming an initialized PubNub instance already exists // and channel which is going to be removed from the group is aredaly added to the group to observe the removal try { - const response = await pubnub.channelGroups.removeChannels({ - channels: ["son"], - channelGroup: "family", - }); - console.log(`removeChannels from group response: ${response}`); -} catch (status) { - console.log(`removeChannels from group failed with error: ${status}`); + const response = await pubnub.channelGroups.removeChannels({ + channels: ['son'], + channelGroup: 'family', + }); + console.log('removeChannels from group response:', response); +} catch (error) { + console.error( + `Remove channels from group error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end @@ -58,11 +64,15 @@ try { // assuming an initialized PubNub instance already exists // and channel group which is getting deleted already exist to see the deletion effect. try { - const response = await pubnub.channelGroups.deleteGroup({ - channelGroup: "family", - }); - console.log(`deleteChannelGroup response: ${response}`); -} catch (status) { - console.log(`deleteChannelGroup failed with error: ${status}`); + const response = await pubnub.channelGroups.deleteGroup({ + channelGroup: 'family', + }); + console.log('deleteChannelGroup response:', response); +} catch (error) { + console.error( + `Delete channel group error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } -// snippet.end \ No newline at end of file +// snippet.end diff --git a/docs-snippets/basic-usage/configuration.ts b/docs-snippets/basic-usage/configuration.ts index f842a8acd..c6c339680 100644 --- a/docs-snippets/basic-usage/configuration.ts +++ b/docs-snippets/basic-usage/configuration.ts @@ -2,20 +2,21 @@ import PubNub from '../../src/web/index'; // snippet.configurationBasicUsageSubscriptionWorkerUrl var pubnub = new PubNub({ - subscribeKey: "demo", - publishKey: "demo", - userId: "unique-user-id", - // using PubNub JS SDK v9.6.0, make sure the versions match - subscriptionWorkerUrl: 'https://www.my-domain.com/static/js/pubnub.worker.9.6.0.js' - }); + subscribeKey: 'demo', + publishKey: 'demo', + userId: 'unique-user-id', + // using PubNub JS SDK v9.6.0, make sure the versions match. + // NOTE: 'subscriptionWorkerUrl' is only needed if you need to use SharedWorker. + subscriptionWorkerUrl: 'https://www.my-domain.com/static/js/pubnub.worker.9.6.0.js', +}); // snippet.end // snippet.setAuthKeyBasicUsage -pubnub.setAuthKey("my_authkey"); +pubnub.setAuthKey('my_authkey'); // snippet.end // snippet.setFilterExpressionBasicUsage -pubnub.setFilterExpression("such=wow"); +pubnub.setFilterExpression('such=wow'); // snippet.end // snippet.getFilterExpressionBasicUsage @@ -29,14 +30,14 @@ PubNub.generateUUID(); // snippet.configurationBasicUsage // Initialize PubNub with your keys var pubnub = new PubNub({ - subscribeKey: 'YOUR_SUBSCRIBE_KEY', - publishKey: 'YOUR_PUBLISH_KEY', - userId: 'YOUR_USER_ID', - cryptoModule: PubNub.CryptoModule?.aesCbcCryptoModule({ cipherKey: 'YOUR_CIPHER_KEY' }), - authKey: 'accessMangerToken', - logLevel: PubNub.LogLevel.Debug, - ssl: true, - presenceTimeout: 130 - }); - -// snippet.end \ No newline at end of file + subscribeKey: 'YOUR_SUBSCRIBE_KEY', + publishKey: 'YOUR_PUBLISH_KEY', + userId: 'YOUR_USER_ID', + cryptoModule: PubNub.CryptoModule?.aesCbcCryptoModule({ cipherKey: 'YOUR_CIPHER_KEY' }), + authKey: 'accessMangerToken', + logLevel: PubNub.LogLevel.Debug, + ssl: true, + presenceTimeout: 130, +}); + +// snippet.end diff --git a/docs-snippets/basic-usage/download-file-web.ts b/docs-snippets/basic-usage/download-file-web.ts index 0c1ec8eb9..801c388c2 100644 --- a/docs-snippets/basic-usage/download-file-web.ts +++ b/docs-snippets/basic-usage/download-file-web.ts @@ -1,3 +1,4 @@ +import { PubNubError } from 'lib/types'; import PubNub from '../../src/web/index'; const pubnub = new PubNub({ @@ -9,15 +10,24 @@ const pubnub = new PubNub({ // snippet.downloadFileWebBasicUsage // In browser // download the intended file -const file = await pubnub.downloadFile({ - channel: 'my_channel', - id: '...', - name: 'cat_picture.jpg', -}); +let file; +try { + file = await pubnub.downloadFile({ + channel: 'my_channel', + id: '...', + name: 'cat_picture.jpg', + }); +} catch (error) { + console.error( + `Download file error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); +} // have proper html element to display the file const myImageTag = document.createElement('img'); -myImageTag.src = URL.createObjectURL(await file.toFile()); +myImageTag.src = URL.createObjectURL(await file!.toFile()); // attach the file content to the html element document.body.appendChild(myImageTag); diff --git a/docs-snippets/basic-usage/file-sharing.ts b/docs-snippets/basic-usage/file-sharing.ts index 02a238371..fae4f854d 100644 --- a/docs-snippets/basic-usage/file-sharing.ts +++ b/docs-snippets/basic-usage/file-sharing.ts @@ -1,4 +1,4 @@ -import PubNub from '../../lib/types'; +import PubNub, { PubNubError } from '../../lib/types'; import fs from 'fs'; const pubnub = new PubNub({ @@ -9,32 +9,35 @@ const pubnub = new PubNub({ // snippet.sendFileBasicUsage // Function to send a file to a channel -async function sendFileToChannel() { - try { - const myFile = fs.createReadStream('./cat_picture.jpg'); +try { + const myFile = fs.createReadStream('./cat_picture.jpg'); - const response = await pubnub.sendFile({ - channel: 'my_channel', - file: { stream: myFile, name: 'cat_picture.jpg', mimeType: 'image/jpeg' }, - customMessageType: 'file-message', - }); + const response = await pubnub.sendFile({ + channel: 'my_channel', + file: { stream: myFile, name: 'cat_picture.jpg', mimeType: 'image/jpeg' }, + customMessageType: 'file-message', + }); - console.log(`File sent successfully: ${response}`); - } catch (error) { - console.log(`Error sending file: ${error}`); - } + console.log('File sent successfully:', response); +} catch (error) { + console.error( + `Error sending file: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } - -// Execute the function to send the file -sendFileToChannel(); // snippet.end // snippet.listFilesBasicUsage try { const response = await pubnub.listFiles({ channel: 'my_channel' }); - console.log(`Files listed successfully: ${response}`); + console.log('Files listed successfully:', response); } catch (error) { - console.log(`Error listing files: ${error}`); + console.error( + `Error listing files: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end @@ -45,48 +48,81 @@ const response = pubnub.getFileUrl({ channel: 'my_channel', id: '...', name: '.. // snippet.downloadFileNodeBasicUsage // In Node.js using streams: // import fs from 'fs' +try { + const downloadFileResponse = await pubnub.downloadFile({ + channel: 'my_channel', + id: '...', + name: 'cat_picture.jpg', + }); -const downloadFileResponse = await pubnub.downloadFile({ - channel: 'my_channel', - id: '...', - name: 'cat_picture.jpg', -}); - -const output = fs.createWriteStream('./cat_picture.jpg'); -const fileStream = await downloadFileResponse.toStream(); + const output = fs.createWriteStream('./cat_picture.jpg'); + const fileStream = await downloadFileResponse.toStream(); -fileStream.pipe(output); + fileStream.pipe(output); -output.once('end', () => { - console.log('File saved to ./cat_picture.jpg'); -}); + output.once('end', () => { + console.log('File saved to ./cat_picture.jpg'); + }); +} catch (error) { + console.error( + `Error downloading file: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); +} // snippet.end // snippet.downloadFileReactNativeBasicUsage // in React and React Native -const file = await pubnub.downloadFile({ - channel: 'awesomeChannel', - id: 'imageId', - name: 'cat_picture.jpg' -}); - -let fileContent = await file.toBlob(); +let file; +try { + file = await pubnub.downloadFile({ + channel: 'awesomeChannel', + id: 'imageId', + name: 'cat_picture.jpg', + }); +} catch (error) { + console.error( + `Error downloading file: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); +} +let fileContent = await file!.toBlob(); // snippet.end // snippet.deleteFileBasicUsage -const deleteFileResponse = await pubnub.deleteFile({ - channel: "my_channel", - id: "...", - name: "cat_picture.jpg", -}); +try { + const deleteFileResponse = await pubnub.deleteFile({ + channel: 'my_channel', + id: '...', + name: 'cat_picture.jpg', + }); + console.log('File deleted successfully:', deleteFileResponse); +} catch (error) { + console.error( + `Error deleting file: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); +} // snippet.end // snippet.publishFileMessageBasicUsage -const fileMessageResponse = await pubnub.publishFile({ - channel: "my_channel", - fileId: "...", - fileName: "cat_picture.jpg", - message: { field: "value" }, - customMessageType: 'file-message', -}); -// snippet.end \ No newline at end of file +try { + const fileMessageResponse = await pubnub.publishFile({ + channel: 'my_channel', + fileId: '...', + fileName: 'cat_picture.jpg', + message: { field: 'value' }, + customMessageType: 'file-message', + }); + console.log('File message published successfully:', fileMessageResponse); +} catch (error) { + console.error( + `Error publishing file message: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); +} +// snippet.end diff --git a/docs-snippets/basic-usage/message-actions.ts b/docs-snippets/basic-usage/message-actions.ts index 7dc8b2d48..7f0052cc7 100644 --- a/docs-snippets/basic-usage/message-actions.ts +++ b/docs-snippets/basic-usage/message-actions.ts @@ -1,4 +1,4 @@ -import PubNub from '../../lib/types'; +import PubNub, { PubNubError } from '../../lib/types'; const pubnub = new PubNub({ publishKey: 'demo', @@ -8,24 +8,24 @@ const pubnub = new PubNub({ // snippet.addMessageActionBasicUsage // first publish a message using publish() method to get the message timetoken -async function addReactionToMessage() { - try { - const response = await pubnub.addMessageAction({ - channel: 'channel_name', - messageTimetoken: 'replace_with_message_timetoken', // Replace with actual message timetoken - action: { - type: 'reaction', - value: 'smiley_face', - }, - }); - console.log(`Message reaction added successfully: ${response}`); - } catch (error) { - console.log(`Error adding reaction: ${error}`); - } +try { + const response = await pubnub.addMessageAction({ + channel: 'channel_name', + messageTimetoken: 'replace_with_message_timetoken', // Replace with actual message timetoken + action: { + type: 'reaction', + value: 'smiley_face', + }, + }); + console.log('Message reaction added successfully:', response); +} catch (error) { + console.error( + `Error adding reaction: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } -// Execute the function to add a message action -addReactionToMessage(); // snippet.end // snippet.removeMessageActionBasicUsage @@ -35,9 +35,13 @@ try { messageTimetoken: 'replace_with_message_timetoken', actionTimetoken: 'replace_with_action_timetoken', }); - console.log(`Message action removed successfully: ${response}`); + console.log('Message action removed successfully:', response); } catch (error) { - console.log(`Error removing message action: ${error}`); + console.error( + `Error removing message action: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end @@ -50,8 +54,12 @@ try { end: 'replace_with_end_timetoken', limit: 100, }); - console.log(`Message actions retrieved successfully: ${response}`); + console.log('Message actions retrieved successfully:', response); } catch (error) { - console.log(`Error retrieving message actions: ${error}`); + console.error( + `Error retrieving message actions: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end diff --git a/docs-snippets/basic-usage/message-persistence.ts b/docs-snippets/basic-usage/message-persistence.ts index 465a00964..07c2cfd57 100644 --- a/docs-snippets/basic-usage/message-persistence.ts +++ b/docs-snippets/basic-usage/message-persistence.ts @@ -1,52 +1,60 @@ -import PubNub from '../../lib/types'; +import PubNub, { PubNubError } from '../../lib/types'; const pubnub = new PubNub({ publishKey: 'demo', subscribeKey: 'demo', - userId: 'myUniqueUserId' + userId: 'myUniqueUserId', }); // snippet.fetchMessagesBasicUsage // Function to fetch message history -async function fetchHistory() { - try { - const result = await pubnub.fetchMessages({ - channels: ['my-channel'], - count: 1, // Number of messages to retrieve - includeCustomMessageType: true, // if you want to include custom message type in the response - start: 'replace-with-start-timetoken', // start timetoken - end: 'replace-with-end-timetoken' // end timetoken - }); - console.log('Fetched Messages:', result); - } catch (error) { - console.log('Fetch Failed:', error); - } +try { + const result = await pubnub.fetchMessages({ + channels: ['my-channel'], + count: 1, // Number of messages to retrieve + includeCustomMessageType: true, // if you want to include custom message type in the response + start: 'replace-with-start-timetoken', // start timetoken + end: 'replace-with-end-timetoken', // end timetoken + }); + console.log('Fetched Messages:', result); +} catch (error) { + console.error( + `Messages fetch failed: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } - -// Execute the function to fetch message history -fetchHistory(); // snippet.end // snippet.deleteMessagesBasicUsage try { - const result = await pubnub.deleteMessages({ - channel: 'ch1', - start: 'replace-with-start-timetoken', - end: 'replace-with-end-timetoken', - }); -} catch (status) { - console.log(status); + const result = await pubnub.deleteMessages({ + channel: 'ch1', + start: 'replace-with-start-timetoken', + end: 'replace-with-end-timetoken', + }); + console.log('Messages deleted successfully:', result); +} catch (error) { + console.error( + `Messages delete failed: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end // snippet.messageCountBasicUsage try { - const result = await pubnub.messageCounts({ - channels: ["chats.room1", "chats.room2"], - channelTimetokens: ['replace-with-channel-timetoken-(optional)'], - }); -} catch (status) { - console.log(status); + const result = await pubnub.messageCounts({ + channels: ['chats.room1', 'chats.room2'], + channelTimetokens: ['replace-with-channel-timetoken-(optional)'], + }); + console.log('Message counts retrieved successfully:', result); +} catch (error) { + console.error( + `Message counts retrieval failed: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end - diff --git a/docs-snippets/basic-usage/miscellaneous.ts b/docs-snippets/basic-usage/miscellaneous.ts index bd1344332..d46f8cd1b 100644 --- a/docs-snippets/basic-usage/miscellaneous.ts +++ b/docs-snippets/basic-usage/miscellaneous.ts @@ -2,33 +2,26 @@ import PubNub from '../../lib/types'; import fs from 'fs'; const pubnub = new PubNub({ - publishKey: 'demo', - subscribeKey: 'demo', - userId: 'myUniqueUserId', - }); + publishKey: 'demo', + subscribeKey: 'demo', + userId: 'myUniqueUserId', +}); // snippet.encryptMessageBasicUsage // Create a crypto module instance with AES-CBC encryption const cryptoModule = PubNub.CryptoModule.aesCbcCryptoModule({ - cipherKey: "pubnubenigma" - }); - - // Function to encrypt a message - function encryptMessage() { - const msgContent = "This is the data I wish to encrypt."; - console.log(`Original Message: ${msgContent}`); - - // Encrypt the message - const encryptedMessage = cryptoModule.encrypt(JSON.stringify(msgContent)); - console.log(`Encrypted Message: ${encryptedMessage}`); - } - - // Execute the function to encrypt the message - encryptMessage(); + cipherKey: 'pubnubenigma', +}); + +const msgContent = 'This is the data I wish to encrypt.'; +console.log(`Original Message: ${msgContent}`); + +// Encrypt the message +const encryptedMessage = cryptoModule.encrypt(JSON.stringify(msgContent)); +console.log('message encrypted successfully'); // snippet.end // snippet.encryptFileBasicUsage - // Node.js example // import fs from 'fs'; @@ -45,7 +38,6 @@ var decrypted = pubnub.decrypt(encrypted); // Pass the encrypted data as the fir // snippet.end // snippet.decryptFileBasicUsage - const fileBufferData = fs.readFileSync('./cat_picture_encrypted.jpg'); const fileData = pubnub.File.create({ data: fileBuffer, name: 'cat_picture.jpg', mimeType: 'image/jpeg' }); @@ -55,8 +47,8 @@ const decryptedFile = await pubnub.decryptFile(fileData); // snippet.setProxyBasicUsage pubnub.setProxy({ - hostname: 'YOUR_HOSTNAME', - port: 8080, - protocol: 'YOUR_PROTOCOL' + hostname: 'YOUR_HOSTNAME', + port: 8080, + protocol: 'YOUR_PROTOCOL', }); // snippet.end diff --git a/docs-snippets/basic-usage/presence.ts b/docs-snippets/basic-usage/presence.ts index 0fa63c7e3..d0e202259 100644 --- a/docs-snippets/basic-usage/presence.ts +++ b/docs-snippets/basic-usage/presence.ts @@ -1,4 +1,4 @@ -import PubNub from '../../lib/types'; +import PubNub, { PubNubError } from '../../lib/types'; const pubnub = new PubNub({ publishKey: 'demo', @@ -8,23 +8,21 @@ const pubnub = new PubNub({ // snippet.hereNowBasicUsage // Function to get presence information for a channel -async function getHereNow() { - try { - const result = await pubnub.hereNow({ - channels: ['ch1'], - channelGroups: ['cg1'], - includeUUIDs: true, - includeState: true, - }); - console.log(`Here Now Result: ${result}`); - } catch (error) { - console.log(`Here Now failed with error: ${error}`); - } +try { + const result = await pubnub.hereNow({ + channels: ['ch1'], + channelGroups: ['cg1'], + includeUUIDs: true, + includeState: true, + }); + console.log('Here Now Result:', result); +} catch (error) { + console.error( + `Here Now failed with error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } - -// Execute the function to get presence information -getHereNow(); - // snippet.end // snippet.whereNowBasicUsage @@ -32,8 +30,13 @@ try { const response = await pubnub.whereNow({ uuid: 'uuid', }); -} catch (status) { - console.log(status); + console.log('State set successfully:', response); +} catch (error) { + console.error( + `State set failed: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end @@ -44,8 +47,13 @@ try { channels: ['ch1'], channelGroups: ['cg1'], }); -} catch (status) { - console.log(status); + console.log('State set successfully:', response); +} catch (error) { + console.error( + `State set failed: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end @@ -56,21 +64,28 @@ try { channels: ['ch1'], channelGroups: ['cg1'], }); -} catch (status) { - console.log(status); + console.log('State retrieved successfully:', response); +} catch (error) { + console.error( + `State retrieval failed: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end - // snippet.basicUsageWithPromises -pubnub.hereNow({ - channels: ["ch1"], - channelGroups : ["cg1"], - includeUUIDs: true, - includeState: true -}).then((response) => { - console.log(response) -}).catch((error) => { - console.log(error) -}); -// snippet.end \ No newline at end of file +pubnub + .hereNow({ + channels: ['ch1'], + channelGroups: ['cg1'], + includeUUIDs: true, + includeState: true, + }) + .then((response) => { + console.log(response); + }) + .catch((error) => { + console.log(error); + }); +// snippet.end diff --git a/docs-snippets/basic-usage/publish-subscribe.ts b/docs-snippets/basic-usage/publish-subscribe.ts index e74896dd8..aa93eb3b4 100644 --- a/docs-snippets/basic-usage/publish-subscribe.ts +++ b/docs-snippets/basic-usage/publish-subscribe.ts @@ -1,4 +1,4 @@ -import PubNub from '../../lib/types'; +import PubNub, { PubNubError } from '../../lib/types'; const pubnub = new PubNub({ publishKey: 'demo', @@ -7,8 +7,6 @@ const pubnub = new PubNub({ }); // snippet.publishBasicUsage -// Function to publish a message -async function publishMessage() { try { const response = await pubnub.publish({ message: { text: 'Hello World' }, @@ -20,12 +18,12 @@ async function publishMessage() { }); console.log('Publish Success:', response); } catch (error) { - console.log('Publish Failed:', error); + console.error( + `Publish Failed: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } -} - -// Execute the function to publish the message -publishMessage(); // snippet.end // snippet.signalBasicUsage @@ -35,10 +33,14 @@ try { channel: 'foo', customMessageType: 'text-message', }); - console.log(`signal response: ${response}`); -} catch (status) { + console.log('signal response:', response); +} catch (error) { // handle error - console.log(`signal failed with error: ${status}`); + console.error( + `Signal failed with error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end @@ -57,9 +59,13 @@ try { }); console.log(`message published with timetoken: ${response.timetoken}`); -} catch (status) { +} catch (error) { // handle error - console.log(`fire failed with error: ${status}`); + console.error( + `Fire failed with error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end diff --git a/src/core/pubnub-common.ts b/src/core/pubnub-common.ts index 002127cf6..78d2c4019 100644 --- a/src/core/pubnub-common.ts +++ b/src/core/pubnub-common.ts @@ -2792,10 +2792,7 @@ export class PubNubCore< * @param parameters - Request configuration parameters. * @param callback - Request completion handler callback. */ - public grantToken( - parameters: PAM.GrantTokenParameters | PAM.ObjectsGrantTokenParameters, - callback: ResultCallback, - ): void; + public grantToken(parameters: PAM.GrantTokenParameters, callback: ResultCallback): void; /** * Grant token permission. @@ -2806,9 +2803,7 @@ export class PubNubCore< * * @returns Asynchronous grant token response. */ - public async grantToken( - parameters: PAM.GrantTokenParameters | PAM.ObjectsGrantTokenParameters, - ): Promise; + public async grantToken(parameters: PAM.GrantTokenParameters): Promise; /** * Grant token permission. From 27519f14cf1901bc980026729d15d8f81653020f Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Wed, 25 Jun 2025 13:43:07 +0530 Subject: [PATCH 17/27] additional information about send file code snippet in node.js --- docs-snippets/basic-usage/file-sharing.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/docs-snippets/basic-usage/file-sharing.ts b/docs-snippets/basic-usage/file-sharing.ts index fae4f854d..f2e6ce2a8 100644 --- a/docs-snippets/basic-usage/file-sharing.ts +++ b/docs-snippets/basic-usage/file-sharing.ts @@ -10,6 +10,8 @@ const pubnub = new PubNub({ // snippet.sendFileBasicUsage // Function to send a file to a channel try { + // in node.js, make sure to import 'fs' + // and use the createReadStream method to read the file const myFile = fs.createReadStream('./cat_picture.jpg'); const response = await pubnub.sendFile({ From aab00bdca0c25ffa8058b98b133efb60e5b3968e Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Wed, 25 Jun 2025 14:17:57 +0530 Subject: [PATCH 18/27] * address Codacy quality checks suggestions. * Indentation as per other code base --- docs-snippets/access-manager.ts | 8 +- docs-snippets/app-context.ts | 10 +- docs-snippets/basic-usage/access-manager.ts | 6 +- docs-snippets/basic-usage/configuration.ts | 4 +- .../basic-usage/download-file-web.ts | 39 +-- docs-snippets/basic-usage/event-listener.ts | 26 +- docs-snippets/basic-usage/message-actions.ts | 3 +- docs-snippets/basic-usage/miscellaneous.ts | 4 +- docs-snippets/basic-usage/mobile-push.ts | 4 +- .../basic-usage/publish-subscribe.ts | 39 ++- docs-snippets/configuration.ts | 12 +- docs-snippets/event-listener.ts | 30 +- docs-snippets/file-sharing.ts | 8 +- docs-snippets/getting-started-example.ts | 15 +- docs-snippets/getting-started.ts | 15 +- docs-snippets/mobile-push.ts | 11 +- docs-snippets/presence.ts | 6 +- docs-snippets/publish-subscribe.ts | 277 ++++++++++-------- 18 files changed, 283 insertions(+), 234 deletions(-) diff --git a/docs-snippets/access-manager.ts b/docs-snippets/access-manager.ts index e020460b8..ac017afc7 100644 --- a/docs-snippets/access-manager.ts +++ b/docs-snippets/access-manager.ts @@ -47,7 +47,9 @@ try { }); } catch (error) { console.error( - `Grant token error: ${error}.${(error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''}`, + `Grant token error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, ); } // snippet.end @@ -122,7 +124,9 @@ try { }); } catch (error) { console.error( - `Grant token error: ${error}.${(error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : ''}`, + `Grant token error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, ); } // snippet.end diff --git a/docs-snippets/app-context.ts b/docs-snippets/app-context.ts index 935f33159..8aa80eda8 100644 --- a/docs-snippets/app-context.ts +++ b/docs-snippets/app-context.ts @@ -14,7 +14,7 @@ const customField = { visible: 'team' }; // Function to set and then update channel metadata try { - let response = await pubnub.objects.setChannelMetadata({ + const response = await pubnub.objects.setChannelMetadata({ channel: channel, data: { name: name, @@ -25,22 +25,22 @@ try { console.log('The channel has been created with name and description.\n'); // Fetch current object with custom fields - let currentObjectResponse = await pubnub.objects.getChannelMetadata({ + const currentObjectResponse = await pubnub.objects.getChannelMetadata({ channel: channel, include: { customFields: true, }, }); - let currentObject = currentObjectResponse.data; + const currentObject = currentObjectResponse.data; // Initialize the custom field object - let custom = currentObject.custom || {}; + const custom = currentObject.custom || {}; // Add or update the field custom['edit'] = 'admin'; // Writing the updated object back to the server - let setResponse = await pubnub.objects.setChannelMetadata({ + const setResponse = await pubnub.objects.setChannelMetadata({ channel: channel, data: { name: currentObject.name || '', diff --git a/docs-snippets/basic-usage/access-manager.ts b/docs-snippets/basic-usage/access-manager.ts index aa9a66227..57044098d 100644 --- a/docs-snippets/basic-usage/access-manager.ts +++ b/docs-snippets/basic-usage/access-manager.ts @@ -45,12 +45,14 @@ try { // snippet.parseTokenBasicUsage pubnub.parseToken( - 'p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI', + 'p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnc' + + 'tokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI', ); // snippet.end // snippet.setTokenBasicUsage pubnub.setToken( - 'p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI', + 'p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnc' + + 'tokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI', ); // snippet.end diff --git a/docs-snippets/basic-usage/configuration.ts b/docs-snippets/basic-usage/configuration.ts index c6c339680..6d8f7583a 100644 --- a/docs-snippets/basic-usage/configuration.ts +++ b/docs-snippets/basic-usage/configuration.ts @@ -1,7 +1,7 @@ import PubNub from '../../src/web/index'; // snippet.configurationBasicUsageSubscriptionWorkerUrl -var pubnub = new PubNub({ +const pubnub = new PubNub({ subscribeKey: 'demo', publishKey: 'demo', userId: 'unique-user-id', @@ -29,7 +29,7 @@ PubNub.generateUUID(); // snippet.configurationBasicUsage // Initialize PubNub with your keys -var pubnub = new PubNub({ +const pubnubConfig = new PubNub({ subscribeKey: 'YOUR_SUBSCRIBE_KEY', publishKey: 'YOUR_PUBLISH_KEY', userId: 'YOUR_USER_ID', diff --git a/docs-snippets/basic-usage/download-file-web.ts b/docs-snippets/basic-usage/download-file-web.ts index 801c388c2..501459edd 100644 --- a/docs-snippets/basic-usage/download-file-web.ts +++ b/docs-snippets/basic-usage/download-file-web.ts @@ -10,25 +10,26 @@ const pubnub = new PubNub({ // snippet.downloadFileWebBasicUsage // In browser // download the intended file -let file; -try { - file = await pubnub.downloadFile({ - channel: 'my_channel', - id: '...', - name: 'cat_picture.jpg', - }); -} catch (error) { - console.error( - `Download file error: ${error}.${ - (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' - }`, - ); -} +const downloadFile = async () => { + try { + const file = await pubnub.downloadFile({ + channel: 'my_channel', + id: '...', + name: 'cat_picture.jpg', + }); -// have proper html element to display the file -const myImageTag = document.createElement('img'); -myImageTag.src = URL.createObjectURL(await file!.toFile()); + // have proper html element to display the file + const myImageTag = document.createElement('img'); + myImageTag.src = URL.createObjectURL(await file!.toFile()); -// attach the file content to the html element -document.body.appendChild(myImageTag); + // attach the file content to the html element + document.body.appendChild(myImageTag); + } catch (error) { + console.error( + `Download file error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); + } +}; // snippet.end diff --git a/docs-snippets/basic-usage/event-listener.ts b/docs-snippets/basic-usage/event-listener.ts index 2391955f2..b93b2104f 100644 --- a/docs-snippets/basic-usage/event-listener.ts +++ b/docs-snippets/basic-usage/event-listener.ts @@ -8,7 +8,7 @@ const pubnub = new PubNub({ // snippet.eventListenerBasicUsage // create a subscription from a channel entity -const channel = pubnub.channel('channel_1') +const channel = pubnub.channel('channel_1'); const subscription1 = channel.subscription({ receivePresenceEvents: true }); // create a subscription set with multiple channels @@ -16,20 +16,26 @@ const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }); // add a status listener pubnub.addListener({ - status: (s) => {console.log('Status', s.category) } + status: (s) => { + console.log('Status', s.category); + }, }); // add message and presence listeners subscription1.addListener({ - // Messages - message: (m) => { console.log('Received message', m) }, - // Presence - presence: (p) => { console.log('Presence event', p) }, + // Messages + message: (m) => { + console.log('Received message', m); + }, + // Presence + presence: (p) => { + console.log('Presence event', p); + }, }); -// add event-specific message actions listener +// add event-specific message actions listener subscriptionSet1.onMessageAction = (p) => { - console.log('Message action event:', p); + console.log('Message action event:', p); }; subscription1.subscribe(); @@ -39,7 +45,9 @@ subscriptionSet1.subscribe(); // snippet.eventListenerAddConnectionStatusListenersBasicUsage // add a status listener pubnub.addListener({ - status: (s) => {console.log('Status', s.category) } + status: (s) => { + console.log('Status', s.category); + }, }); // snippet.end diff --git a/docs-snippets/basic-usage/message-actions.ts b/docs-snippets/basic-usage/message-actions.ts index 7f0052cc7..44b965789 100644 --- a/docs-snippets/basic-usage/message-actions.ts +++ b/docs-snippets/basic-usage/message-actions.ts @@ -46,7 +46,8 @@ try { // snippet.end // snippet.getMessageActionsBasicUsage -// to get some data in response, first publish a message and then add a message action using addMessageAction() method. +// to get some data in response, first publish a message and then add a message action +// using addMessageAction() method. try { const response = await pubnub.getMessageActions({ channel: 'channel_name', diff --git a/docs-snippets/basic-usage/miscellaneous.ts b/docs-snippets/basic-usage/miscellaneous.ts index d46f8cd1b..a4e08c662 100644 --- a/docs-snippets/basic-usage/miscellaneous.ts +++ b/docs-snippets/basic-usage/miscellaneous.ts @@ -32,9 +32,9 @@ const file = pubnub.File.create({ data: fileBuffer, name: 'cat_picture.jpg', mim const encryptedFile = await pubnub.encryptFile(file); // snippet.end -let encrypted = '..'; +const encrypted = '..'; // snippet.decryptBasicUsage -var decrypted = pubnub.decrypt(encrypted); // Pass the encrypted data as the first parameter in decrypt Method +const decrypted = pubnub.decrypt(encrypted); // Pass the encrypted data as the first parameter in decrypt Method // snippet.end // snippet.decryptFileBasicUsage diff --git a/docs-snippets/basic-usage/mobile-push.ts b/docs-snippets/basic-usage/mobile-push.ts index 297f64dbe..8b2c9b010 100644 --- a/docs-snippets/basic-usage/mobile-push.ts +++ b/docs-snippets/basic-usage/mobile-push.ts @@ -142,8 +142,8 @@ try { // snippet.buildNotificationPayloadBasicUsage -let builder = PubNub.notificationPayload('Chat invitation', "You have been invited to 'quiz' chat"); -let messagePayload = builder.buildPayload(['apns2', 'fcm']); +const builder = PubNub.notificationPayload('Chat invitation', "You have been invited to 'quiz' chat"); +const messagePayload = builder.buildPayload(['apns2', 'fcm']); // add required fields to the payload const response = await pubnub.publish({ diff --git a/docs-snippets/basic-usage/publish-subscribe.ts b/docs-snippets/basic-usage/publish-subscribe.ts index aa93eb3b4..ec7297764 100644 --- a/docs-snippets/basic-usage/publish-subscribe.ts +++ b/docs-snippets/basic-usage/publish-subscribe.ts @@ -7,23 +7,23 @@ const pubnub = new PubNub({ }); // snippet.publishBasicUsage - try { - const response = await pubnub.publish({ - message: { text: 'Hello World' }, - channel: 'my_channel', - sendByPost: false, - storeInHistory: true, - meta: { sender: 'user123' }, - customMessageType: 'text-message', - }); - console.log('Publish Success:', response); - } catch (error) { - console.error( - `Publish Failed: ${error}.${ - (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' - }`, - ); - } +try { + const response = await pubnub.publish({ + message: { text: 'Hello World' }, + channel: 'my_channel', + sendByPost: false, + storeInHistory: true, + meta: { sender: 'user123' }, + customMessageType: 'text-message', + }); + console.log('Publish Success:', response); +} catch (error) { + console.error( + `Publish Failed: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); +} // snippet.end // snippet.signalBasicUsage @@ -124,17 +124,16 @@ groupSubscription1.subscribe(); pubnub.unsubscribeAll(); // snippet.end - // *********** OLD SYNTAX *********** // snippet.OLDsubscribeBasicUsage pubnub.subscribe({ - channels: ["my_channel"], + channels: ['my_channel'], }); // snippet.end // snippet.OLDUnsubscribeBasicUsage pubnub.unsubscribe({ - channels: ["my_channel"], + channels: ['my_channel'], }); // snippet.end diff --git a/docs-snippets/configuration.ts b/docs-snippets/configuration.ts index d2b7e0772..6029fb1ae 100644 --- a/docs-snippets/configuration.ts +++ b/docs-snippets/configuration.ts @@ -3,7 +3,7 @@ import PubNub from '../lib/types'; // snippet.configurationCryptoModule // encrypts using 256-bit AES-CBC cipher (recommended) // decrypts data encrypted with the legacy and the 256 bit AES-CBC ciphers -var pubnub = new PubNub({ +const pubnub = new PubNub({ subscribeKey: 'YOUR_SUBSCRIBE_KEY', userId: 'YOUR_USER_ID', cryptoModule: PubNub.CryptoModule.aesCbcCryptoModule({cipherKey: 'pubnubenigma'}) @@ -11,7 +11,7 @@ var pubnub = new PubNub({ // encrypts with 128-bit cipher key entropy (legacy) // decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers -var pubnub = new PubNub({ +const pubnubLegacy = new PubNub({ subscribeKey: 'YOUR_SUBSCRIBE_KEY', userId: 'YOUR_USER_ID', cryptoModule: PubNub.CryptoModule.legacyCryptoModule({cipherKey: 'pubnubenigma'}) @@ -19,7 +19,7 @@ var pubnub = new PubNub({ // snippet.end // snippet.configurationServerOpertaion -var pubnub = new PubNub({ +const pubnubServer = new PubNub({ subscribeKey: "mySubscribeKey", publishKey: "myPublishKey", userId: "myUniqueUserId", @@ -31,14 +31,14 @@ var pubnub = new PubNub({ // snippet.configurationRealOnlyClient // Initialize for Read Only Client -var pubnub = new PubNub({ +const pubnubReadOnly = new PubNub({ subscribeKey: "mySubscribeKey", userId: "myUniqueUserId" }); // snippet.end // snippet.configurationSSLEnabled -var pubnub = new PubNub({ +const pubnubSSL = new PubNub({ subscribeKey: "mySubscribeKey", publishKey: "myPublishKey", cryptoModule: PubNub.CryptoModule.aesCbcCryptoModule({cipherKey: 'pubnubenigma'}), @@ -50,5 +50,5 @@ var pubnub = new PubNub({ // snippet.end // snippet.generateUUIDdeprected -var uuid = PubNub.generateUUID(); +const uuid = PubNub.generateUUID(); // snippet.end diff --git a/docs-snippets/event-listener.ts b/docs-snippets/event-listener.ts index 70e4993b8..643d5ce34 100644 --- a/docs-snippets/event-listener.ts +++ b/docs-snippets/event-listener.ts @@ -13,12 +13,24 @@ const channel = pubnub.channel('channel_1'); const subscription = channel.subscription(); // Event-specific listeners -subscription.onMessage = (message) => { console.log("Message event: ", message); }; -subscription.onPresence = (presence) => { console.log("Presence event: ", presence); }; -subscription.onSignal = (signal) => { console.log("Signal event: ", signal); }; -subscription.onObjects = (objectsEvent) => { console.log("Objects event: ", objectsEvent); }; -subscription.onMessageAction = (messageActionEvent) => { console.log("Message Reaction event: ", messageActionEvent); }; -subscription.onFile = (fileEvent) => { console.log("File event: ", fileEvent); }; +subscription.onMessage = (message) => { + console.log('Message event: ', message); +}; +subscription.onPresence = (presence) => { + console.log('Presence event: ', presence); +}; +subscription.onSignal = (signal) => { + console.log('Signal event: ', signal); +}; +subscription.onObjects = (objectsEvent) => { + console.log('Objects event: ', objectsEvent); +}; +subscription.onMessageAction = (messageActionEvent) => { + console.log('Message Reaction event: ', messageActionEvent); +}; +subscription.onFile = (fileEvent) => { + console.log('File event: ', fileEvent); +}; // Generic listeners subscription.addListener({ @@ -71,13 +83,13 @@ subscription.addListener({ const publisher = event.publisher; // File publisher const timetoken = event.timetoken; // Event timetoken const message = event.message; // Optional message attached to the file - } + }, }); // snippet.end // snippet.AddConnectionStatusListener pubnub.addListener({ - status: (s) => s.category -}) + status: (s) => s.category, +}); // snippet.end diff --git a/docs-snippets/file-sharing.ts b/docs-snippets/file-sharing.ts index afbad9a7e..9a97c62d1 100644 --- a/docs-snippets/file-sharing.ts +++ b/docs-snippets/file-sharing.ts @@ -27,9 +27,9 @@ try { // snippet.downloadFileCustomCipherKey const file = await pubnub.downloadFile({ - channel: "my_channel", - id: "...", - name: "cat_picture.jpg", - cipherKey: "myCipherKey", + channel: 'my_channel', + id: '...', + name: 'cat_picture.jpg', + cipherKey: 'myCipherKey', }); // snippet.end \ No newline at end of file diff --git a/docs-snippets/getting-started-example.ts b/docs-snippets/getting-started-example.ts index ccf9ddcd7..f8aa6fc12 100644 --- a/docs-snippets/getting-started-example.ts +++ b/docs-snippets/getting-started-example.ts @@ -20,13 +20,14 @@ pubnub.addListener({ // Handle message event console.log('New message:', event.message); // Format and display received message - let displayText; - if (typeof event.message === 'object' && event.message && 'text' in event.message) { - const messageObj = event.message as { text?: string; sender?: string }; - displayText = `${messageObj.sender || 'User'}: ${messageObj.text}`; - } else { - displayText = `Message: ${JSON.stringify(event.message)}`; - } + const displayText = (() => { + if (typeof event.message === 'object' && event.message && 'text' in event.message) { + const messageObj = event.message as { text?: string; sender?: string }; + return `${messageObj.sender || 'User'}: ${messageObj.text}`; + } else { + return `Message: ${JSON.stringify(event.message)}`; + } + })(); console.log(displayText); }, diff --git a/docs-snippets/getting-started.ts b/docs-snippets/getting-started.ts index b9ce0fffa..dc0ebf3a9 100644 --- a/docs-snippets/getting-started.ts +++ b/docs-snippets/getting-started.ts @@ -15,13 +15,14 @@ pubnub.addListener({ // Handle message event console.log("New message:", event.message); // Format and display received message - let displayText; - if (typeof event.message === 'object' && event.message && 'text' in event.message) { - const messageObj = event.message as { text?: string; sender?: string }; - displayText = `${messageObj.sender || 'User'}: ${messageObj.text}`; - } else { - displayText = `Message: ${JSON.stringify(event.message)}`; - } + const displayText = (() => { + if (typeof event.message === 'object' && event.message && 'text' in event.message) { + const messageObj = event.message as { text?: string; sender?: string }; + return `${messageObj.sender || 'User'}: ${messageObj.text}`; + } else { + return `Message: ${JSON.stringify(event.message)}`; + } + })(); console.log(displayText); }, presence: function(event: Subscription.Presence) { diff --git a/docs-snippets/mobile-push.ts b/docs-snippets/mobile-push.ts index d683402b5..d8046d126 100644 --- a/docs-snippets/mobile-push.ts +++ b/docs-snippets/mobile-push.ts @@ -7,14 +7,14 @@ const pubnub = new PubNub({ }); // snippet.simpleNotificationPayloadFCMandAPNS -let builder = PubNub.notificationPayload('Chat invitation', "You have been invited to 'quiz' chat"); +const builder = PubNub.notificationPayload('Chat invitation', "You have been invited to 'quiz' chat"); builder.sound = 'default'; console.log(JSON.stringify(builder.buildPayload(['apns', 'fcm']), null, 2)); // snippet.end // snippet.simpleNotificationPayloadFCMandAPNSH/2 -let payloadBuilder = PubNub.notificationPayload('Chat invitation', "You have been invited to 'quiz' chat"); +const payloadBuilder = PubNub.notificationPayload('Chat invitation', "You have been invited to 'quiz' chat"); payloadBuilder.apns.configurations = [{ targets: [{ topic: 'com.meetings.chat.app' }] }]; payloadBuilder.sound = 'default'; @@ -22,14 +22,17 @@ console.log(JSON.stringify(payloadBuilder.buildPayload(['apns2', 'fcm']), null, // snippet.end // snippet.simpleNotificationPayloadFCMandAPNSH/2CustomConfiguration -let configuration = [ +const configuration = [ { collapseId: 'invitations', expirationDate: new Date(Date.now() + 10000), targets: [{ topic: 'com.meetings.chat.app' }], }, ]; -let customConfigurationBuilder = PubNub.notificationPayload('Chat invitation', "You have been invited to 'quiz' chat"); +const customConfigurationBuilder = PubNub.notificationPayload( + 'Chat invitation', + "You have been invited to 'quiz' chat", +); customConfigurationBuilder.apns.configurations = configuration; console.log(JSON.stringify(customConfigurationBuilder.buildPayload(['apns2', 'fcm']), null, 2)); diff --git a/docs-snippets/presence.ts b/docs-snippets/presence.ts index 2edc08b5e..dfe0f06e3 100644 --- a/docs-snippets/presence.ts +++ b/docs-snippets/presence.ts @@ -9,7 +9,7 @@ const pubnub = new PubNub({ // snippet.hereNowWithState try { const response = await pubnub.hereNow({ - channels: ["my_channel"], + channels: ['my_channel'], includeState: true, }); console.log(`hereNow response: ${response}`); @@ -21,7 +21,7 @@ try { // snippet.hereNowFetchOccupancyOnly try { const response = await pubnub.hereNow({ - channels: ["my_channel"], + channels: ['my_channel'], includeUUIDs: false, }); console.log(`hereNow response: ${response}`); @@ -34,7 +34,7 @@ try { // snippet.hereNowChannelGroup try { const response = await pubnub.hereNow({ - channelGroups: ["my_channel_group"] + channelGroups: ['my_channel_group'], }); console.log(`hereNow response: ${response}`); } catch (status) { diff --git a/docs-snippets/publish-subscribe.ts b/docs-snippets/publish-subscribe.ts index 65b6bc435..0a40d3bc1 100644 --- a/docs-snippets/publish-subscribe.ts +++ b/docs-snippets/publish-subscribe.ts @@ -1,4 +1,4 @@ -import PubNub from '../lib/types'; +import PubNub, { PubNubError } from '../lib/types'; const pubnub = new PubNub({ publishKey: 'demo', @@ -8,88 +8,106 @@ const pubnub = new PubNub({ // snippet.publishJsonSerialisedMessage const newMessage = { - text: 'Hi There!', - }; - - try { - const response = await pubnub.publish({ - message: newMessage, - channel: 'my_channel', - customMessageType: 'text-message', - }); - - console.log(`message published with server response: ${response}`); - } catch (status) { - console.log(`publishing failed with status: ${status}`); - } - // snippet.end - - // snippet.publishStoreThePublishedMessagefor10Hours - try { - const response = await pubnub.publish({ - message: 'hello!', - channel: 'my_channel', - storeInHistory: true, - ttl: 10, - customMessageType: 'text-message', - }); - - console.log(`message published with server response: ${response}`); - } catch (status) { - console.log(`publishing failed with status: ${status}`); - } - // snippet.end - - // snippet.publishSuccessfull + text: 'Hi There!', +}; + +try { const response = await pubnub.publish({ - message: "hello world!", - channel: "ch1", + message: newMessage, + channel: 'my_channel', + customMessageType: 'text-message', }); - - console.log(response); // {timetoken: "14920301569575101"} - // end.snippet - - // snippet.publishUnsuccessfulByNetworkDown - try { - const response = await pubnub.publish({ - message: "hello world!", - channel: "ch1", - }); - } catch (status) { - console.log(status); // {error: true, operation: "PNPublishOperation", errorData: Error, category: "PNNetworkIssuesCategory"} - } - // snippet.end - - // snippet.publishUnsuccessfulWithoutPublishKey - try { - const result = await pubnub.publish({ - message: "hello world!", - channel: "ch1", - }); - } catch (status) { - console.log(status); // {error: true, operation: "PNPublishOperation", statusCode: 400, errorData: Error, category: "PNBadRequestCategory"} - } - // snippet.end - // *********** Compilation Error due to wrong code ***************** - // // snippet.publishUnsuccessfulMissingChannel - // try { - // const result = await pubnub.publish({ - // message: "hello world!", - // }); - // } catch (status) { - // console.log(status); // {message: "Missing Channel", type: "validationError", error: true} - // } - // // snippet.end - - // // snippet.publishUnsuccessfulMissingMessage - // try { - // const result = await pubnub.publish({ - // channel: "ch1", - // }); - // } catch (status) { - // console.log(status); // {message: "Missing Message", type: "validationError", error: true} - // } - // // snippet.end + + console.log('message published with server response:', response); +} catch (error) { + console.error( + `Publish Failed: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); +} +// snippet.end + +// snippet.publishStoreThePublishedMessagefor10Hours +try { + const response = await pubnub.publish({ + message: 'hello!', + channel: 'my_channel', + storeInHistory: true, + ttl: 10, + customMessageType: 'text-message', + }); + + console.log('message published with server response:', response); +} catch (error) { + console.error( + `Publish Failed: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); +} +// snippet.end + +// snippet.publishSuccessfull +const response = await pubnub.publish({ + message: 'hello world!', + channel: 'ch1', +}); + +console.log(response); // {timetoken: "14920301569575101"} +// end.snippet + +// snippet.publishUnsuccessfulByNetworkDown +try { + const response = await pubnub.publish({ + message: 'hello world!', + channel: 'ch1', + }); + console.log('message published with server response:', response); +} catch (error) { + console.error( + `Publish Failed: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); +} +// snippet.end + +// snippet.publishUnsuccessfulWithoutPublishKey +try { + const result = await pubnub.publish({ + message: 'hello world!', + channel: 'ch1', + }); + console.log('message published with server response:', response); +} catch (error) { + console.error( + `Publish Failed: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); +} +// snippet.end +// *********** Compilation Error due to wrong code ***************** +// // snippet.publishUnsuccessfulMissingChannel +// try { +// const result = await pubnub.publish({ +// message: "hello world!", +// }); +// } catch (status) { +// console.log(status); // {message: "Missing Channel", type: "validationError", error: true} +// } +// // snippet.end + +// // snippet.publishUnsuccessfulMissingMessage +// try { +// const result = await pubnub.publish({ +// channel: "ch1", +// }); +// } catch (status) { +// console.log(status); // {message: "Missing Message", type: "validationError", error: true} +// } +// // snippet.end // snippet.createSubscription const channel = pubnub.channel('my_channel'); @@ -99,145 +117,144 @@ channel.subscription(subscriptionOptions); // snippet.end const subscription = pubnub.channel('channel_1').subscription(); -const subscriptionSet = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }) +const subscriptionSet = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }); // snippet.ubsubscribe // `subscription` is an active subscription object -subscription.unsubscribe() +subscription.unsubscribe(); // `subscriptionSet` is an active subscription set object -subscriptionSet.unsubscribe() +subscriptionSet.unsubscribe(); // snippet.end - // snippet.ubsubscribeAll -pubnub.unsubscribeAll() +pubnub.unsubscribeAll(); // snippet.end // *************** OLD SUBSCRIBE SYNTAX *************** // snippet.OLDsubscribeMultipleChannels pubnub.subscribe({ - channels: ['my_channel_1', 'my_channel_2', 'my_channel_3'] + channels: ['my_channel_1', 'my_channel_2', 'my_channel_3'], }); // snippet.end // snippet.OLDsubscribeWithPresence pubnub.subscribe({ - channels: ["my_channel"], + channels: ['my_channel'], withPresence: true, }); // snippet.end // snippet.OLDsubscribeWithWildCardChannels pubnub.subscribe({ - channels: ["ab.*"], + channels: ['ab.*'], }); // snippet.end // snippet.OLDsubscribeWithState pubnub.addListener({ status: async (statusEvent) => { - if (statusEvent.category === "PNConnectedCategory") { - try { - await pubnub.setState({ - state: { - some: "state", - }, - }); - } catch (status) { - // handle setState error - } + if (statusEvent.category === 'PNConnectedCategory') { + try { + await pubnub.setState({ + state: { + some: 'state', + }, + }); + } catch (status) { + // handle setState error } + } }, message: (messageEvent) => { - // handle message + // handle message }, presence: (presenceEvent) => { - // handle presence + // handle presence }, }); pubnub.subscribe({ - channels: ["ch1", "ch2", "ch3"], + channels: ['ch1', 'ch2', 'ch3'], }); // snippet.end // snippet.OLDsubscribeChannelGroup pubnub.subscribe({ - channelGroups: ["my_channelGroup"], + channelGroups: ['my_channelGroup'], }); // snippet.end // snippet.OLDsubscribeChannelGroupWithPresence pubnub.subscribe({ - channelGroups: ["family"], + channelGroups: ['family'], withPresence: true, }); // snippet.end // snippet.OLDsubscribeMultipleChannelGroup pubnub.subscribe({ - channelGroups: ["my_channelGroup1", "my_channelGroup2", "my_channelGroup3"], + channelGroups: ['my_channelGroup1', 'my_channelGroup2', 'my_channelGroup3'], }); // snippet.end // snippet.OLDsubscribeChannelGroupAndChannels pubnub.subscribe({ - channels: ["my_channel"], - channelGroups: ["my_channelGroup"], + channels: ['my_channel'], + channelGroups: ['my_channelGroup'], }); // snippet.end // snippet.OLDUnsubscribeMultipleChannels pubnub.unsubscribe({ - channels: ["chan1", "chan2", "chan3"], + channels: ['chan1', 'chan2', 'chan3'], }); // snippet.end // snippet.OLDUnsubscribeMultipleChannelGroup pubnub.unsubscribe({ - channelGroups: ["demo_group1", "demo_group2"], + channelGroups: ['demo_group1', 'demo_group2'], }); // snippet.end { // snippet.subscriptionSetFrom2IndividualSubscriptions // create a subscription from a channel entity - const channel = pubnub.channel('channel_1') + const channel = pubnub.channel('channel_1'); const subscription1 = channel.subscription({ receivePresenceEvents: true }); - + // create a subscription from a channel group entity - const channelGroup = pubnub.channelGroup('channelGroup_1') + const channelGroup = pubnub.channelGroup('channelGroup_1'); const subscription2 = channelGroup.subscription(); - + // add 2 subscriptions to create a subscription set const subscriptionSet = subscription1.addSubscription(subscription2); - + // add another subscription to the set const subscription3 = pubnub.channel('channel_3').subscription({ receivePresenceEvents: false }); subscriptionSet.addSubscription(subscription3); - + // remove a subscription from a subscription set subscriptionSet.removeSubscription(subscription3); - + subscriptionSet.subscribe(); // snippet.end } { -// snippet.SubscriptionSetFrom2Sets -// create a subscription set with multiple channels -const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }); - -// create a subscription set with multiple channel groups and options -const subscriptionSet2 = pubnub.subscriptionSet({ - channels: ['ch1', 'ch2'], - subscriptionOptions: { receivePresenceEvents: true } -}); + // snippet.SubscriptionSetFrom2Sets + // create a subscription set with multiple channels + const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }); -// add a subscription set to another subscription set -subscriptionSet1.addSubscriptionSet(subscriptionSet2); + // create a subscription set with multiple channel groups and options + const subscriptionSet2 = pubnub.subscriptionSet({ + channels: ['ch1', 'ch2'], + subscriptionOptions: { receivePresenceEvents: true }, + }); -// remove a subscription set from another subscription set -subscriptionSet1.removeSubscriptionSet(subscriptionSet2); -// snippet.end + // add a subscription set to another subscription set + subscriptionSet1.addSubscriptionSet(subscriptionSet2); + + // remove a subscription set from another subscription set + subscriptionSet1.removeSubscriptionSet(subscriptionSet2); + // snippet.end } \ No newline at end of file From 133b27039f340e55f9ea14a2682aace0b5165282 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Wed, 25 Jun 2025 14:39:07 +0530 Subject: [PATCH 19/27] Codacy suggestions --- docs-snippets/basic-usage/file-sharing.ts | 2 +- .../basic-usage/publish-subscribe.ts | 2 +- docs-snippets/configuration.ts | 50 +++++----- docs-snippets/file-sharing.ts | 2 +- docs-snippets/getting-started.ts | 96 +++++++++---------- docs-snippets/import-pubnub.ts | 8 +- docs-snippets/presence.ts | 37 ++++--- docs-snippets/publish-subscribe.ts | 2 +- 8 files changed, 99 insertions(+), 100 deletions(-) diff --git a/docs-snippets/basic-usage/file-sharing.ts b/docs-snippets/basic-usage/file-sharing.ts index f2e6ce2a8..fda173eb6 100644 --- a/docs-snippets/basic-usage/file-sharing.ts +++ b/docs-snippets/basic-usage/file-sharing.ts @@ -90,7 +90,7 @@ try { }`, ); } -let fileContent = await file!.toBlob(); +const fileContent = await file!.toBlob(); // snippet.end // snippet.deleteFileBasicUsage diff --git a/docs-snippets/basic-usage/publish-subscribe.ts b/docs-snippets/basic-usage/publish-subscribe.ts index ec7297764..5d514c770 100644 --- a/docs-snippets/basic-usage/publish-subscribe.ts +++ b/docs-snippets/basic-usage/publish-subscribe.ts @@ -139,4 +139,4 @@ pubnub.unsubscribe({ // snippet.OLDUnsubscribeAllBasicUsage pubnub.unsubscribeAll(); -// snippet.end \ No newline at end of file +// snippet.end diff --git a/docs-snippets/configuration.ts b/docs-snippets/configuration.ts index 6029fb1ae..5c53d7128 100644 --- a/docs-snippets/configuration.ts +++ b/docs-snippets/configuration.ts @@ -4,27 +4,27 @@ import PubNub from '../lib/types'; // encrypts using 256-bit AES-CBC cipher (recommended) // decrypts data encrypted with the legacy and the 256 bit AES-CBC ciphers const pubnub = new PubNub({ - subscribeKey: 'YOUR_SUBSCRIBE_KEY', - userId: 'YOUR_USER_ID', - cryptoModule: PubNub.CryptoModule.aesCbcCryptoModule({cipherKey: 'pubnubenigma'}) - }); - - // encrypts with 128-bit cipher key entropy (legacy) - // decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers + subscribeKey: 'YOUR_SUBSCRIBE_KEY', + userId: 'YOUR_USER_ID', + cryptoModule: PubNub.CryptoModule.aesCbcCryptoModule({ cipherKey: 'pubnubenigma' }), +}); + +// encrypts with 128-bit cipher key entropy (legacy) +// decrypts data encrypted with the legacy and the 256-bit AES-CBC ciphers const pubnubLegacy = new PubNub({ - subscribeKey: 'YOUR_SUBSCRIBE_KEY', - userId: 'YOUR_USER_ID', - cryptoModule: PubNub.CryptoModule.legacyCryptoModule({cipherKey: 'pubnubenigma'}) - }); + subscribeKey: 'YOUR_SUBSCRIBE_KEY', + userId: 'YOUR_USER_ID', + cryptoModule: PubNub.CryptoModule.legacyCryptoModule({ cipherKey: 'pubnubenigma' }), +}); // snippet.end // snippet.configurationServerOpertaion const pubnubServer = new PubNub({ - subscribeKey: "mySubscribeKey", - publishKey: "myPublishKey", - userId: "myUniqueUserId", - secretKey: "secretKey", - heartbeatInterval: 0 + subscribeKey: 'mySubscribeKey', + publishKey: 'myPublishKey', + userId: 'myUniqueUserId', + secretKey: 'secretKey', + heartbeatInterval: 0, }); // snippet.end @@ -32,20 +32,20 @@ const pubnubServer = new PubNub({ // Initialize for Read Only Client const pubnubReadOnly = new PubNub({ - subscribeKey: "mySubscribeKey", - userId: "myUniqueUserId" + subscribeKey: 'mySubscribeKey', + userId: 'myUniqueUserId', }); // snippet.end // snippet.configurationSSLEnabled const pubnubSSL = new PubNub({ - subscribeKey: "mySubscribeKey", - publishKey: "myPublishKey", - cryptoModule: PubNub.CryptoModule.aesCbcCryptoModule({cipherKey: 'pubnubenigma'}), - authKey: "myAuthKey", - logLevel: PubNub.LogLevel.Debug, - userId: "myUniqueUserId", - ssl: true + subscribeKey: 'mySubscribeKey', + publishKey: 'myPublishKey', + cryptoModule: PubNub.CryptoModule.aesCbcCryptoModule({ cipherKey: 'pubnubenigma' }), + authKey: 'myAuthKey', + logLevel: PubNub.LogLevel.Debug, + userId: 'myUniqueUserId', + ssl: true, }); // snippet.end diff --git a/docs-snippets/file-sharing.ts b/docs-snippets/file-sharing.ts index 9a97c62d1..570895936 100644 --- a/docs-snippets/file-sharing.ts +++ b/docs-snippets/file-sharing.ts @@ -32,4 +32,4 @@ const file = await pubnub.downloadFile({ name: 'cat_picture.jpg', cipherKey: 'myCipherKey', }); -// snippet.end \ No newline at end of file +// snippet.end diff --git a/docs-snippets/getting-started.ts b/docs-snippets/getting-started.ts index dc0ebf3a9..4e40fea07 100644 --- a/docs-snippets/getting-started.ts +++ b/docs-snippets/getting-started.ts @@ -2,43 +2,43 @@ import PubNub, { Subscription } from '../lib/types'; // snippet.gettingStartedInitPubnub const pubnub = new PubNub({ - publishKey: 'YOUR_PUBLISH_KEY', - subscribeKey: 'YOUR_SUBSCRIBE_KEY', - userId: 'YOUR_USER_ID' + publishKey: 'YOUR_PUBLISH_KEY', + subscribeKey: 'YOUR_SUBSCRIBE_KEY', + userId: 'YOUR_USER_ID', }); // snippet.end // snippet.gettingStartedEventListeners // Add listener to handle messages, presence events, and connection status pubnub.addListener({ - message: function(event: Subscription.Message) { - // Handle message event - console.log("New message:", event.message); - // Format and display received message - const displayText = (() => { - if (typeof event.message === 'object' && event.message && 'text' in event.message) { - const messageObj = event.message as { text?: string; sender?: string }; - return `${messageObj.sender || 'User'}: ${messageObj.text}`; - } else { - return `Message: ${JSON.stringify(event.message)}`; - } - })(); - console.log(displayText); - }, - presence: function(event: Subscription.Presence) { - // Handle presence event - console.log("Presence event:", event); - console.log("Action:", event.action); // join, leave, timeout - console.log("Channel:", event.channel); - }, - status: function(event) { - // Handle status event - if (event.category === "PNConnectedCategory") { - console.log("Connected to PubNub chat!"); - } else if (event.category === "PNNetworkIssuesCategory") { - console.log("Connection lost. Attempting to reconnect..."); - } + message: function (event: Subscription.Message) { + // Handle message event + console.log('New message:', event.message); + // Format and display received message + const displayText = (() => { + if (typeof event.message === 'object' && event.message && 'text' in event.message) { + const messageObj = event.message as { text?: string; sender?: string }; + return `${messageObj.sender || 'User'}: ${messageObj.text}`; + } else { + return `Message: ${JSON.stringify(event.message)}`; + } + })(); + console.log(displayText); + }, + presence: function (event: Subscription.Presence) { + // Handle presence event + console.log('Presence event:', event); + console.log('Action:', event.action); // join, leave, timeout + console.log('Channel:', event.channel); + }, + status: function (event) { + // Handle status event + if (event.category === 'PNConnectedCategory') { + console.log('Connected to PubNub chat!'); + } else if (event.category === 'PNNetworkIssuesCategory') { + console.log('Connection lost. Attempting to reconnect...'); } + }, }); // snippet.end @@ -48,7 +48,7 @@ const channel = pubnub.channel('hello_world'); // Create a subscription const subscription = channel.subscription({ - receivePresenceEvents: true // to receive presence events + receivePresenceEvents: true, // to receive presence events }); // Subscribe @@ -58,26 +58,26 @@ subscription.subscribe(); // snippet.gettingStartedPublishMessages // Function to publish a message async function publishMessage(text: string) { - if (!text.trim()) return; - - try { - const result = await pubnub.publish({ - message: { - text: text, - sender: pubnub.userId, - time: new Date().toISOString() - }, - channel: 'hello_world' - }); - console.log(`Message published with timetoken: ${result.timetoken}`); - console.log(`You: ${text}`); - } catch (error) { - console.error(`Publish failed: ${error}`); - } + if (!text.trim()) return; + + try { + const result = await pubnub.publish({ + message: { + text: text, + sender: pubnub.userId, + time: new Date().toISOString(), + }, + channel: 'hello_world', + }); + console.log(`Message published with timetoken: ${result.timetoken}`); + console.log(`You: ${text}`); + } catch (error) { + console.error(`Publish failed: ${error}`); + } } // Example: publish a message -const text_message = "Hello, world!"; +const text_message = 'Hello, world!'; publishMessage(text_message); // snippet.end diff --git a/docs-snippets/import-pubnub.ts b/docs-snippets/import-pubnub.ts index 1d502f053..d1ded746e 100644 --- a/docs-snippets/import-pubnub.ts +++ b/docs-snippets/import-pubnub.ts @@ -9,8 +9,8 @@ import fs from 'fs'; // snippet.PubNubinitBasicUsage // Initialize PubNub with your keys const pubnub = new PubNub({ - publishKey: 'YOUR_PUBLISH_KEY', - subscribeKey: 'YOUR_SUBSCRIBE_KEY', - userId: 'YOUR_USER_ID', - }); + publishKey: 'YOUR_PUBLISH_KEY', + subscribeKey: 'YOUR_SUBSCRIBE_KEY', + userId: 'YOUR_USER_ID', +}); // snippet.end diff --git a/docs-snippets/presence.ts b/docs-snippets/presence.ts index dfe0f06e3..fa68b7e3f 100644 --- a/docs-snippets/presence.ts +++ b/docs-snippets/presence.ts @@ -8,36 +8,35 @@ const pubnub = new PubNub({ // snippet.hereNowWithState try { - const response = await pubnub.hereNow({ - channels: ['my_channel'], - includeState: true, - }); - console.log(`hereNow response: ${response}`); + const response = await pubnub.hereNow({ + channels: ['my_channel'], + includeState: true, + }); + console.log(`hereNow response: ${response}`); } catch (status) { - console.log(`hereNow failed with error: ${status}`); + console.log(`hereNow failed with error: ${status}`); } // snippet.end // snippet.hereNowFetchOccupancyOnly try { - const response = await pubnub.hereNow({ - channels: ['my_channel'], - includeUUIDs: false, - }); - console.log(`hereNow response: ${response}`); + const response = await pubnub.hereNow({ + channels: ['my_channel'], + includeUUIDs: false, + }); + console.log(`hereNow response: ${response}`); } catch (status) { - console.log(`hereNow failed with error: ${status}`); + console.log(`hereNow failed with error: ${status}`); } // snippet.end - // snippet.hereNowChannelGroup try { - const response = await pubnub.hereNow({ - channelGroups: ['my_channel_group'], - }); - console.log(`hereNow response: ${response}`); + const response = await pubnub.hereNow({ + channelGroups: ['my_channel_group'], + }); + console.log(`hereNow response: ${response}`); } catch (status) { - console.log(`hereNow failed with error: ${status}`); + console.log(`hereNow failed with error: ${status}`); } -// snippet.end \ No newline at end of file +// snippet.end diff --git a/docs-snippets/publish-subscribe.ts b/docs-snippets/publish-subscribe.ts index 0a40d3bc1..c3ce7d9f1 100644 --- a/docs-snippets/publish-subscribe.ts +++ b/docs-snippets/publish-subscribe.ts @@ -257,4 +257,4 @@ pubnub.unsubscribe({ // remove a subscription set from another subscription set subscriptionSet1.removeSubscriptionSet(subscriptionSet2); // snippet.end -} \ No newline at end of file +} From 772d5754a6441295f6bc4a2195a1f5592f86bd70 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Wed, 25 Jun 2025 15:56:04 +0530 Subject: [PATCH 20/27] lint: codacy suggestion --- docs-snippets/basic-usage/event-listener.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/docs-snippets/basic-usage/event-listener.ts b/docs-snippets/basic-usage/event-listener.ts index b93b2104f..287e02c32 100644 --- a/docs-snippets/basic-usage/event-listener.ts +++ b/docs-snippets/basic-usage/event-listener.ts @@ -50,4 +50,3 @@ pubnub.addListener({ }, }); // snippet.end - From 3907c2d1830106757c2228f3166560f1bae7ccb4 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Wed, 25 Jun 2025 19:08:16 +0530 Subject: [PATCH 21/27] removed deprected warning from deleteMessages API --- dist/web/pubnub.js | 1 - lib/core/pubnub-common.js | 1 - lib/types/index.d.ts | 5 ++--- src/core/pubnub-common.ts | 3 --- 4 files changed, 2 insertions(+), 8 deletions(-) diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index 81765fdcc..0dad6cba4 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -16170,7 +16170,6 @@ * * @returns Asynchronous delete messages response or `void` in case if `callback` provided. * - * @deprecated */ deleteMessages(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { diff --git a/lib/core/pubnub-common.js b/lib/core/pubnub-common.js index faa5e5a4b..1e1f3de41 100644 --- a/lib/core/pubnub-common.js +++ b/lib/core/pubnub-common.js @@ -1502,7 +1502,6 @@ class PubNubCore { * * @returns Asynchronous delete messages response or `void` in case if `callback` provided. * - * @deprecated */ deleteMessages(parameters, callback) { return __awaiter(this, void 0, void 0, function* () { diff --git a/lib/types/index.d.ts b/lib/types/index.d.ts index 305c185f5..0ff777ed2 100644 --- a/lib/types/index.d.ts +++ b/lib/types/index.d.ts @@ -510,7 +510,6 @@ declare class PubNubCore< * @param parameters - Request configuration parameters. * @param callback - Request completion handler callback. * - * @deprecated */ deleteMessages( parameters: PubNub.History.DeleteMessagesParameters, @@ -659,7 +658,7 @@ declare class PubNubCore< * @param callback - Request completion handler callback. */ grantToken( - parameters: PubNub.PAM.GrantTokenParameters | PubNub.PAM.ObjectsGrantTokenParameters, + parameters: PubNub.PAM.GrantTokenParameters, callback: PubNub.ResultCallback, ): void; /** @@ -671,7 +670,7 @@ declare class PubNubCore< * * @returns Asynchronous grant token response. */ - grantToken(parameters: PubNub.PAM.GrantTokenParameters | PubNub.PAM.ObjectsGrantTokenParameters): Promise; + grantToken(parameters: PubNub.PAM.GrantTokenParameters): Promise; /** * Revoke token permission. * diff --git a/src/core/pubnub-common.ts b/src/core/pubnub-common.ts index 78d2c4019..08811b510 100644 --- a/src/core/pubnub-common.ts +++ b/src/core/pubnub-common.ts @@ -2068,7 +2068,6 @@ export class PubNubCore< * @param parameters - Request configuration parameters. * @param callback - Request completion handler callback. * - * @deprecated */ public deleteMessages( parameters: History.DeleteMessagesParameters, @@ -2082,7 +2081,6 @@ export class PubNubCore< * * @returns Asynchronous delete messages response. * - * @deprecated */ public async deleteMessages(parameters: History.DeleteMessagesParameters): Promise; @@ -2094,7 +2092,6 @@ export class PubNubCore< * * @returns Asynchronous delete messages response or `void` in case if `callback` provided. * - * @deprecated */ async deleteMessages( parameters: History.DeleteMessagesParameters, From 89143456532b94bc8272cd34557d4fc251987876 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Thu, 26 Jun 2025 16:40:10 +0530 Subject: [PATCH 22/27] added snippet for connect, disconnect and delete proxy --- docs-snippets/basic-usage/miscellaneous.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs-snippets/basic-usage/miscellaneous.ts b/docs-snippets/basic-usage/miscellaneous.ts index a4e08c662..b2d85a2fa 100644 --- a/docs-snippets/basic-usage/miscellaneous.ts +++ b/docs-snippets/basic-usage/miscellaneous.ts @@ -52,3 +52,15 @@ pubnub.setProxy({ protocol: 'YOUR_PROTOCOL', }); // snippet.end + +// snippet.disconnectBasicUsage +pubnub.disconnect(); +// snippet.end + +// snippet.reconnectBasicUsage +pubnub.reconnect(); +// snippet.end + +// snippet.deleteProxy +pubnub.setProxy(); +// snippet.end From a4910423a0a99cc72634a73fdb08b9c94fbca2aa Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Thu, 26 Jun 2025 17:23:48 +0530 Subject: [PATCH 23/27] code snippets: formating setToken strings --- docs-snippets/basic-usage/access-manager.ts | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/docs-snippets/basic-usage/access-manager.ts b/docs-snippets/basic-usage/access-manager.ts index 57044098d..0d68e3c63 100644 --- a/docs-snippets/basic-usage/access-manager.ts +++ b/docs-snippets/basic-usage/access-manager.ts @@ -44,15 +44,9 @@ try { // snippet.end // snippet.parseTokenBasicUsage -pubnub.parseToken( - 'p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnc' + - 'tokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI', -); +pubnub.parseToken('p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI'); // snippet.end // snippet.setTokenBasicUsage -pubnub.setToken( - 'p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnc' + - 'tokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI', -); +pubnub.setToken('p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI'); // snippet.end From 9be3a027e10b88be39bd32d4d629832f2d4c3015 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Thu, 26 Jun 2025 17:46:30 +0530 Subject: [PATCH 24/27] fix dummy token length related format issue. --- docs-snippets/basic-usage/access-manager.ts | 4 +-- docs-snippets/publish-subscribe.ts | 30 ++++++++++----------- 2 files changed, 16 insertions(+), 18 deletions(-) diff --git a/docs-snippets/basic-usage/access-manager.ts b/docs-snippets/basic-usage/access-manager.ts index 0d68e3c63..356b58107 100644 --- a/docs-snippets/basic-usage/access-manager.ts +++ b/docs-snippets/basic-usage/access-manager.ts @@ -44,9 +44,9 @@ try { // snippet.end // snippet.parseTokenBasicUsage -pubnub.parseToken('p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI'); +pubnub.parseToken('use-token-string-generated-by-grantToken()'); // snippet.end // snippet.setTokenBasicUsage -pubnub.setToken('p0thisAkFl043rhDdHRsCkNyZXisRGNoYW6hanNlY3JldAFDZ3Jwsample3KgQ3NwY6BDcGF0pERjaGFuoENnctokenVzcqBDc3BjoERtZXRhoENzaWdYIGOAeTyWGJI'); +pubnub.setToken('use-token-string-generated-by-grantToken()'); // snippet.end diff --git a/docs-snippets/publish-subscribe.ts b/docs-snippets/publish-subscribe.ts index c3ce7d9f1..b690bc8ec 100644 --- a/docs-snippets/publish-subscribe.ts +++ b/docs-snippets/publish-subscribe.ts @@ -240,21 +240,19 @@ pubnub.unsubscribe({ // snippet.end } -{ - // snippet.SubscriptionSetFrom2Sets - // create a subscription set with multiple channels - const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }); - - // create a subscription set with multiple channel groups and options - const subscriptionSet2 = pubnub.subscriptionSet({ - channels: ['ch1', 'ch2'], - subscriptionOptions: { receivePresenceEvents: true }, - }); +// snippet.SubscriptionSetFrom2Sets +// create a subscription set with multiple channels +const subscriptionSet1 = pubnub.subscriptionSet({ channels: ['ch1', 'ch2'] }); + +// create a subscription set with multiple channel groups and options +const subscriptionSet2 = pubnub.subscriptionSet({ + channels: ['ch1', 'ch2'], + subscriptionOptions: { receivePresenceEvents: true }, +}); - // add a subscription set to another subscription set - subscriptionSet1.addSubscriptionSet(subscriptionSet2); +// add a subscription set to another subscription set +subscriptionSet1.addSubscriptionSet(subscriptionSet2); - // remove a subscription set from another subscription set - subscriptionSet1.removeSubscriptionSet(subscriptionSet2); - // snippet.end -} +// remove a subscription set from another subscription set +subscriptionSet1.removeSubscriptionSet(subscriptionSet2); +// snippet.end From cdfe08287fae7b497475ee505eb16f631f313f2a Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Thu, 26 Jun 2025 18:29:52 +0530 Subject: [PATCH 25/27] code snippet: error handling, additional comments --- docs-snippets/basic-usage/miscellaneous.ts | 3 + docs-snippets/basic-usage/mobile-push.ts | 142 ++++++++++++--------- docs-snippets/event-listener.ts | 2 +- docs-snippets/file-sharing.ts | 10 +- docs-snippets/getting-started-example.ts | 7 +- docs-snippets/getting-started.ts | 16 ++- docs-snippets/message-persistence.ts | 30 +++-- docs-snippets/presence.ts | 32 +++-- docs-snippets/publish-subscribe.ts | 22 +--- 9 files changed, 158 insertions(+), 106 deletions(-) diff --git a/docs-snippets/basic-usage/miscellaneous.ts b/docs-snippets/basic-usage/miscellaneous.ts index b2d85a2fa..56ab7d566 100644 --- a/docs-snippets/basic-usage/miscellaneous.ts +++ b/docs-snippets/basic-usage/miscellaneous.ts @@ -38,6 +38,8 @@ const decrypted = pubnub.decrypt(encrypted); // Pass the encrypted data as the f // snippet.end // snippet.decryptFileBasicUsage +// Node.js example. +// import fs from 'fs'; const fileBufferData = fs.readFileSync('./cat_picture_encrypted.jpg'); const fileData = pubnub.File.create({ data: fileBuffer, name: 'cat_picture.jpg', mimeType: 'image/jpeg' }); @@ -46,6 +48,7 @@ const decryptedFile = await pubnub.decryptFile(fileData); // snippet.end // snippet.setProxyBasicUsage +// This method is only available for NodeJS. pubnub.setProxy({ hostname: 'YOUR_HOSTNAME', port: 8080, diff --git a/docs-snippets/basic-usage/mobile-push.ts b/docs-snippets/basic-usage/mobile-push.ts index 8b2c9b010..c3bbd5b25 100644 --- a/docs-snippets/basic-usage/mobile-push.ts +++ b/docs-snippets/basic-usage/mobile-push.ts @@ -1,4 +1,4 @@ -import PubNub from '../../lib/types'; +import PubNub, { PubNubError } from '../../lib/types'; // Initialize PubNub with demo keys const pubnub = new PubNub({ @@ -9,41 +9,38 @@ const pubnub = new PubNub({ // snippet.addDeciveToChannelBasicUsage // Function to add a device to a channel for APNs2 -async function addDeviceToChannelAPNs2() { - try { - const result = await pubnub.push.addChannels({ - channels: ['a', 'b'], - device: 'niceDevice', - pushGateway: 'apns2', - environment: 'production', - topic: 'com.example.bundle_id', - }); - console.log('Operation done for APNs2!'); - console.log('Response:', result); - } catch (error) { - console.log('Operation failed with error for APNs2:', error); - } +try { + const response = await pubnub.push.addChannels({ + channels: ['a', 'b'], + device: 'niceDevice', + pushGateway: 'apns2', + environment: 'production', + topic: 'com.example.bundle_id', + }); + console.log('device added to channels response:', response); +} catch (error) { + console.error( + `Error adding device to channels: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // Function to add a device to a channel for FCM -async function addDeviceToChannelFCM() { - try { - const result = await pubnub.push.addChannels({ - channels: ['a', 'b'], - device: 'niceDevice', - pushGateway: 'gcm', - }); - console.log('Operation done for FCM!'); - console.log('Response:', result); - } catch (error) { - console.log('Operation failed with error for FCM:', error); - } +try { + const response = await pubnub.push.addChannels({ + channels: ['a', 'b'], + device: 'niceDevice', + pushGateway: 'gcm', + }); + console.log('device added to channels response:', response); +} catch (error) { + console.error( + `Error adding device to channels: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } - -// Execute the functions to add the device to channels -addDeviceToChannelAPNs2(); -addDeviceToChannelFCM(); - // snippet.end // snippet.listChannelsForDeviceBasicUsage @@ -55,12 +52,16 @@ try { environment: 'production', topic: 'com.example.bundle_id', }); - console.log(`listing channels for device response: ${response}`); + console.log('listing channels for device response:', response); response.channels.forEach((channel: string) => { console.log(channel); }); -} catch (status) { - console.log(`listing channels for device failed with error: ${status}`); +} catch (error) { + console.error( + `Error listing channels for device: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // for FCM @@ -70,13 +71,17 @@ try { pushGateway: 'gcm', }); - console.log(`listing channels for device response: ${response}`); + console.log('listing channels for device response:', response); response.channels.forEach((channel: string) => { console.log(channel); }); -} catch (status) { - console.log(`listing channels for device failed with error: ${status}`); +} catch (error) { + console.error( + `Error listing channels for device: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end @@ -91,9 +96,13 @@ try { topic: 'com.example.bundle_id', }); - console.log(`removing device from channel response: ${response}`); -} catch (status) { - console.log(`removing device from channel failed with error: ${status}`); + console.log('removing device from channel response:', response); +} catch (error) { + console.error( + `Error removing device from channel: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // for FCM @@ -104,9 +113,13 @@ try { pushGateway: 'gcm', }); - console.log(`removing device from channel response: ${response}`); -} catch (status) { - console.log(`removing device from channel failed with error: ${status}`); + console.log('removing device from channel response:', response); +} catch (error) { + console.error( + `Error removing device from channel: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end @@ -121,9 +134,13 @@ try { topic: 'com.example.bundle_id', }); - console.log(`deleteDevice response: ${response}`); -} catch (status) { - console.log(`deleteDevice failed with error: ${status}`); + console.log('deleteDevice response:', response); +} catch (error) { + console.error( + `Error deleting device: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // for FCM @@ -133,9 +150,13 @@ try { pushGateway: 'gcm', }); - console.log(`deleteDevice response: ${response}`); -} catch (status) { - console.log(`deleteDevice failed with error: ${status}`); + console.log('deleteDevice response:', response); +} catch (error) { + console.error( + `Error deleting device: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end @@ -145,12 +166,17 @@ try { const builder = PubNub.notificationPayload('Chat invitation', "You have been invited to 'quiz' chat"); const messagePayload = builder.buildPayload(['apns2', 'fcm']); // add required fields to the payload - -const response = await pubnub.publish({ - message: messagePayload, - channel: 'chat-bot', -}); - -console.log(`publish response: ${response}`); - +try { + const response = await pubnub.publish({ + message: messagePayload, + channel: 'chat-bot', + }); + console.log('publish response:', response); +} catch (error) { + console.error( + `Error publishing message: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); +} // snippet.end diff --git a/docs-snippets/event-listener.ts b/docs-snippets/event-listener.ts index 643d5ce34..8c1a4c671 100644 --- a/docs-snippets/event-listener.ts +++ b/docs-snippets/event-listener.ts @@ -61,7 +61,7 @@ subscription.addListener({ }, // App Context objects: (objectEvent) => { - const channel = objectEvent.channel; // Channel to which the event belongs + const channel = objectEvent.channel; // channel Id or a User Id of updated/set app context metadata object const channelGroup = objectEvent.subscription; // Channel group const timetoken = objectEvent.timetoken; // Event timetoken const event = objectEvent.message.data.type; // Event name diff --git a/docs-snippets/file-sharing.ts b/docs-snippets/file-sharing.ts index 570895936..2b7df6dac 100644 --- a/docs-snippets/file-sharing.ts +++ b/docs-snippets/file-sharing.ts @@ -1,4 +1,4 @@ -import PubNub from '../lib/types'; +import PubNub, { PubNubError } from '../lib/types'; const pubnub = new PubNub({ publishKey: 'demo', @@ -19,9 +19,13 @@ try { file: { data: myFile, name: 'cat_picture.jpg', mimeType: 'application/json' }, cipherKey: 'myCipherKey', }); - console.log(`File sent successfully: ${response}`); + console.log('File sent successfully:', response); } catch (error) { - console.error('Error sending file:', error); + console.error( + `Error sending file: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end diff --git a/docs-snippets/getting-started-example.ts b/docs-snippets/getting-started-example.ts index f8aa6fc12..c9c97743c 100644 --- a/docs-snippets/getting-started-example.ts +++ b/docs-snippets/getting-started-example.ts @@ -46,7 +46,12 @@ pubnub.addListener({ console.log('Connected to PubNub chat!'); console.log('Your user ID is:', pubnub.userId); } else if (event.category === 'PNNetworkIssuesCategory') { - console.log('Connection lost. Attempting to reconnect...'); + // if eventEngine is not enabled, this event will be triggered when subscription encounter network issues. + console.log('Connection lost'); + // handle reconnection + } else if (event.category === 'PNDisconnectedUnexpectedlyCategory') { + // If enableEventEngine: true set in the constructor, this event will be triggered when the connection is lost. + console.log('Disconnected unexpectedly.'); } }, }); diff --git a/docs-snippets/getting-started.ts b/docs-snippets/getting-started.ts index 4e40fea07..29d17a19c 100644 --- a/docs-snippets/getting-started.ts +++ b/docs-snippets/getting-started.ts @@ -1,4 +1,4 @@ -import PubNub, { Subscription } from '../lib/types'; +import PubNub, { PubNubError, Subscription } from '../lib/types'; // snippet.gettingStartedInitPubnub const pubnub = new PubNub({ @@ -35,8 +35,14 @@ pubnub.addListener({ // Handle status event if (event.category === 'PNConnectedCategory') { console.log('Connected to PubNub chat!'); + console.log('Your user ID is:', pubnub.userId); } else if (event.category === 'PNNetworkIssuesCategory') { - console.log('Connection lost. Attempting to reconnect...'); + // if eventEngine is not enabled, this event will be triggered when subscription encounter network issues. + console.log('Connection lost'); + // handle reconnection + } else if (event.category === 'PNDisconnectedUnexpectedlyCategory') { + // If enableEventEngine: true set in the constructor, this event will be triggered when the connection is lost. + console.log('Disconnected unexpectedly.'); } }, }); @@ -72,7 +78,11 @@ async function publishMessage(text: string) { console.log(`Message published with timetoken: ${result.timetoken}`); console.log(`You: ${text}`); } catch (error) { - console.error(`Publish failed: ${error}`); + console.error( + `Publish failed: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } } diff --git a/docs-snippets/message-persistence.ts b/docs-snippets/message-persistence.ts index 57675b49a..52e939aa3 100644 --- a/docs-snippets/message-persistence.ts +++ b/docs-snippets/message-persistence.ts @@ -1,4 +1,4 @@ -import PubNub from '../lib/types'; +import PubNub, { PubNubError } from '../lib/types'; const pubnub = new PubNub({ publishKey: 'demo', @@ -15,9 +15,13 @@ try { includeMessageActions: true, includeCustomMessageType: true, }); - console.log(`fetch messages response: ${response}`); -} catch (status) { - console.log(`fetch messages failed with error: ${status}`); + console.log('fetch messages response:', response); +} catch (error) { + console.error( + `fetch messages failed with error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end @@ -28,9 +32,13 @@ try { start: 'replace-with-start-timetoken', end: 'replace-with-end-timetoken', }); - console.log(`delete messages response: ${response}`); + console.log('delete messages response:', response); } catch (error) { - console.log(`delete messages failed with error: ${error}`); + console.error( + `delete messages failed with error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end @@ -44,8 +52,12 @@ try { 'replace-with-channel-timetoken-ch3', // timetoken for channel ch3 ], }); - console.log(`message count response: ${response}`); -} catch (status) { - console.log(`message count failed with error: ${status}`); + console.log('message count response:', response); +} catch (error) { + console.error( + `message count failed with error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end diff --git a/docs-snippets/presence.ts b/docs-snippets/presence.ts index fa68b7e3f..57fdbc8af 100644 --- a/docs-snippets/presence.ts +++ b/docs-snippets/presence.ts @@ -1,4 +1,4 @@ -import PubNub from '../lib/types'; +import PubNub, { PubNubError } from '../lib/types'; const pubnub = new PubNub({ publishKey: 'demo', @@ -12,9 +12,13 @@ try { channels: ['my_channel'], includeState: true, }); - console.log(`hereNow response: ${response}`); -} catch (status) { - console.log(`hereNow failed with error: ${status}`); + console.log('hereNow response:', response); +} catch (error) { + console.error( + `hereNow failed with error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end @@ -24,9 +28,13 @@ try { channels: ['my_channel'], includeUUIDs: false, }); - console.log(`hereNow response: ${response}`); -} catch (status) { - console.log(`hereNow failed with error: ${status}`); + console.log('hereNow response:', response); +} catch (error) { + console.error( + `hereNow failed with error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end @@ -35,8 +43,12 @@ try { const response = await pubnub.hereNow({ channelGroups: ['my_channel_group'], }); - console.log(`hereNow response: ${response}`); -} catch (status) { - console.log(`hereNow failed with error: ${status}`); + console.log('hereNow response:', response); +} catch (error) { + console.error( + `hereNow failed with error: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } // snippet.end diff --git a/docs-snippets/publish-subscribe.ts b/docs-snippets/publish-subscribe.ts index b690bc8ec..4d16b1685 100644 --- a/docs-snippets/publish-subscribe.ts +++ b/docs-snippets/publish-subscribe.ts @@ -88,26 +88,6 @@ try { ); } // snippet.end -// *********** Compilation Error due to wrong code ***************** -// // snippet.publishUnsuccessfulMissingChannel -// try { -// const result = await pubnub.publish({ -// message: "hello world!", -// }); -// } catch (status) { -// console.log(status); // {message: "Missing Channel", type: "validationError", error: true} -// } -// // snippet.end - -// // snippet.publishUnsuccessfulMissingMessage -// try { -// const result = await pubnub.publish({ -// channel: "ch1", -// }); -// } catch (status) { -// console.log(status); // {message: "Missing Message", type: "validationError", error: true} -// } -// // snippet.end // snippet.createSubscription const channel = pubnub.channel('my_channel'); @@ -160,7 +140,7 @@ pubnub.addListener({ some: 'state', }, }); - } catch (status) { + } catch (error) { // handle setState error } } From 475b1dd8c73a4b81ecaa0a4d591b62ccf1197b85 Mon Sep 17 00:00:00 2001 From: Mohit Tejani Date: Fri, 27 Jun 2025 22:42:34 +0530 Subject: [PATCH 26/27] details about exception in getting started example. --- docs-snippets/getting-started-example.ts | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/docs-snippets/getting-started-example.ts b/docs-snippets/getting-started-example.ts index c9c97743c..4aef88cd5 100644 --- a/docs-snippets/getting-started-example.ts +++ b/docs-snippets/getting-started-example.ts @@ -1,4 +1,4 @@ -import PubNub from '../lib/types'; +import PubNub, { PubNubError } from '../lib/types'; // snippet.gettingStartedCompleteExample // Save this file as index.js/.ts @@ -85,15 +85,18 @@ async function publishMessage(text: string) { }); // Success message (timetoken is the unique ID for this message) - console.log(`\nMessage sent successfully!`); + console.log(`\n✅ Message sent successfully!`); } catch (error) { // Handle publish errors - console.error(`\n❌ Failed to send message: ${error}`); + console.error( + `\n❌ Failed to send message: ${error}.${ + (error as PubNubError).status ? ` Additional information: ${(error as PubNubError).status}` : '' + }`, + ); } } // 7. define the message and Publish that message. const text_message = 'Hello, world!'; publishMessage(text_message); - // snippet.end From 8ac814d08352819dc824e1e118e450d5e4c70e3e Mon Sep 17 00:00:00 2001 From: PubNub Release Bot <120067856+pubnub-release-bot@users.noreply.github.com> Date: Mon, 30 Jun 2025 05:54:04 +0000 Subject: [PATCH 27/27] PubNub SDK v9.6.2 release. --- .pubnub.yml | 13 ++++++++++--- CHANGELOG.md | 7 +++++++ README.md | 4 ++-- dist/web/pubnub.js | 2 +- dist/web/pubnub.min.js | 2 +- lib/core/components/configuration.js | 2 +- lib/types/index.d.ts | 1 + package.json | 2 +- src/core/components/configuration.ts | 2 +- 9 files changed, 25 insertions(+), 10 deletions(-) diff --git a/.pubnub.yml b/.pubnub.yml index 2ef3dc6de..c37c75d49 100644 --- a/.pubnub.yml +++ b/.pubnub.yml @@ -1,5 +1,12 @@ --- changelog: + - date: 2025-06-30 + version: v9.6.2 + changes: + - type: improvement + text: "Removed deprecation warning from deleteMessages method." + - type: improvement + text: "Added code snippets for docs." - date: 2025-06-18 version: v9.6.1 changes: @@ -1256,7 +1263,7 @@ supported-platforms: - 'Ubuntu 14.04 and up' - 'Windows 7 and up' version: 'Pubnub Javascript for Node' -version: '9.6.1' +version: '9.6.2' sdks: - full-name: PubNub Javascript SDK short-name: Javascript @@ -1272,7 +1279,7 @@ sdks: - distribution-type: source distribution-repository: GitHub release package-name: pubnub.js - location: https://github.com/pubnub/javascript/archive/refs/tags/v9.6.1.zip + location: https://github.com/pubnub/javascript/archive/refs/tags/v9.6.2.zip requires: - name: 'agentkeepalive' min-version: '3.5.2' @@ -1943,7 +1950,7 @@ sdks: - distribution-type: library distribution-repository: GitHub release package-name: pubnub.js - location: https://github.com/pubnub/javascript/releases/download/v9.6.1/pubnub.9.6.1.js + location: https://github.com/pubnub/javascript/releases/download/v9.6.2/pubnub.9.6.2.js requires: - name: 'agentkeepalive' min-version: '3.5.2' diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b614fea7..c2d1c4f27 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,10 @@ +## v9.6.2 +June 30 2025 + +#### Modified +- Removed deprecation warning from deleteMessages method. +- Added code snippets for docs. + ## v9.6.1 June 18 2025 diff --git a/README.md b/README.md index a3903519b..364ab4c0d 100644 --- a/README.md +++ b/README.md @@ -27,8 +27,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.9.6.1.js - * https://cdn.pubnub.com/sdk/javascript/pubnub.9.6.1.min.js + * https://cdn.pubnub.com/sdk/javascript/pubnub.9.6.2.js + * https://cdn.pubnub.com/sdk/javascript/pubnub.9.6.2.min.js 2. Configure your keys: diff --git a/dist/web/pubnub.js b/dist/web/pubnub.js index 0dad6cba4..a62e0d50c 100644 --- a/dist/web/pubnub.js +++ b/dist/web/pubnub.js @@ -4957,7 +4957,7 @@ return base.PubNubFile; }, get version() { - return '9.6.1'; + return '9.6.2'; }, getVersion() { return this.version; diff --git a/dist/web/pubnub.min.js b/dist/web/pubnub.min.js index 42be16df3..76943c7fd 100644 --- a/dist/web/pubnub.min.js +++ b/dist/web/pubnub.min.js @@ -1,2 +1,2 @@ !function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).PubNub=t()}(this,(function(){"use strict";var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function t(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var s={exports:{}};!function(t){!function(e,s){var n=Math.pow(2,-24),r=Math.pow(2,32),i=Math.pow(2,53);var a={encode:function(e){var t,n=new ArrayBuffer(256),a=new DataView(n),o=0;function c(e){for(var s=n.byteLength,r=o+e;s>2,u=0;u>6),r.push(128|63&a)):a<55296?(r.push(224|a>>12),r.push(128|a>>6&63),r.push(128|63&a)):(a=(1023&a)<<10,a|=1023&t.charCodeAt(++n),a+=65536,r.push(240|a>>18),r.push(128|a>>12&63),r.push(128|a>>6&63),r.push(128|63&a))}return d(3,r.length),h(r);default:var p;if(Array.isArray(t))for(d(4,p=t.length),n=0;n>5!==e)throw"Invalid indefinite length element";return s}function m(e,t){for(var s=0;s>10),e.push(56320|1023&n))}}"function"!=typeof t&&(t=function(e){return e}),"function"!=typeof i&&(i=function(){return s});var y=function e(){var r,d,y=l(),f=y>>5,v=31&y;if(7===f)switch(v){case 25:return function(){var e=new ArrayBuffer(4),t=new DataView(e),s=h(),r=32768&s,i=31744&s,a=1023&s;if(31744===i)i=261120;else if(0!==i)i+=114688;else if(0!==a)return a*n;return t.setUint32(0,r<<16|i<<13|a<<13),t.getFloat32(0)}();case 26:return c(a.getFloat32(o),4);case 27:return c(a.getFloat64(o),8)}if((d=g(v))<0&&(f<2||6=0;)w+=d,S.push(u(d));var O=new Uint8Array(w),k=0;for(r=0;r=0;)m(C,d);else m(C,d);return String.fromCharCode.apply(null,C);case 4:var P;if(d<0)for(P=[];!p();)P.push(e());else for(P=new Array(d),r=0;re.toString())).join(", ")}]}`}}a.encoder=new TextEncoder,a.decoder=new TextDecoder;class o{static create(e){return new o(e)}constructor(e){let t,s,n,r;if(e instanceof File)r=e,n=e.name,s=e.type,t=e.size;else if("data"in e){const i=e.data;s=e.mimeType,n=e.name,r=new File([i],n,{type:s}),t=r.size}if(void 0===r)throw new Error("Couldn't construct a file out of supplied options.");if(void 0===n)throw new Error("Couldn't guess filename out of the options. Please provide one.");t&&(this.contentLength=t),this.mimeType=s,this.data=r,this.name=n}toBuffer(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toArrayBuffer(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const s=new FileReader;s.addEventListener("load",(()=>{if(s.result instanceof ArrayBuffer)return e(s.result)})),s.addEventListener("error",(()=>t(s.error))),s.readAsArrayBuffer(this.data)}))}))}toString(){return i(this,void 0,void 0,(function*(){return new Promise(((e,t)=>{const s=new FileReader;s.addEventListener("load",(()=>{if("string"==typeof s.result)return e(s.result)})),s.addEventListener("error",(()=>{t(s.error)})),s.readAsBinaryString(this.data)}))}))}toStream(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in Node.js environments.")}))}toFile(){return i(this,void 0,void 0,(function*(){return this.data}))}toFileUri(){return i(this,void 0,void 0,(function*(){throw new Error("This feature is only supported in React Native environments.")}))}toBlob(){return i(this,void 0,void 0,(function*(){return this.data}))}}o.supportsBlob="undefined"!=typeof Blob,o.supportsFile="undefined"!=typeof File,o.supportsBuffer=!1,o.supportsStream=!1,o.supportsString=!0,o.supportsArrayBuffer=!0,o.supportsEncryptFile=!0,o.supportsFileUri=!1;function c(e){const t=e.replace(/==?$/,""),s=Math.floor(t.length/4*3),n=new ArrayBuffer(s),r=new Uint8Array(n);let i=0;function a(){const e=t.charAt(i++),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(e);if(-1===s)throw new Error(`Illegal character at ${i}: ${t.charAt(i-1)}`);return s}for(let e=0;e>4,c=(15&s)<<4|n>>2,u=(3&n)<<6|i;r[e]=o,64!=n&&(r[e+1]=c),64!=i&&(r[e+2]=u)}return n}function u(e){let t="";const s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",n=new Uint8Array(e),r=n.byteLength,i=r%3,a=r-i;let o,c,u,l,h;for(let e=0;e>18,c=(258048&h)>>12,u=(4032&h)>>6,l=63&h,t+=s[o]+s[c]+s[u]+s[l];return 1==i?(h=n[a],o=(252&h)>>2,c=(3&h)<<4,t+=s[o]+s[c]+"=="):2==i&&(h=n[a]<<8|n[a+1],o=(64512&h)>>10,c=(1008&h)>>4,u=(15&h)<<2,t+=s[o]+s[c]+s[u]+"="),t}var l;!function(e){e.PNNetworkIssuesCategory="PNNetworkIssuesCategory",e.PNTimeoutCategory="PNTimeoutCategory",e.PNCancelledCategory="PNCancelledCategory",e.PNBadRequestCategory="PNBadRequestCategory",e.PNAccessDeniedCategory="PNAccessDeniedCategory",e.PNValidationErrorCategory="PNValidationErrorCategory",e.PNAcknowledgmentCategory="PNAcknowledgmentCategory",e.PNMalformedResponseCategory="PNMalformedResponseCategory",e.PNUnknownCategory="PNUnknownCategory",e.PNNetworkUpCategory="PNNetworkUpCategory",e.PNNetworkDownCategory="PNNetworkDownCategory",e.PNReconnectedCategory="PNReconnectedCategory",e.PNConnectedCategory="PNConnectedCategory",e.PNSubscriptionChangedCategory="PNSubscriptionChangedCategory",e.PNRequestMessageCountExceededCategory="PNRequestMessageCountExceededCategory",e.PNDisconnectedCategory="PNDisconnectedCategory",e.PNConnectionErrorCategory="PNConnectionErrorCategory",e.PNDisconnectedUnexpectedlyCategory="PNDisconnectedUnexpectedlyCategory"}(l||(l={}));var h=l;class d extends Error{constructor(e,t){super(e),this.status=t,this.name="PubNubError",this.message=e,Object.setPrototypeOf(this,new.target.prototype)}}function p(e,t){var s;return null!==(s=e.statusCode)&&void 0!==s||(e.statusCode=0),Object.assign(Object.assign({},e),{statusCode:e.statusCode,category:t,error:!0})}function g(e,t){return p(Object.assign(Object.assign({message:"Unable to deserialize service response"},void 0!==e?{responseText:e}:{}),void 0!==t?{statusCode:t}:{}),h.PNMalformedResponseCategory)}var b,m,y,f,v,S=S||function(e){var t={},s=t.lib={},n=function(){},r=s.Base={extend:function(e){n.prototype=this;var t=new n;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)}},i=s.WordArray=r.extend({init:function(e,t){e=this.words=e||[],this.sigBytes=null!=t?t:4*e.length},toString:function(e){return(e||o).stringify(this)},concat:function(e){var t=this.words,s=e.words,n=this.sigBytes;if(e=e.sigBytes,this.clamp(),n%4)for(var r=0;r>>2]|=(s[r>>>2]>>>24-r%4*8&255)<<24-(n+r)%4*8;else if(65535>>2]=s[r>>>2];else t.push.apply(t,s);return this.sigBytes+=e,this},clamp:function(){var t=this.words,s=this.sigBytes;t[s>>>2]&=4294967295<<32-s%4*8,t.length=e.ceil(s/4)},clone:function(){var e=r.clone.call(this);return e.words=this.words.slice(0),e},random:function(t){for(var s=[],n=0;n>>2]>>>24-n%4*8&255;s.push((r>>>4).toString(16)),s.push((15&r).toString(16))}return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>3]|=parseInt(e.substr(n,2),16)<<24-n%8*4;return new i.init(s,t/2)}},c=a.Latin1={stringify:function(e){var t=e.words;e=e.sigBytes;for(var s=[],n=0;n>>2]>>>24-n%4*8&255));return s.join("")},parse:function(e){for(var t=e.length,s=[],n=0;n>>2]|=(255&e.charCodeAt(n))<<24-n%4*8;return new i.init(s,t)}},u=a.Utf8={stringify:function(e){try{return decodeURIComponent(escape(c.stringify(e)))}catch(e){throw Error("Malformed UTF-8 data")}},parse:function(e){return c.parse(unescape(encodeURIComponent(e)))}},l=s.BufferedBlockAlgorithm=r.extend({reset:function(){this._data=new i.init,this._nDataBytes=0},_append:function(e){"string"==typeof e&&(e=u.parse(e)),this._data.concat(e),this._nDataBytes+=e.sigBytes},_process:function(t){var s=this._data,n=s.words,r=s.sigBytes,a=this.blockSize,o=r/(4*a);if(t=(o=t?e.ceil(o):e.max((0|o)-this._minBufferSize,0))*a,r=e.min(4*t,r),t){for(var c=0;cu;){var l;e:{l=c;for(var h=e.sqrt(l),d=2;d<=h;d++)if(!(l%d)){l=!1;break e}l=!0}l&&(8>u&&(i[u]=o(e.pow(c,.5))),a[u]=o(e.pow(c,1/3)),u++),c++}var p=[];r=r.SHA256=n.extend({_doReset:function(){this._hash=new s.init(i.slice(0))},_doProcessBlock:function(e,t){for(var s=this._hash.words,n=s[0],r=s[1],i=s[2],o=s[3],c=s[4],u=s[5],l=s[6],h=s[7],d=0;64>d;d++){if(16>d)p[d]=0|e[t+d];else{var g=p[d-15],b=p[d-2];p[d]=((g<<25|g>>>7)^(g<<14|g>>>18)^g>>>3)+p[d-7]+((b<<15|b>>>17)^(b<<13|b>>>19)^b>>>10)+p[d-16]}g=h+((c<<26|c>>>6)^(c<<21|c>>>11)^(c<<7|c>>>25))+(c&u^~c&l)+a[d]+p[d],b=((n<<30|n>>>2)^(n<<19|n>>>13)^(n<<10|n>>>22))+(n&r^n&i^r&i),h=l,l=u,u=c,c=o+g|0,o=i,i=r,r=n,n=g+b|0}s[0]=s[0]+n|0,s[1]=s[1]+r|0,s[2]=s[2]+i|0,s[3]=s[3]+o|0,s[4]=s[4]+c|0,s[5]=s[5]+u|0,s[6]=s[6]+l|0,s[7]=s[7]+h|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;return s[r>>>5]|=128<<24-r%32,s[14+(r+64>>>9<<4)]=e.floor(n/4294967296),s[15+(r+64>>>9<<4)]=n,t.sigBytes=4*s.length,this._process(),this._hash},clone:function(){var e=n.clone.call(this);return e._hash=this._hash.clone(),e}});t.SHA256=n._createHelper(r),t.HmacSHA256=n._createHmacHelper(r)}(Math),m=(b=S).enc.Utf8,b.algo.HMAC=b.lib.Base.extend({init:function(e,t){e=this._hasher=new e.init,"string"==typeof t&&(t=m.parse(t));var s=e.blockSize,n=4*s;t.sigBytes>n&&(t=e.finalize(t)),t.clamp();for(var r=this._oKey=t.clone(),i=this._iKey=t.clone(),a=r.words,o=i.words,c=0;c>>2]>>>24-r%4*8&255)<<16|(t[r+1>>>2]>>>24-(r+1)%4*8&255)<<8|t[r+2>>>2]>>>24-(r+2)%4*8&255,a=0;4>a&&r+.75*a>>6*(3-a)&63));if(t=n.charAt(64))for(;e.length%4;)e.push(t);return e.join("")},parse:function(e){var t=e.length,s=this._map;(n=s.charAt(64))&&-1!=(n=e.indexOf(n))&&(t=n);for(var n=[],r=0,i=0;i>>6-i%4*2;n[r>>>2]|=(a|o)<<24-r%4*8,r++}return f.create(n,r)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="},function(e){function t(e,t,s,n,r,i,a){return((e=e+(t&s|~t&n)+r+a)<>>32-i)+t}function s(e,t,s,n,r,i,a){return((e=e+(t&n|s&~n)+r+a)<>>32-i)+t}function n(e,t,s,n,r,i,a){return((e=e+(t^s^n)+r+a)<>>32-i)+t}function r(e,t,s,n,r,i,a){return((e=e+(s^(t|~n))+r+a)<>>32-i)+t}for(var i=S,a=(c=i.lib).WordArray,o=c.Hasher,c=i.algo,u=[],l=0;64>l;l++)u[l]=4294967296*e.abs(e.sin(l+1))|0;c=c.MD5=o.extend({_doReset:function(){this._hash=new a.init([1732584193,4023233417,2562383102,271733878])},_doProcessBlock:function(e,i){for(var a=0;16>a;a++){var o=e[c=i+a];e[c]=16711935&(o<<8|o>>>24)|4278255360&(o<<24|o>>>8)}a=this._hash.words;var c=e[i+0],l=(o=e[i+1],e[i+2]),h=e[i+3],d=e[i+4],p=e[i+5],g=e[i+6],b=e[i+7],m=e[i+8],y=e[i+9],f=e[i+10],v=e[i+11],S=e[i+12],w=e[i+13],O=e[i+14],k=e[i+15],C=t(C=a[0],E=a[1],j=a[2],P=a[3],c,7,u[0]),P=t(P,C,E,j,o,12,u[1]),j=t(j,P,C,E,l,17,u[2]),E=t(E,j,P,C,h,22,u[3]);C=t(C,E,j,P,d,7,u[4]),P=t(P,C,E,j,p,12,u[5]),j=t(j,P,C,E,g,17,u[6]),E=t(E,j,P,C,b,22,u[7]),C=t(C,E,j,P,m,7,u[8]),P=t(P,C,E,j,y,12,u[9]),j=t(j,P,C,E,f,17,u[10]),E=t(E,j,P,C,v,22,u[11]),C=t(C,E,j,P,S,7,u[12]),P=t(P,C,E,j,w,12,u[13]),j=t(j,P,C,E,O,17,u[14]),C=s(C,E=t(E,j,P,C,k,22,u[15]),j,P,o,5,u[16]),P=s(P,C,E,j,g,9,u[17]),j=s(j,P,C,E,v,14,u[18]),E=s(E,j,P,C,c,20,u[19]),C=s(C,E,j,P,p,5,u[20]),P=s(P,C,E,j,f,9,u[21]),j=s(j,P,C,E,k,14,u[22]),E=s(E,j,P,C,d,20,u[23]),C=s(C,E,j,P,y,5,u[24]),P=s(P,C,E,j,O,9,u[25]),j=s(j,P,C,E,h,14,u[26]),E=s(E,j,P,C,m,20,u[27]),C=s(C,E,j,P,w,5,u[28]),P=s(P,C,E,j,l,9,u[29]),j=s(j,P,C,E,b,14,u[30]),C=n(C,E=s(E,j,P,C,S,20,u[31]),j,P,p,4,u[32]),P=n(P,C,E,j,m,11,u[33]),j=n(j,P,C,E,v,16,u[34]),E=n(E,j,P,C,O,23,u[35]),C=n(C,E,j,P,o,4,u[36]),P=n(P,C,E,j,d,11,u[37]),j=n(j,P,C,E,b,16,u[38]),E=n(E,j,P,C,f,23,u[39]),C=n(C,E,j,P,w,4,u[40]),P=n(P,C,E,j,c,11,u[41]),j=n(j,P,C,E,h,16,u[42]),E=n(E,j,P,C,g,23,u[43]),C=n(C,E,j,P,y,4,u[44]),P=n(P,C,E,j,S,11,u[45]),j=n(j,P,C,E,k,16,u[46]),C=r(C,E=n(E,j,P,C,l,23,u[47]),j,P,c,6,u[48]),P=r(P,C,E,j,b,10,u[49]),j=r(j,P,C,E,O,15,u[50]),E=r(E,j,P,C,p,21,u[51]),C=r(C,E,j,P,S,6,u[52]),P=r(P,C,E,j,h,10,u[53]),j=r(j,P,C,E,f,15,u[54]),E=r(E,j,P,C,o,21,u[55]),C=r(C,E,j,P,m,6,u[56]),P=r(P,C,E,j,k,10,u[57]),j=r(j,P,C,E,g,15,u[58]),E=r(E,j,P,C,w,21,u[59]),C=r(C,E,j,P,d,6,u[60]),P=r(P,C,E,j,v,10,u[61]),j=r(j,P,C,E,l,15,u[62]),E=r(E,j,P,C,y,21,u[63]);a[0]=a[0]+C|0,a[1]=a[1]+E|0,a[2]=a[2]+j|0,a[3]=a[3]+P|0},_doFinalize:function(){var t=this._data,s=t.words,n=8*this._nDataBytes,r=8*t.sigBytes;s[r>>>5]|=128<<24-r%32;var i=e.floor(n/4294967296);for(s[15+(r+64>>>9<<4)]=16711935&(i<<8|i>>>24)|4278255360&(i<<24|i>>>8),s[14+(r+64>>>9<<4)]=16711935&(n<<8|n>>>24)|4278255360&(n<<24|n>>>8),t.sigBytes=4*(s.length+1),this._process(),s=(t=this._hash).words,n=0;4>n;n++)r=s[n],s[n]=16711935&(r<<8|r>>>24)|4278255360&(r<<24|r>>>8);return t},clone:function(){var e=o.clone.call(this);return e._hash=this._hash.clone(),e}}),i.MD5=o._createHelper(c),i.HmacMD5=o._createHmacHelper(c)}(Math),function(){var e,t=S,s=(e=t.lib).Base,n=e.WordArray,r=(e=t.algo).EvpKDF=s.extend({cfg:s.extend({keySize:4,hasher:e.MD5,iterations:1}),init:function(e){this.cfg=this.cfg.extend(e)},compute:function(e,t){for(var s=(o=this.cfg).hasher.create(),r=n.create(),i=r.words,a=o.keySize,o=o.iterations;i.length>>2]}},e.BlockCipher=a.extend({cfg:a.cfg.extend({mode:o,padding:u}),reset:function(){a.reset.call(this);var e=(t=this.cfg).iv,t=t.mode;if(this._xformMode==this._ENC_XFORM_MODE)var s=t.createEncryptor;else s=t.createDecryptor,this._minBufferSize=1;this._mode=s.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 l=e.CipherParams=t.extend({init:function(e){this.mixIn(e)},toString:function(e){return(e||this.formatter).stringify(this)}}),h=(o=(d.format={}).OpenSSL={stringify:function(e){var t=e.ciphertext;return((e=e.salt)?s.create([1398893684,1701076831]).concat(e).concat(t):t).toString(r)},parse:function(e){var t=(e=r.parse(e)).words;if(1398893684==t[0]&&1701076831==t[1]){var n=s.create(t.slice(2,4));t.splice(0,4),e.sigBytes-=16}return l.create({ciphertext:e,salt:n})}},e.SerializableCipher=t.extend({cfg:t.extend({format:o}),encrypt:function(e,t,s,n){n=this.cfg.extend(n);var r=e.createEncryptor(s,n);return t=r.finalize(t),r=r.cfg,l.create({ciphertext:t,key:s,iv:r.iv,algorithm:e,mode:r.mode,padding:r.padding,blockSize:e.blockSize,formatter:n.format})},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),e.createDecryptor(s,n).finalize(t.ciphertext)},_parse:function(e,t){return"string"==typeof e?t.parse(e,this):e}})),d=(d.kdf={}).OpenSSL={execute:function(e,t,n,r){return r||(r=s.random(8)),e=i.create({keySize:t+n}).compute(e,r),n=s.create(e.words.slice(t),4*n),e.sigBytes=4*t,l.create({key:e,iv:n,salt:r})}},p=e.PasswordBasedCipher=h.extend({cfg:h.cfg.extend({kdf:d}),encrypt:function(e,t,s,n){return s=(n=this.cfg.extend(n)).kdf.execute(s,e.keySize,e.ivSize),n.iv=s.iv,(e=h.encrypt.call(this,e,t,s.key,n)).mixIn(s),e},decrypt:function(e,t,s,n){return n=this.cfg.extend(n),t=this._parse(t,n.format),s=n.kdf.execute(s,e.keySize,e.ivSize,t.salt),n.iv=s.iv,h.decrypt.call(this,e,t,s.key,n)}})}(),function(){for(var e=S,t=e.lib.BlockCipher,s=e.algo,n=[],r=[],i=[],a=[],o=[],c=[],u=[],l=[],h=[],d=[],p=[],g=0;256>g;g++)p[g]=128>g?g<<1:g<<1^283;var b=0,m=0;for(g=0;256>g;g++){var y=(y=m^m<<1^m<<2^m<<3^m<<4)>>>8^255&y^99;n[b]=y,r[y]=b;var f=p[b],v=p[f],w=p[v],O=257*p[y]^16843008*y;i[b]=O<<24|O>>>8,a[b]=O<<16|O>>>16,o[b]=O<<8|O>>>24,c[b]=O,O=16843009*w^65537*v^257*f^16843008*b,u[y]=O<<24|O>>>8,l[y]=O<<16|O>>>16,h[y]=O<<8|O>>>24,d[y]=O,b?(b=f^p[p[p[w^f]]],m^=p[p[m]]):b=m=1}var k=[0,1,2,4,8,16,32,64,128,27,54];s=s.AES=t.extend({_doReset:function(){for(var e=(s=this._key).words,t=s.sigBytes/4,s=4*((this._nRounds=t+6)+1),r=this._keySchedule=[],i=0;i>>24]<<24|n[a>>>16&255]<<16|n[a>>>8&255]<<8|n[255&a]):(a=n[(a=a<<8|a>>>24)>>>24]<<24|n[a>>>16&255]<<16|n[a>>>8&255]<<8|n[255&a],a^=k[i/t|0]<<24),r[i]=r[i-t]^a}for(e=this._invKeySchedule=[],t=0;tt||4>=i?a:u[n[a>>>24]]^l[n[a>>>16&255]]^h[n[a>>>8&255]]^d[n[255&a]]},encryptBlock:function(e,t){this._doCryptBlock(e,t,this._keySchedule,i,a,o,c,n)},decryptBlock:function(e,t){var s=e[t+1];e[t+1]=e[t+3],e[t+3]=s,this._doCryptBlock(e,t,this._invKeySchedule,u,l,h,d,r),s=e[t+1],e[t+1]=e[t+3],e[t+3]=s},_doCryptBlock:function(e,t,s,n,r,i,a,o){for(var c=this._nRounds,u=e[t]^s[0],l=e[t+1]^s[1],h=e[t+2]^s[2],d=e[t+3]^s[3],p=4,g=1;g>>24]^r[l>>>16&255]^i[h>>>8&255]^a[255&d]^s[p++],m=n[l>>>24]^r[h>>>16&255]^i[d>>>8&255]^a[255&u]^s[p++],y=n[h>>>24]^r[d>>>16&255]^i[u>>>8&255]^a[255&l]^s[p++];d=n[d>>>24]^r[u>>>16&255]^i[l>>>8&255]^a[255&h]^s[p++],u=b,l=m,h=y}b=(o[u>>>24]<<24|o[l>>>16&255]<<16|o[h>>>8&255]<<8|o[255&d])^s[p++],m=(o[l>>>24]<<24|o[h>>>16&255]<<16|o[d>>>8&255]<<8|o[255&u])^s[p++],y=(o[h>>>24]<<24|o[d>>>16&255]<<16|o[u>>>8&255]<<8|o[255&l])^s[p++],d=(o[d>>>24]<<24|o[u>>>16&255]<<16|o[l>>>8&255]<<8|o[255&h])^s[p++],e[t]=b,e[t+1]=m,e[t+2]=y,e[t+3]=d},keySize:8});e.AES=t._createHelper(s)}(),S.mode.ECB=((v=S.lib.BlockCipherMode.extend()).Encryptor=v.extend({processBlock:function(e,t){this._cipher.encryptBlock(e,t)}}),v.Decryptor=v.extend({processBlock:function(e,t){this._cipher.decryptBlock(e,t)}}),v);var w=t(S);class O{constructor({cipherKey:e}){this.cipherKey=e,this.CryptoJS=w,this.encryptedKey=this.CryptoJS.SHA256(e)}encrypt(e){if(0===("string"==typeof e?e:O.decoder.decode(e)).length)throw new Error("encryption error. empty content");const t=this.getIv();return{metadata:t,data:c(this.CryptoJS.AES.encrypt(e,this.encryptedKey,{iv:this.bufferToWordArray(t),mode:this.CryptoJS.mode.CBC}).ciphertext.toString(this.CryptoJS.enc.Base64))}}encryptFileData(e){return i(this,void 0,void 0,(function*(){const t=yield this.getKey(),s=this.getIv();return{data:yield crypto.subtle.encrypt({name:this.algo,iv:s},t,e),metadata:s}}))}decrypt(e){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=this.bufferToWordArray(new Uint8ClampedArray(e.metadata)),s=this.bufferToWordArray(new Uint8ClampedArray(e.data));return O.encoder.encode(this.CryptoJS.AES.decrypt({ciphertext:s},this.encryptedKey,{iv:t,mode:this.CryptoJS.mode.CBC}).toString(this.CryptoJS.enc.Utf8)).buffer}decryptFileData(e){return i(this,void 0,void 0,(function*(){if("string"==typeof e.data)throw new Error("Decryption error: data for decryption should be ArrayBuffed.");const t=yield this.getKey();return crypto.subtle.decrypt({name:this.algo,iv:e.metadata},t,e.data)}))}get identifier(){return"ACRH"}get algo(){return"AES-CBC"}getIv(){return crypto.getRandomValues(new Uint8Array(O.BLOCK_SIZE))}getKey(){return i(this,void 0,void 0,(function*(){const e=O.encoder.encode(this.cipherKey),t=yield crypto.subtle.digest("SHA-256",e.buffer);return crypto.subtle.importKey("raw",t,this.algo,!0,["encrypt","decrypt"])}))}bufferToWordArray(e){const t=[];let s;for(s=0;s({messageType:"object",message:this.configuration,details:"Create with configuration:",ignoredKeys:(e,t)=>"function"==typeof t[e]||"logger"===e})))}get logger(){return this._logger}HMACSHA256(e){return w.HmacSHA256(e,this.configuration.secretKey).toString(w.enc.Base64)}SHA256(e){return w.SHA256(e).toString(w.enc.Hex)}encrypt(e,t,s){return this.configuration.customEncrypt?(this.logger&&this.logger.warn(this.constructor.name,"'customEncrypt' is deprecated. Consult docs for better alternative."),this.configuration.customEncrypt(e)):this.pnEncrypt(e,t,s)}decrypt(e,t,s){return this.configuration.customDecrypt?(this.logger&&this.logger.warn(this.constructor.name,"'customDecrypt' is deprecated. Consult docs for better alternative."),this.configuration.customDecrypt(e)):this.pnDecrypt(e,t,s)}pnEncrypt(e,t,s){const n=null!=t?t:this.configuration.cipherKey;if(!n)return e;this.logger&&this.logger.debug(this.constructor.name,(()=>({messageType:"object",message:Object.assign({data:e,cipherKey:n},null!=s?s:{}),details:"Encrypt with parameters:"}))),s=this.parseOptions(s);const r=this.getMode(s),i=this.getPaddedKey(n,s);if(this.configuration.useRandomIVs){const t=this.getRandomIV(),s=w.AES.encrypt(e,i,{iv:t,mode:r}).ciphertext;return t.clone().concat(s.clone()).toString(w.enc.Base64)}const a=this.getIV(s);return w.AES.encrypt(e,i,{iv:a,mode:r}).ciphertext.toString(w.enc.Base64)||e}pnDecrypt(e,t,s){const n=null!=t?t:this.configuration.cipherKey;if(!n)return e;this.logger&&this.logger.debug(this.constructor.name,(()=>({messageType:"object",message:Object.assign({data:e,cipherKey:n},null!=s?s:{}),details:"Decrypt with parameters:"}))),s=this.parseOptions(s);const r=this.getMode(s),i=this.getPaddedKey(n,s);if(this.configuration.useRandomIVs){const t=new Uint8ClampedArray(c(e)),s=k(t.slice(0,16)),n=k(t.slice(16));try{const e=w.AES.decrypt({ciphertext:n},i,{iv:s,mode:r}).toString(w.enc.Utf8);return JSON.parse(e)}catch(e){return this.logger&&this.logger.error(this.constructor.name,(()=>({messageType:"error",message:e}))),null}}else{const t=this.getIV(s);try{const s=w.enc.Base64.parse(e),n=w.AES.decrypt({ciphertext:s},i,{iv:t,mode:r}).toString(w.enc.Utf8);return JSON.parse(n)}catch(e){return this.logger&&this.logger.error(this.constructor.name,(()=>({messageType:"error",message:e}))),null}}}parseOptions(e){var t,s,n,r;if(!e)return this.defaultOptions;const i={encryptKey:null!==(t=e.encryptKey)&&void 0!==t?t:this.defaultOptions.encryptKey,keyEncoding:null!==(s=e.keyEncoding)&&void 0!==s?s:this.defaultOptions.keyEncoding,keyLength:null!==(n=e.keyLength)&&void 0!==n?n:this.defaultOptions.keyLength,mode:null!==(r=e.mode)&&void 0!==r?r:this.defaultOptions.mode};return-1===this.allowedKeyEncodings.indexOf(i.keyEncoding.toLowerCase())&&(i.keyEncoding=this.defaultOptions.keyEncoding),-1===this.allowedKeyLengths.indexOf(i.keyLength)&&(i.keyLength=this.defaultOptions.keyLength),-1===this.allowedModes.indexOf(i.mode.toLowerCase())&&(i.mode=this.defaultOptions.mode),i}decodeKey(e,t){return"base64"===t.keyEncoding?w.enc.Base64.parse(e):"hex"===t.keyEncoding?w.enc.Hex.parse(e):e}getPaddedKey(e,t){return e=this.decodeKey(e,t),t.encryptKey?w.enc.Utf8.parse(this.SHA256(e).slice(0,32)):e}getMode(e){return"ecb"===e.mode?w.mode.ECB:w.mode.CBC}getIV(e){return"cbc"===e.mode?w.enc.Utf8.parse(this.iv):null}getRandomIV(){return w.lib.WordArray.random(16)}}class P{encrypt(e,t){return i(this,void 0,void 0,(function*(){if(!(t instanceof ArrayBuffer)&&"string"!=typeof t)throw new Error("Cannot encrypt this file. In browsers file encryption supports only string or ArrayBuffer");const s=yield this.getKey(e);return t instanceof ArrayBuffer?this.encryptArrayBuffer(s,t):this.encryptString(s,t)}))}encryptArrayBuffer(e,t){return i(this,void 0,void 0,(function*(){const s=crypto.getRandomValues(new Uint8Array(16));return this.concatArrayBuffer(s.buffer,yield crypto.subtle.encrypt({name:"AES-CBC",iv:s},e,t))}))}encryptString(e,t){return i(this,void 0,void 0,(function*(){const s=crypto.getRandomValues(new Uint8Array(16)),n=P.encoder.encode(t).buffer,r=yield crypto.subtle.encrypt({name:"AES-CBC",iv:s},e,n),i=this.concatArrayBuffer(s.buffer,r);return P.decoder.decode(i)}))}encryptFile(e,t,s){return i(this,void 0,void 0,(function*(){var n,r;if((null!==(n=t.contentLength)&&void 0!==n?n:0)<=0)throw new Error("encryption error. empty content");const i=yield this.getKey(e),a=yield t.toArrayBuffer(),o=yield this.encryptArrayBuffer(i,a);return s.create({name:t.name,mimeType:null!==(r=t.mimeType)&&void 0!==r?r:"application/octet-stream",data:o})}))}decrypt(e,t){return i(this,void 0,void 0,(function*(){if(!(t instanceof ArrayBuffer)&&"string"!=typeof t)throw new Error("Cannot decrypt this file. In browsers file decryption supports only string or ArrayBuffer");const s=yield this.getKey(e);return t instanceof ArrayBuffer?this.decryptArrayBuffer(s,t):this.decryptString(s,t)}))}decryptArrayBuffer(e,t){return i(this,void 0,void 0,(function*(){const s=t.slice(0,16);if(t.slice(P.IV_LENGTH).byteLength<=0)throw new Error("decryption error: empty content");return yield crypto.subtle.decrypt({name:"AES-CBC",iv:s},e,t.slice(P.IV_LENGTH))}))}decryptString(e,t){return i(this,void 0,void 0,(function*(){const s=P.encoder.encode(t).buffer,n=s.slice(0,16),r=s.slice(16),i=yield crypto.subtle.decrypt({name:"AES-CBC",iv:n},e,r);return P.decoder.decode(i)}))}decryptFile(e,t,s){return i(this,void 0,void 0,(function*(){const n=yield this.getKey(e),r=yield t.toArrayBuffer(),i=yield this.decryptArrayBuffer(n,r);return s.create({name:t.name,mimeType:t.mimeType,data:i})}))}getKey(e){return i(this,void 0,void 0,(function*(){const t=yield crypto.subtle.digest("SHA-256",P.encoder.encode(e)),s=Array.from(new Uint8Array(t)).map((e=>e.toString(16).padStart(2,"0"))).join(""),n=P.encoder.encode(s.slice(0,32)).buffer;return crypto.subtle.importKey("raw",n,"AES-CBC",!0,["encrypt","decrypt"])}))}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}}P.IV_LENGTH=16,P.encoder=new TextEncoder,P.decoder=new TextDecoder;class j{constructor(e){this.config=e,this.cryptor=new C(Object.assign({},e)),this.fileCryptor=new P}set logger(e){this.cryptor.logger=e}encrypt(e){const t="string"==typeof e?e:j.decoder.decode(e);return{data:this.cryptor.encrypt(t),metadata:null}}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.encryptFile(null===(s=this.config)||void 0===s?void 0:s.cipherKey,e,t)}))}decrypt(e){const t="string"==typeof e.data?e.data:u(e.data);return this.cryptor.decrypt(t)}decryptFile(e,t){return i(this,void 0,void 0,(function*(){if(!this.config.cipherKey)throw new d("File encryption error: cipher key not set.");return this.fileCryptor.decryptFile(this.config.cipherKey,e,t)}))}get identifier(){return""}toString(){const e=Object.entries(this.config).reduce(((e,[t,s])=>("logger"===t||e.push(`${t}: ${"function"==typeof s?"":s}`),e)),[]);return`${this.constructor.name} { ${e.join(", ")} }`}}j.encoder=new TextEncoder,j.decoder=new TextDecoder;class E extends a{set logger(e){if(this.defaultCryptor.identifier===E.LEGACY_IDENTIFIER)this.defaultCryptor.logger=e;else{const t=this.cryptors.find((e=>e.identifier===E.LEGACY_IDENTIFIER));t&&(t.logger=e)}}static legacyCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new E({default:new j(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t})),cryptors:[new O({cipherKey:e.cipherKey})]})}static aesCbcCryptoModule(e){var t;if(!e.cipherKey)throw new d("Crypto module error: cipher key not set.");return new E({default:new O({cipherKey:e.cipherKey}),cryptors:[new j(Object.assign(Object.assign({},e),{useRandomIVs:null===(t=e.useRandomIVs)||void 0===t||t}))]})}static withDefaultCryptor(e){return new this({default:e})}encrypt(e){const t=e instanceof ArrayBuffer&&this.defaultCryptor.identifier===E.LEGACY_IDENTIFIER?this.defaultCryptor.encrypt(E.decoder.decode(e)):this.defaultCryptor.encrypt(e);if(!t.metadata)return t.data;if("string"==typeof t.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");const s=this.getHeaderData(t);return this.concatArrayBuffer(s,t.data)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){if(this.defaultCryptor.identifier===N.LEGACY_IDENTIFIER)return this.defaultCryptor.encryptFile(e,t);const s=yield this.getFileData(e),n=yield this.defaultCryptor.encryptFileData(s);if("string"==typeof n.data)throw new Error("Encryption error: encrypted data should be ArrayBuffed.");return t.create({name:e.name,mimeType:"application/octet-stream",data:this.concatArrayBuffer(this.getHeaderData(n),n.data)})}))}decrypt(e){const t="string"==typeof e?c(e):e,s=N.tryParse(t),n=this.getCryptor(s),r=s.length>0?t.slice(s.length-s.metadataLength,s.length):null;if(t.slice(s.length).byteLength<=0)throw new Error("Decryption error: empty content");return n.decrypt({data:t.slice(s.length),metadata:r})}decryptFile(e,t){return i(this,void 0,void 0,(function*(){const s=yield e.data.arrayBuffer(),n=N.tryParse(s),r=this.getCryptor(n);if((null==r?void 0:r.identifier)===N.LEGACY_IDENTIFIER)return r.decryptFile(e,t);const i=(yield this.getFileData(s)).slice(n.length-n.metadataLength,n.length);return t.create({name:e.name,data:yield this.defaultCryptor.decryptFileData({data:s.slice(n.length),metadata:i})})}))}getCryptorFromId(e){const t=this.getAllCryptors().find((t=>e===t.identifier));if(t)return t;throw Error("Unknown cryptor error")}getCryptor(e){if("string"==typeof e){const t=this.getAllCryptors().find((t=>t.identifier===e));if(t)return t;throw new Error("Unknown cryptor error")}if(e instanceof T)return this.getCryptorFromId(e.identifier)}getHeaderData(e){if(!e.metadata)return;const t=N.from(this.defaultCryptor.identifier,e.metadata),s=new Uint8Array(t.length);let n=0;return s.set(t.data,n),n+=t.length-e.metadata.byteLength,s.set(new Uint8Array(e.metadata),n),s.buffer}concatArrayBuffer(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(new Uint8Array(e),0),s.set(new Uint8Array(t),e.byteLength),s.buffer}getFileData(e){return i(this,void 0,void 0,(function*(){if(e instanceof ArrayBuffer)return e;if(e instanceof o)return e.toArrayBuffer();throw new Error("Cannot decrypt/encrypt file. In browsers file encrypt/decrypt supported for string, ArrayBuffer or Blob")}))}}E.LEGACY_IDENTIFIER="";class N{static from(e,t){if(e!==N.LEGACY_IDENTIFIER)return new T(e,t.byteLength)}static tryParse(e){const t=new Uint8Array(e);let s,n,r=null;if(t.byteLength>=4&&(s=t.slice(0,4),this.decoder.decode(s)!==N.SENTINEL))return E.LEGACY_IDENTIFIER;if(!(t.byteLength>=5))throw new Error("Decryption error: invalid header version");if(r=t[4],r>N.MAX_VERSION)throw new Error("Decryption error: Unknown cryptor error");let i=5+N.IDENTIFIER_LENGTH;if(!(t.byteLength>=i))throw new Error("Decryption error: invalid crypto identifier");n=t.slice(5,i);let a=null;if(!(t.byteLength>=i+1))throw new Error("Decryption error: invalid metadata length");return a=t[i],i+=1,255===a&&t.byteLength>=i+2&&(a=new Uint16Array(t.slice(i,i+2)).reduce(((e,t)=>(e<<8)+t),0)),new T(this.decoder.decode(n),a)}}N.SENTINEL="PNED",N.LEGACY_IDENTIFIER="",N.IDENTIFIER_LENGTH=4,N.VERSION=1,N.MAX_VERSION=1,N.decoder=new TextDecoder;class T{constructor(e,t){this._identifier=e,this._metadataLength=t}get identifier(){return this._identifier}set identifier(e){this._identifier=e}get metadataLength(){return this._metadataLength}set metadataLength(e){this._metadataLength=e}get version(){return N.VERSION}get length(){return N.SENTINEL.length+1+N.IDENTIFIER_LENGTH+(this.metadataLength<255?1:3)+this.metadataLength}get data(){let e=0;const t=new Uint8Array(this.length),s=new TextEncoder;t.set(s.encode(N.SENTINEL)),e+=N.SENTINEL.length,t[e]=this.version,e++,this.identifier&&t.set(s.encode(this.identifier),e);const n=this.metadataLength;return e+=N.IDENTIFIER_LENGTH,n<255?t[e]=n:t.set([255,n>>8,255&n],e),t}}T.IDENTIFIER_LENGTH=4,T.SENTINEL="PNED";class _ extends Error{static create(e,t){return _.isErrorObject(e)?_.createFromError(e):_.createFromServiceResponse(e,t)}static createFromError(e){let t=h.PNUnknownCategory,s="Unknown error",n="Error";if(!e)return new _(s,t,0);if(e instanceof _)return e;if(_.isErrorObject(e)&&(s=e.message,n=e.name),"AbortError"===n||-1!==s.indexOf("Aborted"))t=h.PNCancelledCategory,s="Request cancelled";else if(-1!==s.toLowerCase().indexOf("timeout"))t=h.PNTimeoutCategory,s="Request timeout";else if(-1!==s.toLowerCase().indexOf("network"))t=h.PNNetworkIssuesCategory,s="Network issues";else if("TypeError"===n)t=-1!==s.indexOf("Load failed")||-1!=s.indexOf("Failed to fetch")?h.PNNetworkIssuesCategory:h.PNBadRequestCategory;else if("FetchError"===n){const n=e.code;["ECONNREFUSED","ENETUNREACH","ENOTFOUND","ECONNRESET","EAI_AGAIN"].includes(n)&&(t=h.PNNetworkIssuesCategory),"ECONNREFUSED"===n?s="Connection refused":"ENETUNREACH"===n?s="Network not reachable":"ENOTFOUND"===n?s="Server not found":"ECONNRESET"===n?s="Connection reset by peer":"EAI_AGAIN"===n?s="Name resolution error":"ETIMEDOUT"===n?(t=h.PNTimeoutCategory,s="Request timeout"):s=`Unknown system error: ${e}`}else"Request timeout"===s&&(t=h.PNTimeoutCategory);return new _(s,t,0,e)}static createFromServiceResponse(e,t){let s,n=h.PNUnknownCategory,r="Unknown error",{status:i}=e;if(null!=t||(t=e.body),402===i?r="Not available for used key set. Contact support@pubnub.com":400===i?(n=h.PNBadRequestCategory,r="Bad request"):403===i&&(n=h.PNAccessDeniedCategory,r="Access denied"),"object"==typeof e&&0===Object.keys(e).length&&(n=h.PNMalformedResponseCategory,r="Malformed response (network issues)",i=400),t&&t.byteLength>0){const n=(new TextDecoder).decode(t);if(-1!==e.headers["content-type"].indexOf("text/javascript")||-1!==e.headers["content-type"].indexOf("application/json"))try{const e=JSON.parse(n);"object"==typeof e&&(Array.isArray(e)?"number"==typeof e[0]&&0===e[0]&&e.length>1&&"string"==typeof e[1]&&(s=e[1]):("error"in e&&(1===e.error||!0===e.error)&&"status"in e&&"number"==typeof e.status&&"message"in e&&"service"in e?(s=e,i=e.status):s=e,"error"in e&&e.error instanceof Error&&(s=e.error)))}catch(e){s=n}else if(-1!==e.headers["content-type"].indexOf("xml")){const e=/(.*)<\/Message>/gi.exec(n);r=e?`Upload to bucket failed: ${e[1]}`:"Upload to bucket failed."}else s=n}return new _(r,n,i,s)}constructor(e,t,s,n){super(e),this.category=t,this.statusCode=s,this.errorData=n,this.name="PubNubAPIError"}toStatus(e){return{error:!0,category:this.category,operation:e,statusCode:this.statusCode,errorData:this.errorData,toJSON:function(){let e;const t=this.errorData;if(t)try{if("object"==typeof t){const s=Object.assign(Object.assign(Object.assign(Object.assign({},"name"in t?{name:t.name}:{}),"message"in t?{message:t.message}:{}),"stack"in t?{stack:t.stack}:{}),t);e=JSON.parse(JSON.stringify(s,_.circularReplacer()))}else e=t}catch(t){e={error:"Could not serialize the error object"}}const s=r(this,["toJSON"]);return JSON.stringify(Object.assign(Object.assign({},s),{errorData:e}))}}}toPubNubError(e,t){return new d(null!=t?t:this.message,this.toStatus(e))}static circularReplacer(){const e=new WeakSet;return function(t,s){if("object"==typeof s&&null!==s){if(e.has(s))return"[Circular]";e.add(s)}return s}}static isErrorObject(e){return!(!e||"object"!=typeof e)&&(e instanceof Error||("name"in e&&"message"in e&&"string"==typeof e.name&&"string"==typeof e.message||"[object Error]"===Object.prototype.toString.call(e)))}}class I{constructor(e){this.configuration=e,this.subscriptionWorkerReady=!1,this.accessTokensMap={},this.workerEventsQueue=[],this.callbacks=new Map,this.setupSubscriptionWorker()}terminate(){this.scheduleEventPost({type:"client-unregister",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey})}makeSendable(e){if(!e.path.startsWith("/v2/subscribe")&&!e.path.endsWith("/heartbeat")&&!e.path.endsWith("/leave"))return this.configuration.transport.makeSendable(e);let t;this.configuration.logger.debug(this.constructor.name,"Process request with SharedWorker transport.");const s={type:"send-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,request:e};return e.cancellable&&(t={abort:()=>{const t={type:"cancel-request",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,identifier:e.identifier};this.scheduleEventPost(t)}}),[new Promise(((t,n)=>{this.callbacks.set(e.identifier,{resolve:t,reject:n}),this.parsedAccessTokenForRequest(e).then((e=>s.token=e)).then((()=>this.scheduleEventPost(s)))})),t]}request(e){return e}scheduleEventPost(e,t=!1){const s=this.sharedSubscriptionWorker;s?s.port.postMessage(e):t?this.workerEventsQueue.splice(0,0,e):this.workerEventsQueue.push(e)}flushScheduledEvents(){const e=this.sharedSubscriptionWorker;if(!e||0===this.workerEventsQueue.length)return;const t=[];for(let e=0;e!t.includes(e))),this.workerEventsQueue.forEach((t=>e.port.postMessage(t))),this.workerEventsQueue=[]}get sharedSubscriptionWorker(){return this.subscriptionWorkerReady?this.subscriptionWorker:null}setupSubscriptionWorker(){if("undefined"!=typeof SharedWorker){try{this.subscriptionWorker=new SharedWorker(this.configuration.workerUrl,`/pubnub-${this.configuration.sdkVersion}`)}catch(e){throw this.configuration.logger.error(this.constructor.name,(()=>({messageType:"error",message:e}))),e}this.subscriptionWorker.port.start(),this.scheduleEventPost({type:"client-register",clientIdentifier:this.configuration.clientIdentifier,subscriptionKey:this.configuration.subscriptionKey,userId:this.configuration.userId,heartbeatInterval:this.configuration.heartbeatInterval,workerOfflineClientsCheckInterval:this.configuration.workerOfflineClientsCheckInterval,workerUnsubscribeOfflineClients:this.configuration.workerUnsubscribeOfflineClients,workerLogVerbosity:this.configuration.workerLogVerbosity},!0),this.subscriptionWorker.port.onmessage=e=>this.handleWorkerEvent(e)}}handleWorkerEvent(e){const{data:t}=e;if("shared-worker-ping"===t.type||"shared-worker-connected"===t.type||"shared-worker-console-log"===t.type||"shared-worker-console-dir"===t.type||t.clientIdentifier===this.configuration.clientIdentifier)if("shared-worker-connected"===t.type)this.configuration.logger.trace("SharedWorker","Ready for events processing."),this.subscriptionWorkerReady=!0,this.flushScheduledEvents();else if("shared-worker-console-log"===t.type)this.configuration.logger.debug("SharedWorker",t.message);else if("shared-worker-console-dir"===t.type)this.configuration.logger.debug("SharedWorker",(()=>({messageType:"object",message:t.data,details:t.message?t.message:void 0})));else if("shared-worker-ping"===t.type){const{subscriptionKey:e,clientIdentifier:t}=this.configuration;this.scheduleEventPost({type:"client-pong",subscriptionKey:e,clientIdentifier:t})}else if("request-process-success"===t.type||"request-process-error"===t.type){const{resolve:e,reject:s}=this.callbacks.get(t.identifier);if("request-process-success"===t.type)e({status:t.response.status,url:t.url,headers:t.response.headers,body:t.response.body});else{let e=h.PNUnknownCategory,n="Unknown error";if(t.error)"NETWORK_ISSUE"===t.error.type?e=h.PNNetworkIssuesCategory:"TIMEOUT"===t.error.type?e=h.PNTimeoutCategory:"ABORTED"===t.error.type&&(e=h.PNCancelledCategory),n=`${t.error.message} (${t.identifier})`;else if(t.response)return s(_.create({url:t.url,headers:t.response.headers,body:t.response.body,status:t.response.status},t.response.body));s(new _(n,e,0,new Error(n)))}}}parsedAccessTokenForRequest(e){return i(this,void 0,void 0,(function*(){var t;const s=e.queryParameters?null!==(t=e.queryParameters.auth)&&void 0!==t?t:"":void 0;if(s)return this.accessTokensMap[s]?this.accessTokensMap[s]:this.stringifyAccessToken(s).then((([e,t])=>{if(e&&t)return(this.accessTokensMap={[s]:{token:t,expiration:e.timestamp*e.ttl*60}})[s]}))}))}stringifyAccessToken(e){return i(this,void 0,void 0,(function*(){if(!this.configuration.tokenManager)return[void 0,void 0];const t=this.configuration.tokenManager.parseToken(e);if(!t)return[void 0,void 0];const s=e=>e?Object.entries(e).sort((([e],[t])=>e.localeCompare(t))).map((([e,t])=>Object.entries(t||{}).sort((([e],[t])=>e.localeCompare(t))).map((([t,s])=>{return`${e}:${t}=${s?(n=s,Object.entries(n).filter((([e,t])=>t)).map((([e])=>e[0])).sort().join("")):""}`;var n})).join(","))).join(";"):"";let n=[s(t.resources),s(t.patterns),t.authorized_uuid].filter(Boolean).join("|");if("undefined"!=typeof crypto&&crypto.subtle){const e=yield crypto.subtle.digest("SHA-256",(new TextEncoder).encode(n));n=String.fromCharCode(...Array.from(new Uint8Array(e)))}return[t,"undefined"!=typeof btoa?btoa(n):n]}))}}function M(e){const t=e=>"object"==typeof e&&null!==e&&e.constructor===Object,s=e=>"number"==typeof e&&isFinite(e);if(!t(e))return e;const n={};return Object.keys(e).forEach((r=>{const i=(e=>"string"==typeof e||e instanceof String)(r);let a=r;const o=e[r];if(i&&r.indexOf(",")>=0){a=r.split(",").map(Number).reduce(((e,t)=>e+String.fromCharCode(t)),"")}else(s(r)||i&&!isNaN(Number(r)))&&(a=String.fromCharCode(s(r)?r:parseInt(r,10)));n[a]=t(o)?M(o):o})),n}const A=e=>{var t,s,n,r,i,a;return e.subscriptionWorkerUrl&&"undefined"==typeof SharedWorker&&(e.subscriptionWorkerUrl=null),Object.assign(Object.assign({},(e=>{var t,s,n,r,i,a,o,c,u,l,h,p,g,b,m,y;const f=Object.assign({},e);if(null!==(t=f.logVerbosity)&&void 0!==t||(f.logVerbosity=!1),null!==(s=f.ssl)&&void 0!==s||(f.ssl=!0),null!==(n=f.transactionalRequestTimeout)&&void 0!==n||(f.transactionalRequestTimeout=15),null!==(r=f.subscribeRequestTimeout)&&void 0!==r||(f.subscribeRequestTimeout=310),null!==(i=f.fileRequestTimeout)&&void 0!==i||(f.fileRequestTimeout=300),null!==(a=f.restore)&&void 0!==a||(f.restore=!1),null!==(o=f.useInstanceId)&&void 0!==o||(f.useInstanceId=!1),null!==(c=f.suppressLeaveEvents)&&void 0!==c||(f.suppressLeaveEvents=!1),null!==(u=f.requestMessageCountThreshold)&&void 0!==u||(f.requestMessageCountThreshold=100),null!==(l=f.autoNetworkDetection)&&void 0!==l||(f.autoNetworkDetection=!1),null!==(h=f.enableEventEngine)&&void 0!==h||(f.enableEventEngine=!1),null!==(p=f.maintainPresenceState)&&void 0!==p||(f.maintainPresenceState=!0),null!==(g=f.useSmartHeartbeat)&&void 0!==g||(f.useSmartHeartbeat=!1),null!==(b=f.keepAlive)&&void 0!==b||(f.keepAlive=!1),f.userId&&f.uuid)throw new d("PubNub client configuration error: use only 'userId'");if(null!==(m=f.userId)&&void 0!==m||(f.userId=f.uuid),!f.userId)throw new d("PubNub client configuration error: 'userId' not set");if(0===(null===(y=f.userId)||void 0===y?void 0:y.trim().length))throw new d("PubNub client configuration error: 'userId' is empty");f.origin||(f.origin=Array.from({length:20},((e,t)=>`ps${t+1}.pndsn.com`)));const v={subscribeKey:f.subscribeKey,publishKey:f.publishKey,secretKey:f.secretKey};void 0!==f.presenceTimeout&&(f.presenceTimeout>320?(f.presenceTimeout=320,console.warn("WARNING: Presence timeout is larger than the maximum. Using maximum value: ",320)):f.presenceTimeout<=0&&(console.warn("WARNING: Presence timeout should be larger than zero."),delete f.presenceTimeout)),void 0!==f.presenceTimeout?f.heartbeatInterval=f.presenceTimeout/2-1:f.presenceTimeout=300;let S=!1,w=!0,O=5,k=!1,C=100,P=!0;return void 0!==f.dedupeOnSubscribe&&"boolean"==typeof f.dedupeOnSubscribe&&(k=f.dedupeOnSubscribe),void 0!==f.maximumCacheSize&&"number"==typeof f.maximumCacheSize&&(C=f.maximumCacheSize),void 0!==f.useRequestId&&"boolean"==typeof f.useRequestId&&(P=f.useRequestId),void 0!==f.announceSuccessfulHeartbeats&&"boolean"==typeof f.announceSuccessfulHeartbeats&&(S=f.announceSuccessfulHeartbeats),void 0!==f.announceFailedHeartbeats&&"boolean"==typeof f.announceFailedHeartbeats&&(w=f.announceFailedHeartbeats),void 0!==f.fileUploadPublishRetryLimit&&"number"==typeof f.fileUploadPublishRetryLimit&&(O=f.fileUploadPublishRetryLimit),Object.assign(Object.assign({},f),{keySet:v,dedupeOnSubscribe:k,maximumCacheSize:C,useRequestId:P,announceSuccessfulHeartbeats:S,announceFailedHeartbeats:w,fileUploadPublishRetryLimit:O})})(e)),{listenToBrowserNetworkEvents:null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t,subscriptionWorkerUrl:e.subscriptionWorkerUrl,subscriptionWorkerOfflineClientsCheckInterval:null!==(s=e.subscriptionWorkerOfflineClientsCheckInterval)&&void 0!==s?s:10,subscriptionWorkerUnsubscribeOfflineClients:null!==(n=e.subscriptionWorkerUnsubscribeOfflineClients)&&void 0!==n&&n,subscriptionWorkerLogVerbosity:null!==(r=e.subscriptionWorkerLogVerbosity)&&void 0!==r&&r,transport:null!==(i=e.transport)&&void 0!==i?i:"fetch",keepAlive:null===(a=e.keepAlive)||void 0===a||a})};var U;!function(e){e.Unknown="UnknownEndpoint",e.MessageSend="MessageSendEndpoint",e.Subscribe="SubscribeEndpoint",e.Presence="PresenceEndpoint",e.Files="FilesEndpoint",e.MessageStorage="MessageStorageEndpoint",e.ChannelGroups="ChannelGroupsEndpoint",e.DevicePushNotifications="DevicePushNotificationsEndpoint",e.AppContext="AppContextEndpoint",e.MessageReactions="MessageReactionsEndpoint"}(U||(U={}));class ${static None(){return{shouldRetry:(e,t,s,n)=>!1,getDelay:(e,t)=>-1,validate:()=>!0}}static LinearRetryPolicy(e){var t;return{delay:e.delay,maximumRetry:e.maximumRetry,excluded:null!==(t=e.excluded)&&void 0!==t?t:[],shouldRetry(e,t,s,n){return R(e,t,s,null!=n?n:0,this.maximumRetry,this.excluded)},getDelay(e,t){let s=-1;return t&&void 0!==t.headers["retry-after"]&&(s=parseInt(t.headers["retry-after"],10)),-1===s&&(s=this.delay),1e3*(s+Math.random())},validate(){if(this.delay<2)throw new Error("Delay can not be set less than 2 seconds for retry");if(this.maximumRetry>10)throw new Error("Maximum retry for linear retry policy can not be more than 10")}}}static ExponentialRetryPolicy(e){var t;return{minimumDelay:e.minimumDelay,maximumDelay:e.maximumDelay,maximumRetry:e.maximumRetry,excluded:null!==(t=e.excluded)&&void 0!==t?t:[],shouldRetry(e,t,s,n){return R(e,t,s,null!=n?n:0,this.maximumRetry,this.excluded)},getDelay(e,t){let s=-1;return t&&void 0!==t.headers["retry-after"]&&(s=parseInt(t.headers["retry-after"],10)),-1===s&&(s=Math.min(Math.pow(2,e),this.maximumDelay)),1e3*(s+Math.random())},validate(){if(this.minimumDelay<2)throw new Error("Minimum delay can not be set less than 2 seconds for retry");if(this.maximumDelay>150)throw new Error("Maximum delay can not be set more than 150 seconds for retry");if(this.maximumRetry>6)throw new Error("Maximum retry for exponential retry policy can not be more than 6")}}}}const R=(e,t,s,n,r,i)=>(!s||s!==h.PNCancelledCategory&&s!==h.PNBadRequestCategory&&s!==h.PNAccessDeniedCategory)&&(!F(e,i)&&(!(n>r)&&(!t||(429===t.status||t.status>=500)))),F=(e,t)=>!!(t&&t.length>0)&&t.includes(D(e)),D=e=>{let t=U.Unknown;return e.path.startsWith("/v2/subscribe")?t=U.Subscribe:e.path.startsWith("/publish/")||e.path.startsWith("/signal/")?t=U.MessageSend:e.path.startsWith("/v2/presence")?t=U.Presence:e.path.startsWith("/v2/history")||e.path.startsWith("/v3/history")?t=U.MessageStorage:e.path.startsWith("/v1/message-actions/")?t=U.MessageReactions:e.path.startsWith("/v1/channel-registration/")||e.path.startsWith("/v2/objects/")?t=U.ChannelGroups:e.path.startsWith("/v1/push/")||e.path.startsWith("/v2/push/")?t=U.DevicePushNotifications:e.path.startsWith("/v1/files/")&&(t=U.Files),t};var x={exports:{}}; -/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!function(e,t){!function(e){var t="0.1.0",s={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 n(){var e,t,s="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(s+="-"),s+=(12===e?4:16===e?3&t|8:t).toString(16);return s}function r(e,t){var n=s[t||"all"];return n&&n.test(e)||!1}n.isUUID=r,n.VERSION=t,e.uuid=n,e.isUUID=r}(t),null!==e&&(e.exports=t.uuid)}(x,x.exports);var G,q=t(x.exports),K={createUUID:()=>q.uuid?q.uuid():q()};!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warn=3]="Warn",e[e.Error=4]="Error",e[e.None=5]="None"}(G||(G={}));class L{constructor(e,t,s){this.pubNubId=e,this.minLogLevel=t,this.loggers=s}get logLevel(){return this.minLogLevel}trace(e,t){this.log(G.Trace,e,t)}debug(e,t){this.log(G.Debug,e,t)}info(e,t){this.log(G.Info,e,t)}warn(e,t){this.log(G.Warn,e,t)}error(e,t){this.log(G.Error,e,t)}log(e,t,s){if(ee[n](r)))}}const H=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),B=(e,t)=>{const s=e.map((e=>H(e)));return s.length?s.join(","):null!=t?t:""},W=(e,t)=>{const s=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!s[e])||(s[e]=!0,!1)))},z=(e,t)=>[...e].filter((s=>t.includes(s)&&e.indexOf(s)===e.lastIndexOf(s)&&t.indexOf(s)===t.lastIndexOf(s))),V=e=>Object.keys(e).map((t=>{const s=e[t];return Array.isArray(s)?s.map((e=>`${t}=${H(e)}`)).join("&"):`${t}=${H(s)}`})).join("&"),J=(e,t)=>{if("0"===t||"0"===e)return;const s=Q(`${Date.now()}0000`,t,!1);return Q(e,s,!0)},X=(e,t,s)=>{if(e&&0!==e.length){if(t&&t.length>0&&"0"!==t){const n=Q(e,t,!1);return Q(null!=s?s:`${Date.now()}0000`,n.replace("-",""),Number(n)<0)}return s&&s.length>0&&"0"!==s?s:`${Date.now()}0000`}},Q=(e,t,s)=>{t=t.padStart(17,"0");const n=e.slice(0,10),r=e.slice(10,17),i=t.slice(0,10),a=t.slice(10,17);let o=Number(n),c=Number(r);return o+=Number(i)*(s?1:-1),c+=Number(a)*(s?1:-1),c>=1e7?(o+=Math.floor(c/1e7),c%=1e7):c<0&&(o>0?(o-=1,c+=1e7):o<0&&(c*=-1)),0!==o?`${o}${`${c}`.padStart(7,"0")}`:`${c}`},Y=e=>{const t="string"!=typeof e?JSON.stringify(e):e,s=new Uint32Array(1);let n=0,r=t.length;for(;r-- >0;)s[0]=(s[0]<<5)-s[0]+t.charCodeAt(n++);return s[0].toString(16).padStart(8,"0")};class Z{debug(e){this.log(e)}error(e){this.log(e)}info(e){this.log(e)}trace(e){this.log(e)}warn(e){this.log(e)}log(e){const t=G[e.level],s=t.toLowerCase();console["trace"===s?"debug":s](`${e.timestamp.toISOString()} PubNub-${e.pubNubId} ${t.padEnd(5," ")}${e.location?` ${e.location}`:""} ${this.logMessage(e)}`)}logMessage(e){if("text"===e.messageType)return e.message;if("object"===e.messageType)return`${e.details?`${e.details}\n`:""}${this.formattedObject(e)}`;if("network-request"===e.messageType){const t=!!e.canceled||!!e.failed,s=e.minimumLevel!==G.Trace||t?void 0:this.formattedHeaders(e),n=e.message,r=n.queryParameters&&Object.keys(n.queryParameters).length>0?V(n.queryParameters):void 0,i=`${n.origin}${n.path}${r?`?${r}`:""}`,a=t?void 0:this.formattedBody(e);let o="Sending";t&&(o=`${e.canceled?"Canceled":"Failed"}${e.details?` (${e.details})`:""}`);const c=((null==a?void 0:a.formData)?"FormData":"Method").length;return`${o} HTTP request:\n ${this.paddedString("Method",c)}: ${n.method}\n ${this.paddedString("URL",c)}: ${i}${s?`\n ${this.paddedString("Headers",c)}:\n${s}`:""}${(null==a?void 0:a.formData)?`\n ${this.paddedString("FormData",c)}:\n${a.formData}`:""}${(null==a?void 0:a.body)?`\n ${this.paddedString("Body",c)}:\n${a.body}`:""}`}if("network-response"===e.messageType){const t=e.minimumLevel===G.Trace?this.formattedHeaders(e):void 0,s=this.formattedBody(e),n=((null==s?void 0:s.formData)?"Headers":"Status").length,r=e.message;return`Received HTTP response:\n ${this.paddedString("URL",n)}: ${r.url}\n ${this.paddedString("Status",n)}: ${r.status}${t?`\n ${this.paddedString("Headers",n)}:\n${t}`:""}${(null==s?void 0:s.body)?`\n ${this.paddedString("Body",n)}:\n${s.body}`:""}`}if("error"===e.messageType){const t=this.formattedErrorStatus(e),s=e.message;return`${s.name}: ${s.message}${t?`\n${t}`:""}`}return""}formattedObject(e){const t=(s,n=1,r=!1)=>{const i=10===n,a=" ".repeat(2*n),o=[],c=(t,s)=>!!e.ignoredKeys&&("function"==typeof e.ignoredKeys?e.ignoredKeys(t,s):e.ignoredKeys.includes(t));if("string"==typeof s)o.push(`${a}- ${s}`);else if("number"==typeof s)o.push(`${a}- ${s}`);else if("boolean"==typeof s)o.push(`${a}- ${s}`);else if(null===s)o.push(`${a}- null`);else if(void 0===s)o.push(`${a}- undefined`);else if("function"==typeof s)o.push(`${a}- `);else if("object"==typeof s)if(Array.isArray(s)||"function"!=typeof s.toString||0===s.toString().indexOf("[object"))if(Array.isArray(s))for(const e of s){const s=r?"":a;if(null===e)o.push(`${s}- null`);else if(void 0===e)o.push(`${s}- undefined`);else if("function"==typeof e)o.push(`${s}- `);else if("object"==typeof e){const r=Array.isArray(e),a=i?"...":t(e,n+1,!r);o.push(`${s}-${r&&!i?"\n":" "}${a}`)}else o.push(`${s}- ${e}`);r=!1}else{const e=s,u=Object.keys(e),l=u.reduce(((t,s)=>Math.max(t,c(s,e)?t:s.length)),0);for(const s of u){if(c(s,e))continue;const u=r?"":a,h=e[s],d=s.padEnd(l," ");if(null===h)o.push(`${u}${d}: null`);else if(void 0===h)o.push(`${u}${d}: undefined`);else if("function"==typeof h)o.push(`${u}${d}: `);else if("object"==typeof h){const e=Array.isArray(h),s=e&&0===h.length,r=!e&&"function"==typeof h.toString&&0!==h.toString().indexOf("[object"),a=i?"...":s?"[]":t(h,n+1,r);o.push(`${u}${d}:${i||r||s?" ":"\n"}${a}`)}else o.push(`${u}${d}: ${h}`);r=!1}}else o.push(`${r?"":a}${s.toString()}`),r=!1;return o.join("\n")};return t(e.message)}formattedHeaders(e){if(!e.message.headers)return;const t=e.message.headers,s=Object.keys(t).reduce(((e,t)=>Math.max(e,t.length)),0);return Object.keys(t).map((e=>` - ${e.toLowerCase().padEnd(s," ")}: ${t[e]}`)).join("\n")}formattedBody(e){var t;if(!e.message.headers)return;let s,n;const r=e.message.headers,i=null!==(t=r["content-type"])&&void 0!==t?t:r["Content-Type"],a="formData"in e.message?e.message.formData:void 0,o=e.message.body;if(a){const e=a.reduce(((e,{key:t})=>Math.max(e,t.length)),0);s=a.map((({key:t,value:s})=>` - ${t.padEnd(e," ")}: ${s}`)).join("\n")}return o?(n="string"==typeof o?` ${o}`:o instanceof ArrayBuffer?!i||-1===i.indexOf("javascript")&&-1===i.indexOf("json")?` ArrayBuffer { byteLength: ${o.byteLength} }`:` ${Z.decoder.decode(o)}`:` File { name: ${o.name}${o.contentLength?`, contentLength: ${o.contentLength}`:""}${o.mimeType?`, mimeType: ${o.mimeType}`:""} }`,{body:n,formData:s}):{formData:s}}formattedErrorStatus(e){if(!e.message.status)return;const t=e.message.status,s=t.errorData;let n;if(Z.isError(s))n=` ${s.name}: ${s.message}`,s.stack&&(n+=`\n${s.stack.split("\n").map((e=>` ${e}`)).join("\n")}`);else if(s)try{n=` ${JSON.stringify(s)}`}catch(e){n=` ${s}`}return` Category : ${t.category}\n Operation : ${t.operation}\n Status : ${t.statusCode}${n?`\n Error data:\n${n}`:""}`}paddedString(e,t){return e.padEnd(t-e.length," ")}static isError(e){return!!e&&(e instanceof Error||"[object Error]"===Object.prototype.toString.call(e))}}Z.decoder=new TextDecoder;const ee=(e,t)=>{var s,n,r,i;!e.retryConfiguration&&e.enableEventEngine&&(e.retryConfiguration=$.ExponentialRetryPolicy({minimumDelay:2,maximumDelay:150,maximumRetry:6,excluded:[U.MessageSend,U.Presence,U.Files,U.MessageStorage,U.ChannelGroups,U.DevicePushNotifications,U.AppContext,U.MessageReactions]}));const a=`pn-${K.createUUID()}`;e.logVerbosity?e.logLevel=G.Debug:void 0===e.logLevel&&(e.logLevel=G.None);const o=new L(se(a),e.logLevel,[...null!==(s=e.loggers)&&void 0!==s?s:[],new Z]);void 0!==e.logVerbosity&&o.warn("Configuration","'logVerbosity' is deprecated. Use 'logLevel' instead."),null===(n=e.retryConfiguration)||void 0===n||n.validate(),null!==(r=e.useRandomIVs)&&void 0!==r||(e.useRandomIVs=true),e.useRandomIVs&&o.warn("Configuration","'useRandomIVs' is deprecated. Use 'cryptoModule' instead."),e.origin=te(null!==(i=e.ssl)&&void 0!==i&&i,e.origin);const c=e.cryptoModule;c&&delete e.cryptoModule;const u=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_loggerManager:o,_instanceId:a,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(e.useInstanceId)return this._instanceId},getInstanceId(){if(e.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},logger(){return this._loggerManager},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt(),logger:this.logger()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,getKeepPresenceChannelsInPresenceRequests:()=>"Web"===e.sdkFamily&&e.subscriptionWorkerUrl,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},getFileTimeout(){return this.fileRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"9.6.1"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?(o.warn("Configuration","'cipherKey' is deprecated. Use 'cryptoModule' instead."),u.setCipherKey(e.cipherKey)):c&&(u._cryptoModule=c),u},te=(e,t)=>{const s=e?"https://":"http://";return"string"==typeof t?`${s}${t}`:`${s}${t[Math.floor(Math.random()*t.length)]}`},se=e=>{let t=2166136261;for(let s=0;s>>0;return t.toString(16).padStart(8,"0")};class ne{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){const t=this.cbor.decodeToken(e);if(void 0!==t){const e=t.res.uuid?Object.keys(t.res.uuid):[],s=Object.keys(t.res.chan),n=Object.keys(t.res.grp),r=t.pat.uuid?Object.keys(t.pat.uuid):[],i=Object.keys(t.pat.chan),a=Object.keys(t.pat.grp),o={version:t.v,timestamp:t.t,ttl:t.ttl,authorized_uuid:t.uuid,signature:t.sig},c=e.length>0,u=s.length>0,l=n.length>0;if(c||u||l){if(o.resources={},c){const s=o.resources.uuids={};e.forEach((e=>s[e]=this.extractPermissions(t.res.uuid[e])))}if(u){const e=o.resources.channels={};s.forEach((s=>e[s]=this.extractPermissions(t.res.chan[s])))}if(l){const e=o.resources.groups={};n.forEach((s=>e[s]=this.extractPermissions(t.res.grp[s])))}}const h=r.length>0,d=i.length>0,p=a.length>0;if(h||d||p){if(o.patterns={},h){const e=o.patterns.uuids={};r.forEach((s=>e[s]=this.extractPermissions(t.pat.uuid[s])))}if(d){const e=o.patterns.channels={};i.forEach((s=>e[s]=this.extractPermissions(t.pat.chan[s])))}if(p){const e=o.patterns.groups={};a.forEach((s=>e[s]=this.extractPermissions(t.pat.grp[s])))}}return t.meta&&Object.keys(t.meta).length>0&&(o.meta=t.meta),o}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}}var re,ie;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(re||(re={}));class ae{constructor(e,t,s,n){this.publishKey=e,this.secretKey=t,this.hasher=s,this.logger=n}signature(e){const t=e.path.startsWith("/publish")?re.GET:e.method;let s=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===re.POST||t===re.PATCH){const t=e.body;let n;t&&t instanceof ArrayBuffer?n=ae.textDecoder.decode(t):t&&"object"!=typeof t&&(n=t),n&&(s+=n)}return this.logger.trace(this.constructor.name,(()=>({messageType:"text",message:`Request signature input:\n${s}`}))),`v2.${this.hasher(s,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const s=e[t];return Array.isArray(s)?s.sort().map((e=>`${t}=${H(e)}`)).join("&"):`${t}=${H(s)}`})).join("&")}}ae.textDecoder=new TextDecoder("utf-8");class oe{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:s}=e;t.secretKey&&s&&(this.signatureGenerator=new ae(t.publishKey,t.secretKey,s,this.logger))}get logger(){return this.configuration.clientConfiguration.logger()}makeSendable(e){const t=this.configuration.clientConfiguration.retryConfiguration,s=this.configuration.transport;if(void 0!==t){let n,r,i=!1,a=0;const o={abort:e=>{i=!0,n&&clearTimeout(n),r&&r.abort(e)}};return[new Promise(((o,c)=>{const u=()=>{if(i)return;const[l,d]=s.makeSendable(this.request(e));r=d;const p=(s,r)=>{const i=!r||r.category!==h.PNCancelledCategory,l=!s||s.status>=400;let d=-1;i&&l&&t.shouldRetry(e,s,null==r?void 0:r.category,a+1)&&(d=t.getDelay(a,s)),d>0?(a++,this.logger.warn(this.constructor.name,`HTTP request retry #${a} in ${d}ms.`),n=setTimeout((()=>u()),d)):s?o(s):r&&c(r)};l.then((e=>p(e))).catch((e=>p(void 0,e)))};u()})),r?o:void 0]}return s.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:s}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),s.useInstanceId&&(e.queryParameters.instanceid=s.getInstanceId()),e.queryParameters.uuid||(e.queryParameters.uuid=s.userId),s.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=s.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:s,tokenManager:n}=this.configuration,r=null!==(t=n&&n.getToken())&&void 0!==t?t:s.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const s=e._getPnsdkSuffix(" ");return s.length>0&&(t+=s),t}}class ce{constructor(e,t="fetch"){this.logger=e,this.transport=t,e.debug(this.constructor.name,`Create with configuration:\n - transport: ${t}`),"fetch"!==t||window&&window.fetch||(e.warn(this.constructor.name,`'${t}' not supported in this browser. Fallback to the 'xhr' transport.`),this.transport="xhr"),"fetch"===this.transport&&(ce.originalFetch=fetch.bind(window),this.isFetchMonkeyPatched()&&(ce.originalFetch=ce.getOriginalFetch(),e.warn(this.constructor.name,"Native Web Fetch API 'fetch' function monkey patched."),this.isFetchMonkeyPatched(ce.originalFetch)?e.warn(this.constructor.name,"Unable receive native Web Fetch API. There can be issues with subscribe long-poll cancellation"):e.info(this.constructor.name,"Use native Web Fetch API 'fetch' implementation from iframe as APM workaround.")))}makeSendable(e){const t=new AbortController,s={abortController:t,abort:e=>{t.signal.aborted||(this.logger.trace(this.constructor.name,`On-demand request aborting: ${e}`),t.abort(e))}};return[this.webTransportRequestFromTransportRequest(e).then((t=>(this.logger.debug(this.constructor.name,(()=>({messageType:"network-request",message:e}))),this.sendRequest(t,s).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const s=e[1].byteLength>0?e[1]:void 0,{status:n,headers:r}=e[0],i={};r.forEach(((e,t)=>i[t]=e.toLowerCase()));const a={status:n,url:t.url,headers:i,body:s};if(this.logger.debug(this.constructor.name,(()=>({messageType:"network-response",message:a}))),n>=400)throw _.create(a);return a})).catch((t=>{const s=("string"==typeof t?t:t.message).toLowerCase();let n="string"==typeof t?new Error(t):t;throw s.includes("timeout")?this.logger.warn(this.constructor.name,(()=>({messageType:"network-request",message:e,details:"Timeout",canceled:!0}))):s.includes("cancel")||s.includes("abort")?(this.logger.debug(this.constructor.name,(()=>({messageType:"network-request",message:e,details:"Aborted",canceled:!0}))),n=new Error("Aborted"),n.name="AbortError"):s.includes("network")?this.logger.warn(this.constructor.name,(()=>({messageType:"network-request",message:e,details:"Network error",failed:!0}))):this.logger.warn(this.constructor.name,(()=>({messageType:"network-request",message:e,details:_.create(n).message,failed:!0}))),_.create(n)}))))),s]}request(e){return e}sendRequest(e,t){return i(this,void 0,void 0,(function*(){return"fetch"===this.transport?this.sendFetchRequest(e,t):this.sendXHRRequest(e,t)}))}sendFetchRequest(e,t){return i(this,void 0,void 0,(function*(){let s;const n=new Promise(((n,r)=>{s=setTimeout((()=>{clearTimeout(s),r(new Error("Request timeout")),t.abort("Cancel because of timeout")}),1e3*e.timeout)})),r=new Request(e.url,{method:e.method,headers:e.headers,redirect:"follow",body:e.body});return Promise.race([ce.originalFetch(r,{signal:t.abortController.signal,credentials:"omit",cache:"no-cache"}).then((e=>(s&&clearTimeout(s),e))),n])}))}sendXHRRequest(e,t){return i(this,void 0,void 0,(function*(){return new Promise(((s,n)=>{var r;const i=new XMLHttpRequest;i.open(e.method,e.url,!0);let a=!1;i.responseType="arraybuffer",i.timeout=1e3*e.timeout,t.abortController.signal.onabort=()=>{i.readyState!=XMLHttpRequest.DONE&&i.readyState!=XMLHttpRequest.UNSENT&&(a=!0,i.abort())},Object.entries(null!==(r=e.headers)&&void 0!==r?r:{}).forEach((([e,t])=>i.setRequestHeader(e,t))),i.onabort=()=>{n(new Error("Aborted"))},i.ontimeout=()=>{n(new Error("Request timeout"))},i.onerror=()=>{if(!a){const t=this.transportResponseFromXHR(e.url,i);n(new Error(_.create(t).message))}},i.onload=()=>{const e=new Headers;i.getAllResponseHeaders().split("\r\n").forEach((t=>{const[s,n]=t.split(": ");s.length>1&&n.length>1&&e.append(s,n)})),s(new Response(i.response,{status:i.status,headers:e,statusText:i.statusText}))},i.send(e.body)}))}))}webTransportRequestFromTransportRequest(e){return i(this,void 0,void 0,(function*(){let t,s=e.path;if(e.formData&&e.formData.length>0){e.queryParameters={};const s=e.body,n=new FormData;for(const{key:t,value:s}of e.formData)n.append(t,s);try{const e=yield s.toArrayBuffer();n.append("file",new Blob([e],{type:"application/octet-stream"}),s.name)}catch(e){this.logger.warn(this.constructor.name,(()=>({messageType:"error",message:e})));try{const e=yield s.toFileUri();n.append("file",e,s.name)}catch(e){this.logger.error(this.constructor.name,(()=>({messageType:"error",message:e})))}}t=n}else if(e.body&&("string"==typeof e.body||e.body instanceof ArrayBuffer))if(e.compressible&&"undefined"!=typeof CompressionStream){const s="string"==typeof e.body?ce.encoder.encode(e.body):e.body,n=s.byteLength,r=new ReadableStream({start(e){e.enqueue(s),e.close()}});t=yield new Response(r.pipeThrough(new CompressionStream("deflate"))).arrayBuffer(),this.logger.trace(this.constructor.name,(()=>{const e=t.byteLength,s=(e/n).toFixed(2);return{messageType:"text",message:`Body of ${n} bytes, compressed by ${s}x to ${e} bytes.`}}))}else t=e.body;return e.queryParameters&&0!==Object.keys(e.queryParameters).length&&(s=`${s}?${V(e.queryParameters)}`),{url:`${e.origin}${s}`,method:e.method,headers:e.headers,timeout:e.timeout,body:t}}))}isFetchMonkeyPatched(e){return!(null!=e?e:fetch).toString().includes("[native code]")&&"fetch"!==fetch.name}transportResponseFromXHR(e,t){const s=t.getAllResponseHeaders().split("\n"),n={};for(const e of s){const[t,s]=e.trim().split(":");t&&s&&(n[t.toLowerCase()]=s.trim())}return{status:t.status,url:e,headers:n,body:t.response}}static getOriginalFetch(){let e=document.querySelector('iframe[name="pubnub-context-unpatched-fetch"]');return e||(e=document.createElement("iframe"),e.style.display="none",e.name="pubnub-context-unpatched-fetch",e.src="about:blank",document.body.appendChild(e)),e.contentWindow?e.contentWindow.fetch.bind(e.contentWindow):fetch}}ce.encoder=new TextEncoder,ce.decoder=new TextDecoder;class ue{constructor(e){this.params=e,this.requestIdentifier=K.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(e){this&&this.cancellationController&&this.cancellationController.abort(e)}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return i(this,void 0,void 0,(function*(){return this.deserializeResponse(e)}))}request(){var e,t,s,n,r,i;const a={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:re.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(n=null===(s=this.params)||void 0===s?void 0:s.cancellable)&&void 0!==n&&n,compressible:null!==(i=null===(r=this.params)||void 0===r?void 0:r.compressible)&&void 0!==i&&i,timeout:10,identifier:this.requestIdentifier},o=this.headers;if(o&&(a.headers=o),a.method===re.POST||a.method===re.PATCH){const[e,t]=[this.body,this.formData];t&&(a.formData=t),e&&(a.body=e)}return a}get headers(){var e,t;return Object.assign({"Accept-Encoding":"gzip, deflate"},null!==(t=null===(e=this.params)||void 0===e?void 0:e.compressible)&&void 0!==t&&t?{"Content-Encoding":"deflate"}:{})}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=ue.decoder.decode(e.body),s=e.headers["content-type"];let n;if(!s||-1===s.indexOf("javascript")&&-1===s.indexOf("json"))throw new d("Service response error, check status for details",g(t,e.status));try{n=JSON.parse(t)}catch(s){throw console.error("Error parsing JSON response:",s),new d("Service response error, check status for details",g(t,e.status))}if("status"in n&&"number"==typeof n.status&&n.status>=400)throw _.create(e);return n}}ue.decoder=new TextDecoder,function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(ie||(ie={}));var le=ie;var he;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files"}(he||(he={}));class de extends ue{constructor(e){var t,s,n,r,i,a;super({cancellable:!0}),this.parameters=e,null!==(t=(r=this.parameters).withPresence)&&void 0!==t||(r.withPresence=false),null!==(s=(i=this.parameters).channelGroups)&&void 0!==s||(i.channelGroups=[]),null!==(n=(a=this.parameters).channels)&&void 0!==n||(a.channels=[])}operation(){return le.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;return e?t||s?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){let t,s;try{s=ue.decoder.decode(e.body);t=JSON.parse(s)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new d("Service response error, check status for details",g(s,e.status));const n=t.m.filter((e=>{const t=void 0===e.b?e.c:e.b;return this.parameters.channels&&this.parameters.channels.includes(t)||this.parameters.channelGroups&&this.parameters.channelGroups.includes(t)})).map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?he.Presence:he.Message),t!=he.Signal&&"string"==typeof e.d?t==he.Message?{type:he.Message,data:this.messageFromEnvelope(e)}:{type:he.Files,data:this.fileFromEnvelope(e)}:t==he.Message?{type:he.Message,data:this.messageFromEnvelope(e)}:t===he.Presence?{type:he.Presence,data:this.presenceEventFromEnvelope(e)}:t==he.Signal?{type:he.Signal,data:this.signalFromEnvelope(e)}:t===he.AppContext?{type:he.AppContext,data:this.appContextFromEnvelope(e)}:t===he.MessageAction?{type:he.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:he.Files,data:this.fileFromEnvelope(e)}}));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:n}}))}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{accept:"text/javascript"})}presenceEventFromEnvelope(e){var t;const{d:s}=e,[n,r]=this.subscriptionChannelFromEnvelope(e),i=n.replace("-pnpres",""),a=null!==r?i:null,o=null!==r?r:i;return"string"!=typeof s&&("data"in s?(s.state=s.data,delete s.data):"action"in s&&"interval"===s.action&&(s.hereNowRefresh=null!==(t=s.here_now_refresh)&&void 0!==t&&t,delete s.here_now_refresh)),Object.assign({channel:i,subscription:r,actualChannel:a,subscribedChannel:o,timetoken:e.p.t},s)}messageFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d),i={channel:t,subscription:s,actualChannel:null!==s?t:null,subscribedChannel:null!==s?s:t,timetoken:e.p.t,publisher:e.i,message:n};return e.u&&(i.userMetadata=e.u),e.cmt&&(i.customMessageType=e.cmt),r&&(i.error=r),i}signalFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(n.userMetadata=e.u),e.cmt&&(n.customMessageType=e.cmt),n}messageActionFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,event:n.event,data:Object.assign(Object.assign({},n.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,message:n}}fileFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d);let i=r;const a={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i};return e.u&&(a.userMetadata=e.u),n?"string"==typeof n?null!=i||(i="Unexpected file information payload data type."):(a.message=n.message,n.file&&(a.file={id:n.file.id,name:n.file.name,url:this.parameters.getFileUrl({id:n.file.id,name:n.file.name,channel:t})})):null!=i||(i="File information payload is missing."),e.cmt&&(a.customMessageType=e.cmt),i&&(a.error=i),a}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,s;try{const s=this.parameters.crypto.decrypt(e);t=s instanceof ArrayBuffer?JSON.parse(pe.decoder.decode(s)):s}catch(e){t=null,s=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,s]}}class pe extends de{get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/subscribe/${t}/${B(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:s,state:n,timetoken:r,region:i}=this.parameters,a={};return e&&e.length>0&&(a["channel-group"]=e.sort().join(",")),t&&t.length>0&&(a["filter-expr"]=t),s&&(a.heartbeat=s),n&&Object.keys(n).length>0&&(a.state=JSON.stringify(n)),void 0!==r&&"string"==typeof r?r.length>0&&"0"!==r&&(a.tt=r):void 0!==r&&r>0&&(a.tt=r),i&&(a.tr=i),a}}class ge{constructor(){this.hasListeners=!1,this.listeners=[{count:-1,listener:{}}]}set onStatus(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"status"})}set onMessage(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"message"})}set onPresence(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"presence"})}set onSignal(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"signal"})}set onObjects(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"objects"})}set onMessageAction(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"messageAction"})}set onFile(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"file"})}handleEvent(e){if(this.hasListeners)if(e.type===he.Message)this.announce("message",e.data);else if(e.type===he.Signal)this.announce("signal",e.data);else if(e.type===he.Presence)this.announce("presence",e.data);else if(e.type===he.AppContext){const{data:t}=e,{message:s}=t;if(this.announce("objects",t),"uuid"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:a,type:o}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"user"})});this.announce("user",u)}else if("channel"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:a,type:o}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"space"})});this.announce("space",u)}else if("membership"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:a,data:o}=s,c=r(s,["event","data"]),{uuid:u,channel:l}=o,h=r(o,["uuid","channel"]),d=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",data:Object.assign(Object.assign({},h),{user:u,space:l})})});this.announce("membership",d)}}else e.type===he.MessageAction?this.announce("messageAction",e.data):e.type===he.Files&&this.announce("file",e.data)}handleStatus(e){this.hasListeners&&this.announce("status",e)}addListener(e){this.updateTypeOrObjectListener({add:!0,listener:e})}removeListener(e){this.updateTypeOrObjectListener({add:!1,listener:e})}removeAllListeners(){this.listeners=[{count:-1,listener:{}}],this.hasListeners=!1}updateTypeOrObjectListener(e){if(e.type)"function"==typeof e.listener?this.listeners[0].listener[e.type]=e.listener:delete this.listeners[0].listener[e.type];else if(e.listener&&"function"!=typeof e.listener){let t,s=!1;for(t of this.listeners)if(t.listener===e.listener){e.add?(t.count++,s=!0):(t.count--,0===t.count&&this.listeners.splice(this.listeners.indexOf(t),1));break}e.add&&!s&&this.listeners.push({count:1,listener:e.listener})}this.hasListeners=this.listeners.length>1||Object.keys(this.listeners[0]).length>0}announce(e,t){this.listeners.forEach((({listener:s})=>{const n=s[e];n&&n(t)}))}}class be{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class me{constructor(e){this.config=e,e.logger().debug(this.constructor.name,(()=>({messageType:"object",message:{maximumCacheSize:e.maximumCacheSize},details:"Create with configuration:"}))),this.maximumCacheSize=e.maximumCacheSize,this.hashHistory=[]}getKey(e){var t;return`${e.timetoken}-${this.hashCode(JSON.stringify(null!==(t=e.message)&&void 0!==t?t:"")).toString()}`}isDuplicate(e){return this.hashHistory.includes(this.getKey(e))}addEntry(e){this.hashHistory.length>=this.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}hashCode(e){let t=0;if(0===e.length)return t;for(let s=0;s{this.pendingChannelSubscriptions.add(e),this.channels[e]={},r&&(this.presenceChannels[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==s||s.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},r&&(this.presenceChannelGroups[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t=!1){let{channels:s,channelGroups:n}=e;const i=new Set,a=new Set;null==s||s.forEach((e=>{e in this.channels&&(delete this.channels[e],a.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],a.add(e))})),null==n||n.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],i.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],i.add(e))})),0===a.size&&0===i.size||(!1!==this.configuration.suppressLeaveEvents||t||(n=Array.from(i),s=Array.from(a),this.leaveCall({channels:s,channelGroups:n},(e=>{const{error:t}=e,i=r(e,["error"]);let a;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?a=e.errorData.message:"message"in e&&"string"==typeof e.message&&(a=e.message)),this.emitStatus(Object.assign(Object.assign({},i),{error:null!=a&&a,affectedChannels:s,affectedChannelGroups:n,currentTimetoken:this.currentTimetoken,lastTimetoken:this.lastTimetoken}))}))),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.referenceTimetoken=null,this.storedTimetoken=null,this.region=null,this.reconnectionManager.stopPolling()),this.reconnect(!0))}unsubscribeAll(e=!1){this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(e=!1){this.stopSubscribeLoop();const t=[...Object.keys(this.channelGroups)],s=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((e=>t.push(`${e}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>s.push(`${e}-pnpres`))),0===s.length&&0===t.length||(this.subscribeCall(Object.assign(Object.assign({channels:s,channelGroups:t,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken},null!==this.region?{region:this.region}:{}),this.configuration.filterExpression?{filterExpression:this.configuration.filterExpression}:{}),((e,t)=>{this.processSubscribeResponse(e,t)})),!e&&this.configuration.useSmartHeartbeat&&this.startHeartbeatTimer())}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===h.PNCancelledCategory)return;return void(e.category===h.PNTimeoutCategory?this.startSubscribeLoop():e.category===h.PNNetworkIssuesCategory||e.category===h.PNMalformedResponseCategory?(this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.emitStatus({category:h.PNNetworkDownCategory})),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.emitStatus({category:h.PNNetworkUpCategory})),this.reconnect(),this.subscriptionStatusAnnounced=!0;const t={category:h.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.emitStatus(t)})),this.reconnectionManager.startPolling(),this.emitStatus(Object.assign(Object.assign({},e),{category:h.PNNetworkIssuesCategory}))):e.category===h.PNBadRequestCategory?(this.stopHeartbeatTimer(),this.emitStatus(e)):this.emitStatus(e))}if(this.referenceTimetoken=X(t.cursor.timetoken,this.storedTimetoken),this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const t={category:h.PNConnectedCategory,operation:e.operation,affectedChannels:Array.from(this.pendingChannelSubscriptions),subscribedChannels:this.subscribedChannels,affectedChannelGroups:Array.from(this.pendingChannelGroupSubscriptions),lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.subscriptionStatusAnnounced=!0,this.emitStatus(t),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:s}=t,{requestMessageCountThreshold:n,dedupeOnSubscribe:r}=this.configuration;n&&s.length>=n&&this.emitStatus({category:h.PNRequestMessageCountExceededCategory,operation:e.operation});try{const e={timetoken:this.currentTimetoken,region:this.region?this.region:void 0};this.configuration.logger().debug(this.constructor.name,(()=>({messageType:"object",message:s.map((e=>{const t=e.type===he.Message||e.type===he.Signal?Y(e.data.message):void 0;return t?{type:e.type,data:Object.assign(Object.assign({},e.data),{pn_mfp:t})}:e})),details:"Received events:"}))),s.forEach((t=>{if(r&&"message"in t.data&&"timetoken"in t.data){if(this.dedupingManager.isDuplicate(t.data))return void this.configuration.logger().warn(this.constructor.name,(()=>({messageType:"object",message:t.data,details:"Duplicate message detected (skipped):"})));this.dedupingManager.addEntry(t.data)}this.emitEvent(e,t)}))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.emitStatus(t)}this.region=t.cursor.region,this.startSubscribeLoop()}setState(e){const{state:t,channels:s,channelGroups:n}=e;null==s||s.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==n||n.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:s,channelGroups:n}=e;t?(null==s||s.forEach((e=>this.heartbeatChannels[e]={})),null==n||n.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==s||s.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==n||n.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:s,channelGroups:n},(e=>this.emitStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.configuration.useSmartHeartbeat||this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.emitStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.emitStatus({category:h.PNNetworkDownCategory}),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.emitStatus(e)}))}}class fe{constructor(e,t,s){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=s}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class ve extends fe{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:s}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return s&&Object.keys(s).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,s={}),this._isSilent||s&&Object.keys(s).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:s}=e,n={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(n.collapse_id=t),s&&(n.expiration=s.toISOString()),n}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:s="development",excludedDevices:n=[]}=e,r={topic:t,environment:s};return n.length&&(r.excluded_devices=n),r}}class Se extends fe{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this._body=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.notification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.payload.notification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.payload.notification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={}}toObject(){let e=Object.assign({},this.payload.data),t=null;const s={};if(Object.keys(this.payload).length>2){const t=r(this.payload,["notification","data"]);e=Object.assign(Object.assign({},e),t)}return this._isSilent?e.notification=this.payload.notification:t=this.payload.notification,Object.keys(e).length&&(s.data=e),t&&Object.keys(t).length&&(s.notification=t),Object.keys(s).length?s:null}}class we{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new ve(this._payload.apns,e,t),this.fcm=new Se(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const s=this.apns.toObject();s&&Object.keys(s).length&&(t.pn_apns=s)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_gcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class Oe{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class ke{transition(e,t){var s;if(this.transitionMap.has(t.type))return null===(s=this.transitionMap.get(t.type))||void 0===s?void 0:s(e,t)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class Ce extends Oe{constructor(e){super(!0),this.logger=e,this._pendingEvents=[],this._inTransition=!1}get currentState(){return this._currentState}get currentContext(){return this._currentContext}describe(e){return new ke(e)}start(e,t){this._currentState=e,this._currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this._currentState)throw this.logger.error(this.constructor.name,"Finite state machine is not started"),new Error("Start the engine first");if(this._inTransition)return this.logger.trace(this.constructor.name,(()=>({messageType:"object",message:e,details:"Event engine in transition. Enqueue received event:"}))),void this._pendingEvents.push(e);this._inTransition=!0,this.logger.trace(this.constructor.name,(()=>({messageType:"object",message:e,details:"Event engine received event:"}))),this.notify({type:"eventReceived",event:e});const t=this._currentState.transition(this._currentContext,e);if(t){const[s,n,r]=t;this.logger.trace(this.constructor.name,`Exiting state: ${this._currentState.label}`);for(const e of this._currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this._currentContext)});this.logger.trace(this.constructor.name,(()=>({messageType:"object",details:`Entering '${s.label}' state with context:`,message:n})));const i=this._currentState;this._currentState=s;const a=this._currentContext;this._currentContext=n,this.notify({type:"transitionDone",fromState:i,fromContext:a,toState:s,toContext:n,event:e});for(const e of r)this.notify({type:"invocationDispatched",invocation:e});for(const e of this._currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this._currentContext)});if(this._inTransition=!1,this._pendingEvents.length>0){const e=this._pendingEvents.shift();e&&(this.logger.trace(this.constructor.name,(()=>({messageType:"object",message:e,details:"De-queueing pending event:"}))),this.transition(e))}}else this.logger.warn(this.constructor.name,`No transition from '${this._currentState.label}' found for event: ${e.type}`)}}class Pe{constructor(e,t){this.dependencies=e,this.logger=t,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if(this.logger.trace(this.constructor.name,`Process invocation: ${e.type}`),"CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw this.logger.error(this.constructor.name,`Unhandled invocation '${e.type}'`),new Error(`Unhandled invocation '${e.type}'`);const s=t(e.payload,this.dependencies);this.logger.trace(this.constructor.name,(()=>({messageType:"object",details:"Call invocation handler with parameters:",message:e.payload,ignoredKeys:["abortSignal"]}))),e.managed&&this.instances.set(e.type,s),s.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function je(e,t){const s=function(...s){return{type:e,payload:null==t?void 0:t(...s)}};return s.type=e,s}function Ee(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!1});return s.type=e,s}function Ne(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!0});return s.type=e,s.cancel={type:"CANCEL",payload:e,managed:!1},s}class Te extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class _e extends Oe{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new Te}abort(){this._aborted=!0,this.notify(new Te)}}class Ie{constructor(e,t){this.payload=e,this.dependencies=t}}class Me extends Ie{constructor(e,t,s){super(e,t),this.asyncFunction=s,this.abortSignal=new _e}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const Ae=e=>(t,s)=>new Me(t,s,e),Ue=Ne("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),$e=Ee("LEAVE",((e,t)=>({channels:e,groups:t}))),Re=Ee("EMIT_STATUS",(e=>e)),Fe=Ne("WAIT",(()=>({}))),De=je("RECONNECT",(()=>({}))),xe=je("DISCONNECT",((e=!1)=>({isOffline:e}))),Ge=je("JOINED",((e,t)=>({channels:e,groups:t}))),qe=je("LEFT",((e,t)=>({channels:e,groups:t}))),Ke=je("LEFT_ALL",((e=!1)=>({isOffline:e}))),Le=je("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),He=je("HEARTBEAT_FAILURE",(e=>e)),Be=je("TIMES_UP",(()=>({})));class We extends Pe{constructor(e,t){super(t,t.config.logger()),this.on(Ue.type,Ae(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,presenceState:r,config:i}){try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},i.maintainPresenceState&&{state:r}),{heartbeat:i.presenceTimeout}));e.transition(Le(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;e.transition(He(t))}}}))))),this.on($e.type,Ae(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{leave:s,config:n}){if(!n.suppressLeaveEvents)try{s({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(Fe.type,Ae(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeatDelay:n}){return s.throwIfAborted(),yield n(),s.throwIfAborted(),e.transition(Be())}))))),this.on(Re.type,Ae(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s,config:n}){n.announceFailedHeartbeats&&!0===(null==e?void 0:e.error)?s(Object.assign(Object.assign({},e),{operation:le.PNHeartbeatOperation})):n.announceSuccessfulHeartbeats&&200===e.statusCode&&s(Object.assign(Object.assign({},e),{error:!1,operation:le.PNHeartbeatOperation,category:h.PNAcknowledgmentCategory}))})))))}}const ze=new ke("HEARTBEAT_STOPPED");ze.on(Ge.type,((e,t)=>ze.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),ze.on(qe.type,((e,t)=>ze.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),ze.on(De.type,((e,t)=>Xe.with({channels:e.channels,groups:e.groups}))),ze.on(Ke.type,((e,t)=>Qe.with(void 0)));const Ve=new ke("HEARTBEAT_COOLDOWN");Ve.onEnter((()=>Fe())),Ve.onExit((()=>Fe.cancel)),Ve.on(Be.type,((e,t)=>Xe.with({channels:e.channels,groups:e.groups}))),Ve.on(Ge.type,((e,t)=>Xe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ve.on(qe.type,((e,t)=>Xe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[$e(t.payload.channels,t.payload.groups)]))),Ve.on(xe.type,((e,t)=>ze.with({channels:e.channels,groups:e.groups},[...t.payload.isOffline?[]:[$e(e.channels,e.groups)]]))),Ve.on(Ke.type,((e,t)=>Qe.with(void 0,[...t.payload.isOffline?[]:[$e(e.channels,e.groups)]])));const Je=new ke("HEARTBEAT_FAILED");Je.on(Ge.type,((e,t)=>Xe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Je.on(qe.type,((e,t)=>Xe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[$e(t.payload.channels,t.payload.groups)]))),Je.on(De.type,((e,t)=>Xe.with({channels:e.channels,groups:e.groups}))),Je.on(xe.type,((e,t)=>ze.with({channels:e.channels,groups:e.groups},[...t.payload.isOffline?[]:[$e(e.channels,e.groups)]]))),Je.on(Ke.type,((e,t)=>Qe.with(void 0,[...t.payload.isOffline?[]:[$e(e.channels,e.groups)]])));const Xe=new ke("HEARTBEATING");Xe.onEnter((e=>Ue(e.channels,e.groups))),Xe.onExit((()=>Ue.cancel)),Xe.on(Le.type,((e,t)=>Ve.with({channels:e.channels,groups:e.groups},[Re(Object.assign({},t.payload))]))),Xe.on(Ge.type,((e,t)=>Xe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Xe.on(qe.type,((e,t)=>Xe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[$e(t.payload.channels,t.payload.groups)]))),Xe.on(He.type,((e,t)=>Je.with(Object.assign({},e),[...t.payload.status?[Re(Object.assign({},t.payload.status))]:[]]))),Xe.on(xe.type,((e,t)=>ze.with({channels:e.channels,groups:e.groups},[...t.payload.isOffline?[]:[$e(e.channels,e.groups)]]))),Xe.on(Ke.type,((e,t)=>Qe.with(void 0,[...t.payload.isOffline?[]:[$e(e.channels,e.groups)]])));const Qe=new ke("HEARTBEAT_INACTIVE");Qe.on(Ge.type,((e,t)=>Xe.with({channels:t.payload.channels,groups:t.payload.groups})));class Ye{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.channels=[],this.groups=[],this.engine=new Ce(e.config.logger()),this.dispatcher=new We(this.engine,e),e.config.logger().debug(this.constructor.name,"Create presence event engine."),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(Qe,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],this.engine.transition(Ge(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(qe(null!=e?e:[],null!=t?t:[]))}leaveAll(e=!1){this.engine.transition(Ke(e))}reconnect(){this.engine.transition(De())}disconnect(e=!1){this.engine.transition(xe(e))}dispose(){this.disconnect(!0),this._unsubscribeEngine(),this.dispatcher.dispose()}}const Ze=Ne("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),et=Ne("RECEIVE_MESSAGES",((e,t,s)=>({channels:e,groups:t,cursor:s}))),tt=Ee("EMIT_MESSAGES",((e,t)=>({cursor:e,events:t}))),st=Ee("EMIT_STATUS",(e=>e)),nt=je("SUBSCRIPTION_CHANGED",((e,t,s=!1)=>({channels:e,groups:t,isOffline:s}))),rt=je("SUBSCRIPTION_RESTORED",((e,t,s,n)=>({channels:e,groups:t,cursor:{timetoken:s,region:null!=n?n:0}}))),it=je("HANDSHAKE_SUCCESS",(e=>e)),at=je("HANDSHAKE_FAILURE",(e=>e)),ot=je("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),ct=je("RECEIVE_FAILURE",(e=>e)),ut=je("DISCONNECT",((e=!1)=>({isOffline:e}))),lt=je("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),ht=je("UNSUBSCRIBE_ALL",(()=>({}))),dt=new ke("UNSUBSCRIBED");dt.on(nt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):bt.with({channels:t.channels,groups:t.groups}))),dt.on(rt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):bt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region}})));const pt=new ke("HANDSHAKE_STOPPED");pt.on(nt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):pt.with({channels:t.channels,groups:t.groups,cursor:e.cursor}))),pt.on(lt.type,((e,{payload:t})=>bt.with(Object.assign(Object.assign({},e),{cursor:t.cursor||e.cursor})))),pt.on(rt.type,((e,{payload:t})=>{var s;return 0===t.channels.length&&0===t.groups.length?dt.with(void 0):pt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||(null===(s=e.cursor)||void 0===s?void 0:s.region)||0}})})),pt.on(ht.type,(e=>dt.with()));const gt=new ke("HANDSHAKE_FAILED");gt.on(nt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):bt.with({channels:t.channels,groups:t.groups,cursor:e.cursor}))),gt.on(lt.type,((e,{payload:t})=>bt.with(Object.assign(Object.assign({},e),{cursor:t.cursor||e.cursor})))),gt.on(rt.type,((e,{payload:t})=>{var s,n;return 0===t.channels.length&&0===t.groups.length?dt.with(void 0):bt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region?t.cursor.region:null!==(n=null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)&&void 0!==n?n:0}})})),gt.on(ht.type,(e=>dt.with()));const bt=new ke("HANDSHAKING");bt.onEnter((e=>Ze(e.channels,e.groups))),bt.onExit((()=>Ze.cancel)),bt.on(nt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):bt.with({channels:t.channels,groups:t.groups,cursor:e.cursor}))),bt.on(it.type,((e,{payload:t})=>{var s,n,r,i,a;return ft.with({channels:e.channels,groups:e.groups,cursor:{timetoken:(null===(s=e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=e.cursor)||void 0===n?void 0:n.timetoken:t.timetoken,region:t.region},referenceTimetoken:X(t.timetoken,null===(r=e.cursor)||void 0===r?void 0:r.timetoken)},[st({category:h.PNConnectedCategory,affectedChannels:e.channels.slice(0),affectedChannelGroups:e.groups.slice(0),currentTimetoken:(null===(i=e.cursor)||void 0===i?void 0:i.timetoken)?null===(a=e.cursor)||void 0===a?void 0:a.timetoken:t.timetoken})])})),bt.on(at.type,((e,t)=>{var s;return gt.with(Object.assign(Object.assign({},e),{reason:t.payload}),[st({category:h.PNConnectionErrorCategory,error:null===(s=t.payload.status)||void 0===s?void 0:s.category})])})),bt.on(ut.type,((e,t)=>{var s;if(t.payload.isOffline){const t=_.create(new Error("Network connection error")).toPubNubError(le.PNSubscribeOperation);return gt.with(Object.assign(Object.assign({},e),{reason:t}),[st({category:h.PNConnectionErrorCategory,error:null===(s=t.status)||void 0===s?void 0:s.category})])}return pt.with(Object.assign({},e))})),bt.on(rt.type,((e,{payload:t})=>{var s;return 0===t.channels.length&&0===t.groups.length?dt.with(void 0):bt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),bt.on(ht.type,(e=>dt.with()));const mt=new ke("RECEIVE_STOPPED");mt.on(nt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):mt.with({channels:t.channels,groups:t.groups,cursor:e.cursor}))),mt.on(rt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):mt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||e.cursor.region}}))),mt.on(lt.type,((e,{payload:t})=>{var s;return bt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.cursor.timetoken?null===(s=t.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.cursor.region||e.cursor.region}})})),mt.on(ht.type,(()=>dt.with(void 0)));const yt=new ke("RECEIVE_FAILED");yt.on(lt.type,((e,{payload:t})=>{var s;return bt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.cursor.timetoken?null===(s=t.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.cursor.region||e.cursor.region}})})),yt.on(nt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):bt.with({channels:t.channels,groups:t.groups,cursor:e.cursor}))),yt.on(rt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):bt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||e.cursor.region}}))),yt.on(ht.type,(e=>dt.with(void 0)));const ft=new ke("RECEIVING");ft.onEnter((e=>et(e.channels,e.groups,e.cursor))),ft.onExit((()=>et.cancel)),ft.on(ot.type,((e,{payload:t})=>ft.with({channels:e.channels,groups:e.groups,cursor:t.cursor,referenceTimetoken:X(t.cursor.timetoken)},[tt(e.cursor,t.events)]))),ft.on(nt.type,((e,{payload:t})=>{var s;if(0===t.channels.length&&0===t.groups.length){let e;return t.isOffline&&(e=null===(s=_.create(new Error("Network connection error")).toPubNubError(le.PNSubscribeOperation).status)||void 0===s?void 0:s.category),dt.with(void 0,[st(Object.assign({category:t.isOffline?h.PNDisconnectedUnexpectedlyCategory:h.PNDisconnectedCategory},e?{error:e}:{}))])}return ft.with({channels:t.channels,groups:t.groups,cursor:e.cursor,referenceTimetoken:e.referenceTimetoken},[st({category:h.PNSubscriptionChangedCategory,affectedChannels:t.channels.slice(0),affectedChannelGroups:t.groups.slice(0),currentTimetoken:e.cursor.timetoken})])})),ft.on(rt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0,[st({category:h.PNDisconnectedCategory})]):ft.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||e.cursor.region},referenceTimetoken:X(e.cursor.timetoken,`${t.cursor.timetoken}`,e.referenceTimetoken)},[st({category:h.PNSubscriptionChangedCategory,affectedChannels:t.channels.slice(0),affectedChannelGroups:t.groups.slice(0),currentTimetoken:t.cursor.timetoken})]))),ft.on(ct.type,((e,{payload:t})=>{var s;return yt.with(Object.assign(Object.assign({},e),{reason:t}),[st({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(s=t.status)||void 0===s?void 0:s.category})])})),ft.on(ut.type,((e,t)=>{var s;if(t.payload.isOffline){const t=_.create(new Error("Network connection error")).toPubNubError(le.PNSubscribeOperation);return yt.with(Object.assign(Object.assign({},e),{reason:t}),[st({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(s=t.status)||void 0===s?void 0:s.category})])}return mt.with(Object.assign({},e),[st({category:h.PNDisconnectedCategory})])})),ft.on(ht.type,(e=>dt.with(void 0,[st({category:h.PNDisconnectedCategory})])));class vt extends Pe{constructor(e,t){super(t,t.config.logger()),this.on(Ze.type,Ae(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,presenceState:r,config:i}){s.throwIfAborted();try{const a=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:i.filterExpression},i.maintainPresenceState&&{state:r}));return e.transition(it(a))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(at(t))}}}))))),this.on(et.type,Ae(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,config:r}){s.throwIfAborted();try{const i=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:r.filterExpression});e.transition(ot(i.cursor,i.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;if(!s.aborted)return e.transition(ct(t))}}}))))),this.on(tt.type,Ae(((e,t,s)=>i(this,[e,t,s],void 0,(function*({cursor:e,events:t},s,{emitMessages:n}){t.length>0&&n(e,t)}))))),this.on(st.type,Ae(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s}){return s(e)})))))}}class St{get _engine(){return this.engine}constructor(e){this.channels=[],this.groups=[],this.dependencies=e,this.engine=new Ce(e.config.logger()),this.dispatcher=new vt(this.engine,e),e.config.logger().debug(this.constructor.name,"Create subscribe event engine."),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(dt,void 0)}get subscriptionTimetoken(){const e=this.engine.currentState;if(!e)return;let t,s="0";if(e.label===ft.label){const e=this.engine.currentContext;s=e.cursor.timetoken,t=e.referenceTimetoken}return J(s,null!=t?t:"0")}subscribe({channels:e,channelGroups:t,timetoken:s,withPresence:n}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],n&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),s?this.engine.transition(rt(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),s)):this.engine.transition(nt(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])))),this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const s=W(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),n=W(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(s).size||new Set(this.groups).size!==new Set(n).size){const r=z(this.channels,e),i=z(this.groups,t);this.dependencies.presenceState&&(null==r||r.forEach((e=>delete this.dependencies.presenceState[e])),null==i||i.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=s,this.groups=n,this.engine.transition(nt(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:r.slice(0),groups:i.slice(0)})}}unsubscribeAll(e=!1){const t=this.getSubscribedChannels(),s=this.getSubscribedChannels();this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(nt(this.channels.slice(0),this.groups.slice(0),e)),this.dependencies.leaveAll&&this.dependencies.leaveAll({channels:s,groups:t,isOffline:e})}reconnect({timetoken:e,region:t}){const s=this.getSubscribedChannels(),n=this.getSubscribedChannels();this.engine.transition(lt(e,t)),this.dependencies.presenceReconnect&&this.dependencies.presenceReconnect({channels:n,groups:s})}disconnect(e=!1){const t=this.getSubscribedChannels(),s=this.getSubscribedChannels();this.engine.transition(ut(e)),this.dependencies.presenceDisconnect&&this.dependencies.presenceDisconnect({channels:s,groups:t,isOffline:e})}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(!0),this._unsubscribeEngine(),this.dispatcher.dispose()}}class wt extends ue{constructor(e){var t;const s=null!==(t=e.sendByPost)&&void 0!==t&&t;super({method:s?re.POST:re.GET,compressible:s}),this.parameters=e,this.parameters.sendByPost=s}operation(){return le.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:s}=this.parameters,n=this.prepareMessagePayload(e);return`/publish/${s.publishKey}/${s.subscribeKey}/0/${H(t)}/0${this.parameters.sendByPost?"":`/${H(n)}`}`}get queryParameters(){const{customMessageType:e,meta:t,replicate:s,storeInHistory:n,ttl:r}=this.parameters,i={};return e&&(i.custom_message_type=e),void 0!==n&&(i.store=n?"1":"0"),void 0!==r&&(i.ttl=r),void 0===s||s||(i.norep="true"),t&&"object"==typeof t&&(i.meta=JSON.stringify(t)),i}get headers(){var e;return this.parameters.sendByPost?Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"}):super.headers}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Ot extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:s,message:n}=this.parameters,r=JSON.stringify(n);return`/signal/${e}/${t}/0/${H(s)}/0/${H(r)}`}get queryParameters(){const{customMessageType:e}=this.parameters,t={};return e&&(t.custom_message_type=e),t}}class kt extends de{operation(){return le.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${B(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:s,region:n}=this.parameters,r={ee:""};return e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),t&&t.length>0&&(r["filter-expr"]=t),"string"==typeof s?s&&"0"!==s&&s.length>0&&(r.tt=s):s&&s>0&&(r.tt=s),n&&(r.tr=n),r}}class Ct extends de{operation(){return le.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${B(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,state:s}=this.parameters,n={ee:""};return e&&e.length>0&&(n["channel-group"]=e.sort().join(",")),t&&t.length>0&&(n["filter-expr"]=t),s&&Object.keys(s).length>0&&(n.state=JSON.stringify(s)),n}}class Pt extends ue{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=(n=this.parameters).channels)&&void 0!==t||(n.channels=[]),null!==(s=(r=this.parameters).channelGroups)&&void 0!==s||(r.channelGroups=[])}operation(){return le.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),{channels:s=[],channelGroups:n=[]}=this.parameters,r={channels:{}};return 1===s.length&&0===n.length?r.channels[s[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${B(null!=s?s:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class jt extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:s=[],channelGroups:n=[]}=this.parameters;return e?t?0===(null==s?void 0:s.length)&&0===(null==n?void 0:n.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing State":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{state:this.deserializeResponse(e).payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${B(null!=s?s:[],",")}/uuid/${H(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,s={state:JSON.stringify(t)};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),s}}class Et extends ue{constructor(e){super({cancellable:!0}),this.parameters=e}operation(){return le.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${B(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:s}=this.parameters,n={heartbeat:`${s}`};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),t&&(n.state=JSON.stringify(t)),n}}class Nt extends ue{constructor(e){super(),this.parameters=e,this.parameters.channelGroups&&(this.parameters.channelGroups=Array.from(new Set(this.parameters.channelGroups))),this.parameters.channels&&(this.parameters.channels=Array.from(new Set(this.parameters.channels)))}operation(){return le.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${B(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class Tt extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${H(t)}`}}class _t extends ue{constructor(e){var t,s,n,r,i,a;super(),this.parameters=e,null!==(t=(r=this.parameters).queryParameters)&&void 0!==t||(r.queryParameters={}),null!==(s=(i=this.parameters).includeUUIDs)&&void 0!==s||(i.includeUUIDs=true),null!==(n=(a=this.parameters).includeState)&&void 0!==n||(a.includeState=false)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?le.PNGlobalHereNowOperation:le.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t,s;const n=this.deserializeResponse(e),r="occupancy"in n?1:n.payload.total_channels,i="occupancy"in n?n.occupancy:n.payload.total_occupancy,a={};let o={};if("occupancy"in n){const e=this.parameters.channels[0];o[e]={uuids:null!==(t=n.uuids)&&void 0!==t?t:[],occupancy:i}}else o=null!==(s=n.payload.channels)&&void 0!==s?s:{};return Object.keys(o).forEach((e=>{const t=o[e];a[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy}})),{totalChannels:r,totalOccupancy:i,channels:a}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;let n=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||s&&s.length>0)&&(n+=`/channel/${B(null!=t?t:[],",")}`),n}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:s,queryParameters:n}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign({},t?{}:{disable_uuids:"1"}),null!=s&&s?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),n)}}class It extends ue{constructor(e){super({method:re.DELETE}),this.parameters=e}operation(){return le.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${H(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class Mt extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:s,channelTimetokens:n}=this.parameters;return e?t?s&&n?"`timetoken` and `channelTimetokens` are incompatible together":s||n?n&&n.length>1&&n.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${B(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class At extends ue{constructor(e){var t,s,n;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(s=e.includeMeta)&&void 0!==s||(e.includeMeta=false),null!==(n=e.logVerbosity)&&void 0!==n||(e.logVerbosity=false)}operation(){return le.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),s=t[0],n=t[1],r=t[2];return Array.isArray(s)?{messages:s.map((e=>{const t=this.processPayload(e.message),s={entry:t.payload,timetoken:e.timetoken};return t.error&&(s.error=t.error),e.meta&&(s.meta=e.meta),s})),startTimeToken:n,endTimeToken:r}:{messages:[],startTimeToken:n,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${H(t)}`}get queryParameters(){const{start:e,end:t,reverse:s,count:n,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:n,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),null!=s?{reverse:s.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:s}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let n,r;try{const s=t.decrypt(e);n=s instanceof ArrayBuffer?JSON.parse(At.decoder.decode(s)):s}catch(t){s&&console.log("decryption error",t.message),n=e,r=`Error while decrypting message content: ${t.message}`}return{payload:n,error:r}}}var Ut;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Ut||(Ut={}));class $t extends ue{constructor(e){var t,s,n,r,i;super(),this.parameters=e;const a=null!==(t=e.includeMessageActions)&&void 0!==t&&t,o=e.channels.length>1||a?25:100;e.count?e.count=Math.min(e.count,o):e.count=o,e.includeUuid?e.includeUUID=e.includeUuid:null!==(s=e.includeUUID)&&void 0!==s||(e.includeUUID=true),null!==(n=e.stringifiedTimeToken)&&void 0!==n||(e.stringifiedTimeToken=false),null!==(r=e.includeMessageType)&&void 0!==r||(e.includeMessageType=true),null!==(i=e.logVerbosity)&&void 0!==i||(e.logVerbosity=false)}operation(){return le.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return e?t?void 0!==s&&s&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t;const s=this.deserializeResponse(e),n=null!==(t=s.channels)&&void 0!==t?t:{},r={};return Object.keys(n).forEach((e=>{r[e]=n[e].map((t=>{null===t.message_type&&(t.message_type=Ut.Message);const s=this.processPayload(e,t),n=Object.assign(Object.assign({channel:e,timetoken:t.timetoken,message:s.payload,messageType:t.message_type},t.custom_message_type?{customMessageType:t.custom_message_type}:{}),{uuid:t.uuid});if(t.actions){const e=n;e.actions=t.actions,e.data=t.actions}return t.meta&&(n.meta=t.meta),s.error&&(n.error=s.error),n}))})),s.more?{channels:r,more:s.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return`/v3/${s?"history-with-actions":"history"}/sub-key/${e}/channel/${B(t)}`}get queryParameters(){const{start:e,end:t,count:s,includeCustomMessageType:n,includeMessageType:r,includeMeta:i,includeUUID:a,stringifiedTimeToken:o}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:s},e?{start:e}:{}),t?{end:t}:{}),o?{string_message_token:"true"}:{}),void 0!==i&&i?{include_meta:"true"}:{}),a?{include_uuid:"true"}:{}),null!=n?{include_custom_message_type:n?"true":"false"}:{}),r?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:s,logVerbosity:n}=this.parameters;if(!s||"string"!=typeof t.message)return{payload:t.message};let r,i;try{const e=s.decrypt(t.message);r=e instanceof ArrayBuffer?JSON.parse($t.decoder.decode(e)):e}catch(e){n&&console.log("decryption error",e.message),r=t.message,i=`Error while decrypting message content: ${e.message}`}if(!i&&r&&t.message_type==Ut.Files&&"object"==typeof r&&this.isFileMessage(r)){const t=r;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return void 0!==e.file}}class Rt extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);let s=null,n=null;return t.data.length>0&&(s=t.data[0].actionTimetoken,n=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:s,end:n}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${H(t)}`}get queryParameters(){const{limit:e,start:t,end:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),s?{end:s}:{}),e?{limit:e}:{})}}class Ft extends ue{constructor(e){super({method:re.POST}),this.parameters=e}operation(){return le.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:s,messageTimetoken:n}=this.parameters;return e?s?n?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${H(t)}/message/${s}`}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"})}get body(){return JSON.stringify(this.parameters.action)}}class Dt extends ue{constructor(e){super({method:re.DELETE}),this.parameters=e}operation(){return le.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s,actionTimetoken:n}=this.parameters;return e?t?s?n?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:s,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${H(t)}/message/${n}/action/${s}`}}class xt extends ue{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).storeInHistory)&&void 0!==t||(s.storeInHistory=true)}operation(){return le.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:s,subscribeKey:n},fileId:r,fileName:i}=this.parameters,a=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${s}/${n}/0/${H(t)}/0/${H(this.prepareMessagePayload(a))}`}get queryParameters(){const{customMessageType:e,storeInHistory:t,ttl:s,meta:n}=this.parameters;return Object.assign(Object.assign(Object.assign({store:t?"1":"0"},e?{custom_message_type:e}:{}),s?{ttl:s}:{}),n&&"object"==typeof n?{meta:JSON.stringify(n)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Gt extends ue{constructor(e){super({method:re.LOCAL}),this.parameters=e}operation(){return le.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:s,keySet:{subscribeKey:n}}=this.parameters;return`/v1/files/${n}/channels/${H(e)}/files/${t}/${s}`}}class qt extends ue{constructor(e){super({method:re.DELETE}),this.parameters=e}operation(){return le.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},id:t,channel:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${H(s)}/files/${t}/${n}`}}class Kt extends ue{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).limit)&&void 0!==t||(s.limit=100)}operation(){return le.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${H(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Lt extends ue{constructor(e){super({method:re.POST}),this.parameters=e}operation(){return le.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${H(t)}/generate-upload-url`}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"})}get body(){return JSON.stringify({name:this.parameters.name})}}class Ht extends ue{constructor(e){super({method:re.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return le.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:s,uploadUrl:n}=this.parameters;return e?t?s?n?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Ht.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class Bt{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return i(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((s=>(e=s.name,t=s.id,this.uploadFile(s)))).then((e=>{if(204!==e.status)throw new d("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:h.PNUnknownCategory,operation:le.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof d)throw e;const t=e instanceof _?e:_.create(e);throw new d("File upload error.",t.toStatus(le.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return i(this,void 0,void 0,(function*(){const e=new Lt(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:s,crypto:n,cryptography:r}=this.parameters,{id:i,name:a,url:o,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&n?this.file=yield n.encryptFile(this.file,s):t&&r&&(this.file=yield r.encryptFile(t,this.file,s))),this.parameters.sendRequest(new Ht({fileId:i,fileName:a,file:this.file,uploadUrl:o,formFields:c}))}))}publishFileMessage(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i;let a,o={timetoken:"0"},c=this.parameters.fileUploadPublishRetryLimit,u=!1;do{try{o=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),u=!0}catch(e){e instanceof d&&(a=e),c-=1}}while(!u&&c>0);if(u)return{status:200,timetoken:o.timetoken,id:e,name:t};throw new d("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(n=null===(s=a.status)||void 0===s?void 0:s.category)&&void 0!==n?n:h.PNUnknownCategory,statusCode:null!==(i=null===(r=a.status)||void 0===r?void 0:r.statusCode)&&void 0!==i?i:0,channel:this.parameters.channel,id:e,name:t})}))}}var Wt;!function(e){e[e.Channel=0]="Channel",e[e.ChannelGroup=1]="ChannelGroup"}(Wt||(Wt={}));class zt{constructor({channels:e,channelGroups:t}){this.isEmpty=!0,this._channelGroups=new Set((null!=t?t:[]).filter((e=>e.length>0))),this._channels=new Set((null!=e?e:[]).filter((e=>e.length>0))),this.isEmpty=0===this._channels.size&&0===this._channelGroups.size}get channels(){return this.isEmpty?[]:Array.from(this._channels)}get channelGroups(){return this.isEmpty?[]:Array.from(this._channelGroups)}contains(e){return!this.isEmpty&&(this._channels.has(e)||this._channelGroups.has(e))}with(e){return new zt({channels:[...this._channels,...e._channels],channelGroups:[...this._channelGroups,...e._channelGroups]})}without(e){return new zt({channels:[...this._channels].filter((t=>!e._channels.has(t))),channelGroups:[...this._channelGroups].filter((t=>!e._channelGroups.has(t)))})}add(e){return e._channelGroups.size>0&&(this._channelGroups=new Set([...this._channelGroups,...e._channelGroups])),e._channels.size>0&&(this._channels=new Set([...this._channels,...e._channels])),this.isEmpty=0===this._channels.size&&0===this._channelGroups.size,this}remove(e){return e._channelGroups.size>0&&(this._channelGroups=new Set([...this._channelGroups].filter((t=>!e._channelGroups.has(t))))),e._channels.size>0&&(this._channels=new Set([...this._channels].filter((t=>!e._channels.has(t))))),this}removeAll(){return this._channels.clear(),this._channelGroups.clear(),this.isEmpty=!0,this}toString(){return`SubscriptionInput { channels: [${this.channels.join(", ")}], channelGroups: [${this.channelGroups.join(", ")}], is empty: ${this.isEmpty?"true":"false"}} }`}}class Vt{constructor(e,t,s,n){this._isSubscribed=!1,this.clones={},this.parents=[],this._id=K.createUUID(),this.referenceTimetoken=n,this.subscriptionInput=t,this.options=s,this.client=e}get id(){return this._id}get isLastClone(){return 1===Object.keys(this.clones).length}get isSubscribed(){return!!this._isSubscribed||this.parents.length>0&&this.parents.some((e=>e.isSubscribed))}set isSubscribed(e){this.isSubscribed!==e&&(this._isSubscribed=e)}addParentState(e){this.parents.includes(e)||this.parents.push(e)}removeParentState(e){const t=this.parents.indexOf(e);-1!==t&&this.parents.splice(t,1)}storeClone(e,t){this.clones[e]||(this.clones[e]=t)}}class Jt{constructor(e){this.id=K.createUUID(),this.eventDispatcher=new ge,this._state=e}get state(){return this._state}get channels(){return this.state.subscriptionInput.channels.slice(0)}get channelGroups(){return this.state.subscriptionInput.channelGroups.slice(0)}set onMessage(e){this.eventDispatcher.onMessage=e}set onPresence(e){this.eventDispatcher.onPresence=e}set onSignal(e){this.eventDispatcher.onSignal=e}set onObjects(e){this.eventDispatcher.onObjects=e}set onMessageAction(e){this.eventDispatcher.onMessageAction=e}set onFile(e){this.eventDispatcher.onFile=e}addListener(e){this.eventDispatcher.addListener(e)}removeListener(e){this.eventDispatcher.removeListener(e)}removeAllListeners(){this.eventDispatcher.removeAllListeners()}handleEvent(e,t){var s;if((!this.state.cursor||e>this.state.cursor)&&(this.state.cursor=e),this.state.referenceTimetoken&&t.data.timetoken({messageType:"text",message:`Event timetoken (${t.data.timetoken}) is older than reference timetoken (${this.state.referenceTimetoken}) for ${this.id} subscription object. Ignoring event.`})));if((null===(s=this.state.options)||void 0===s?void 0:s.filter)&&!this.state.options.filter(t))return void this.state.client.logger.trace(this.constructor.name,`Event filtered out by filter function for ${this.id} subscription object. Ignoring event.`);const n=Object.values(this.state.clones);n.length>0&&this.state.client.logger.trace(this.constructor.name,`Notify ${this.id} subscription object clones (count: ${n.length}) about received event.`),n.forEach((e=>e.eventDispatcher.handleEvent(t)))}dispose(){const e=Object.keys(this.state.clones);e.length>1?(this.state.client.logger.debug(this.constructor.name,`Remove subscription object clone on dispose: ${this.id}`),delete this.state.clones[this.id]):1===e.length&&this.state.clones[this.id]&&(this.state.client.logger.debug(this.constructor.name,`Unsubscribe subscription object on dispose: ${this.id}`),this.unsubscribe())}invalidate(e=!1){this.state._isSubscribed=!1,e&&(delete this.state.clones[this.id],0===Object.keys(this.state.clones).length&&(this.state.client.logger.trace(this.constructor.name,"Last clone removed. Reset shared subscription state."),this.state.subscriptionInput.removeAll(),this.state.parents=[]))}subscribe(e){this.state.isSubscribed?this.state.client.logger.trace(this.constructor.name,"Already subscribed. Ignoring subscribe request."):(this.state.client.logger.debug(this.constructor.name,(()=>e?{messageType:"object",message:e,details:"Subscribe with parameters:"}:{messageType:"text",message:"Subscribe"})),this.state.isSubscribed=!0,this.updateSubscription({subscribing:!0,timetoken:null==e?void 0:e.timetoken}))}unsubscribe(){if(!this.state._isSubscribed||this.state.isSubscribed){if(!this.state._isSubscribed&&this.state.parents.length>0&&this.state.isSubscribed)return void this.state.client.logger.warn(this.constructor.name,(()=>({messageType:"object",details:"Subscription is subscribed as part of a subscription set. Remove from active sets to unsubscribe:",message:this.state.parents.filter((e=>e.isSubscribed))})));if(!this.state._isSubscribed)return void this.state.client.logger.trace(this.constructor.name,"Not subscribed. Ignoring unsubscribe request.")}this.state.client.logger.debug(this.constructor.name,"Unsubscribe"),this.state.isSubscribed=!0,delete this.state.cursor,this.updateSubscription({subscribing:!1})}updateSubscription(e){var t,s;(null==e?void 0:e.timetoken)&&((null===(t=this.state.cursor)||void 0===t?void 0:t.timetoken)&&"0"!==(null===(s=this.state.cursor)||void 0===s?void 0:s.timetoken)?"0"!==e.timetoken&&e.timetoken>this.state.cursor.timetoken&&(this.state.cursor.timetoken=e.timetoken):this.state.cursor={timetoken:e.timetoken});const n=e.subscriptions&&e.subscriptions.length>0?e.subscriptions:void 0;e.subscribing?this.register(Object.assign(Object.assign({},e.timetoken?{cursor:this.state.cursor}:{}),n?{subscriptions:n}:{})):this.unregister(n)}}class Xt extends Vt{constructor(e){const t=new zt({});e.subscriptions.forEach((e=>t.add(e.state.subscriptionInput))),super(e.client,t,e.options,e.client.subscriptionTimetoken),this.subscriptions=e.subscriptions}addSubscription(e){this.subscriptions.includes(e)||(e.state.addParentState(this),this.subscriptions.push(e),this.subscriptionInput.add(e.state.subscriptionInput))}removeSubscription(e,t){const s=this.subscriptions.indexOf(e);-1!==s&&(this.subscriptions.splice(s,1),t||e.state.removeParentState(this),this.subscriptionInput.remove(e.state.subscriptionInput))}removeAllSubscriptions(){this.subscriptions.forEach((e=>e.state.removeParentState(this))),this.subscriptions.splice(0,this.subscriptions.length),this.subscriptionInput.removeAll()}}class Qt extends Jt{constructor(e){let t;if("client"in e){let s=[];!e.subscriptions&&e.entities?e.entities.forEach((t=>s.push(t.subscription(e.options)))):e.subscriptions&&(s=e.subscriptions),t=new Xt({client:e.client,subscriptions:s,options:e.options}),s.forEach((e=>e.state.addParentState(t))),t.client.logger.debug("SubscriptionSet",(()=>({messageType:"object",details:"Create subscription set with parameters:",message:Object.assign({subscriptions:t.subscriptions},e.options?e.options:{})})))}else t=e.state,t.client.logger.debug("SubscriptionSet","Create subscription set clone");super(t),this.state.storeClone(this.id,this),t.subscriptions.forEach((e=>e.addParentSet(this)))}get state(){return super.state}get subscriptions(){return this.state.subscriptions.slice(0)}handleEvent(e,t){var s;this.state.subscriptionInput.contains(null!==(s=t.data.subscription)&&void 0!==s?s:t.data.channel)&&(this.state._isSubscribed?(super.handleEvent(e,t),this.state.subscriptions.length>0&&this.state.client.logger.trace(this.constructor.name,`Notify ${this.id} subscription set subscriptions (count: ${this.state.subscriptions.length}) about received event.`),this.state.subscriptions.forEach((s=>s.handleEvent(e,t)))):this.state.client.logger.trace(this.constructor.name,`Subscription set ${this.id} is not subscribed. Ignoring event.`))}subscriptionInput(e=!1){let t=this.state.subscriptionInput;return this.state.subscriptions.forEach((s=>{e&&s.state.entity.subscriptionsCount>0&&(t=t.without(s.state.subscriptionInput))})),t}cloneEmpty(){return new Qt({state:this.state})}dispose(){const e=this.state.isLastClone;this.state.subscriptions.forEach((t=>{t.removeParentSet(this),e&&t.state.removeParentState(this.state)})),super.dispose()}invalidate(e=!1){(e?this.state.subscriptions.slice(0):this.state.subscriptions).forEach((t=>{e&&(t.state.entity.decreaseSubscriptionCount(this.state.id),t.removeParentSet(this)),t.invalidate(e)})),e&&this.state.removeAllSubscriptions(),super.invalidate()}addSubscription(e){this.addSubscriptions([e])}addSubscriptions(e){const t=[],s=[];this.state.client.logger.debug(this.constructor.name,(()=>{const t=[],s=[];return e.forEach((e=>{this.state.subscriptions.includes(e)?t.push(e):s.push(e)})),{messageType:"object",details:`Add subscriptions to ${this.id} (subscriptions count: ${this.state.subscriptions.length+s.length}):`,message:{addedSubscriptions:s,ignoredSubscriptions:t}}})),e.filter((e=>!this.state.subscriptions.includes(e))).forEach((e=>{e.state.isSubscribed?s.push(e):t.push(e),e.addParentSet(this),this.state.addSubscription(e)})),0===s.length&&0===t.length||!this.state.isSubscribed||(s.forEach((({state:e})=>e.entity.increaseSubscriptionCount(this.state.id))),t.length>0&&this.updateSubscription({subscribing:!0,subscriptions:t}))}removeSubscription(e){this.removeSubscriptions([e])}removeSubscriptions(e){const t=[];this.state.client.logger.debug(this.constructor.name,(()=>{const t=[],s=[];return e.forEach((e=>{this.state.subscriptions.includes(e)?s.push(e):t.push(e)})),{messageType:"object",details:`Remove subscriptions from ${this.id} (subscriptions count: ${this.state.subscriptions.length}):`,message:{removedSubscriptions:s,ignoredSubscriptions:t}}})),e.filter((e=>this.state.subscriptions.includes(e))).forEach((e=>{e.state.isSubscribed&&t.push(e),e.removeParentSet(this),this.state.removeSubscription(e,e.parentSetsCount>1)})),0!==t.length&&this.state.isSubscribed&&this.updateSubscription({subscribing:!1,subscriptions:t})}addSubscriptionSet(e){this.addSubscriptions(e.subscriptions)}removeSubscriptionSet(e){this.removeSubscriptions(e.subscriptions)}register(e){var t;const s=null!==(t=e.subscriptions)&&void 0!==t?t:this.state.subscriptions;s.forEach((({state:e})=>e.entity.increaseSubscriptionCount(this.state.id))),this.state.client.logger.trace(this.constructor.name,(()=>({messageType:"text",message:`Register subscription for real-time events: ${this}`}))),this.state.client.registerEventHandleCapable(this,e.cursor,s)}unregister(e){const t=null!=e?e:this.state.subscriptions;t.forEach((({state:e})=>e.entity.decreaseSubscriptionCount(this.state.id))),this.state.client.logger.trace(this.constructor.name,(()=>({messageType:"text",message:`Unregister subscription from real-time events: ${this}`}))),this.state.client.unregisterEventHandleCapable(this,t)}toString(){const e=this.state;return`${this.constructor.name} { id: ${this.id}, stateId: ${e.id}, clonesCount: ${Object.keys(this.state.clones).length}, isSubscribed: ${e.isSubscribed}, subscriptions: [${e.subscriptions.map((e=>e.toString())).join(", ")}] }`}}class Yt extends Vt{constructor(e){var t,s;const n=e.entity.subscriptionNames(null!==(s=null===(t=e.options)||void 0===t?void 0:t.receivePresenceEvents)&&void 0!==s&&s),r=new zt({[e.entity.subscriptionType==Wt.Channel?"channels":"channelGroups"]:n});super(e.client,r,e.options,e.client.subscriptionTimetoken),this.entity=e.entity}}class Zt extends Jt{constructor(e){"client"in e?e.client.logger.debug("Subscription",(()=>({messageType:"object",details:"Create subscription with parameters:",message:Object.assign({entity:e.entity},e.options?e.options:{})}))):e.state.client.logger.debug("Subscription","Create subscription clone"),super("state"in e?e.state:new Yt(e)),this.parents=[],this.handledUpdates=[],this.state.storeClone(this.id,this)}get state(){return super.state}get parentSetsCount(){return this.parents.length}handleEvent(e,t){var s;if(this.state.isSubscribed){if(this.parentSetsCount>0){const e=Y(t.data);if(this.handledUpdates.includes(e))return void this.state.client.logger.trace(this.constructor.name,`Message (${e}) already handled. Ignoring.`);this.handledUpdates.push(e),this.handledUpdates.length>10&&this.handledUpdates.shift()}this.state.subscriptionInput.contains(null!==(s=t.data.subscription)&&void 0!==s?s:t.data.channel)&&super.handleEvent(e,t)}}subscriptionInput(e=!1){return e&&this.state.entity.subscriptionsCount>0?new zt({}):this.state.subscriptionInput}cloneEmpty(){return new Zt({state:this.state})}dispose(){this.parentSetsCount>0?this.state.client.logger.debug(this.constructor.name,(()=>({messageType:"text",message:`'${this.state.entity.subscriptionNames()}' subscription still in use. Ignore dispose request.`}))):(this.handledUpdates.splice(0,this.handledUpdates.length),super.dispose())}invalidate(e=!1){e&&this.state.entity.decreaseSubscriptionCount(this.state.id),this.handledUpdates.splice(0,this.handledUpdates.length),super.invalidate(e)}addParentSet(e){this.parents.includes(e)||(this.parents.push(e),this.state.client.logger.trace(this.constructor.name,`Add parent subscription set for ${this.id}: ${e.id}. Parent subscription set count: ${this.parentSetsCount}`))}removeParentSet(e){const t=this.parents.indexOf(e);-1!==t&&(this.parents.splice(t,1),this.state.client.logger.trace(this.constructor.name,`Remove parent subscription set from ${this.id}: ${e.id}. Parent subscription set count: ${this.parentSetsCount}`)),0===this.parentSetsCount&&this.handledUpdates.splice(0,this.handledUpdates.length)}addSubscription(e){this.state.client.logger.debug(this.constructor.name,(()=>({messageType:"text",message:`Create set with subscription: ${e}`})));const t=new Qt({client:this.state.client,subscriptions:[this,e],options:this.state.options});return this.state.isSubscribed||e.state.isSubscribed?(this.state.client.logger.trace(this.constructor.name,"Subscribe resulting set because the receiver is already subscribed."),t.subscribe(),t):t}register(e){this.state.entity.increaseSubscriptionCount(this.state.id),this.state.client.logger.trace(this.constructor.name,(()=>({messageType:"text",message:`Register subscription for real-time events: ${this}`}))),this.state.client.registerEventHandleCapable(this,e.cursor)}unregister(e){this.state.entity.decreaseSubscriptionCount(this.state.id),this.state.client.logger.trace(this.constructor.name,(()=>({messageType:"text",message:`Unregister subscription from real-time events: ${this}`}))),this.handledUpdates.splice(0,this.handledUpdates.length),this.state.client.unregisterEventHandleCapable(this)}toString(){const e=this.state;return`${this.constructor.name} { id: ${this.id}, stateId: ${e.id}, entity: ${e.entity.subscriptionNames(!1).pop()}, clonesCount: ${Object.keys(e.clones).length}, isSubscribed: ${e.isSubscribed}, parentSetsCount: ${this.parentSetsCount}, cursor: ${e.cursor?e.cursor.timetoken:"not set"}, referenceTimetoken: ${e.referenceTimetoken?e.referenceTimetoken:"not set"} }`}}class es{constructor(e,t){this.subscriptionStateIds=[],this.client=t,this._nameOrId=e}get subscriptionType(){return Wt.Channel}subscriptionNames(e){return[this._nameOrId,...e&&!this._nameOrId.endsWith("-pnpres")?[`${this._nameOrId}-pnpres`]:[]]}subscription(e){return new Zt({client:this.client,entity:this,options:e})}get subscriptionsCount(){return this.subscriptionStateIds.length}increaseSubscriptionCount(e){this.subscriptionStateIds.includes(e)||this.subscriptionStateIds.push(e)}decreaseSubscriptionCount(e){{const t=this.subscriptionStateIds.indexOf(e);t>=0&&this.subscriptionStateIds.splice(t,1)}}toString(){return`${this.constructor.name} { nameOrId: ${this._nameOrId}, subscriptionsCount: ${this.subscriptionsCount} }`}}class ts extends es{get id(){return this._nameOrId}subscriptionNames(e){return[this.id]}}class ss extends es{get name(){return this._nameOrId}get subscriptionType(){return Wt.ChannelGroup}}class ns extends es{get id(){return this._nameOrId}subscriptionNames(e){return[this.id]}}class rs extends es{get name(){return this._nameOrId}}class is extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${H(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class as extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${H(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class os extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${H(t)}`}}class cs extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${H(t)}/remove`}}class us extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{groups:this.deserializeResponse(e).payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class ls{constructor(e,t,s){this.sendRequest=s,this.logger=e,this.keySet=t}listChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"List channel group channels with parameters:"})));const s=new os(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=e=>{e&&this.logger.info("PubNub",`List channel group channels success. Received ${e.channels.length} channels.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}listGroups(e){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub","List all channel groups.");const t=new us({keySet:this.keySet}),s=e=>{e&&this.logger.info("PubNub",`List all channel groups success. Received ${e.groups.length} groups.`)};return e?this.sendRequest(t,((t,n)=>{s(n),e(t,n)})):this.sendRequest(t).then((e=>(s(e),e)))}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add channels to the channel group with parameters:"})));const s=new as(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.info("PubNub","Add channels to the channel group success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove channels from the channel group with parameters:"})));const s=new is(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.info("PubNub","Remove channels from the channel group success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}deleteGroup(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove a channel group with parameters:"})));const s=new cs(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.info("PubNub",`Remove a channel group success. Removed '${e.channelGroup}' channel group.'`)};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}}class hs extends ue{constructor(e){var t,s;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(s=this.parameters).environment)&&void 0!==t||(s.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;return e?s?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?n?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: gcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}get path(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;let r="apns2"===n?`/v2/push/sub-key/${e}/devices-apns2/${s}`:`/v1/push/sub-key/${e}/devices/${s}`;return"remove-device"===t&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let s=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(s[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;s=Object.assign(Object.assign({},s),{environment:e,topic:t})}return s}}class ds extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return le.PNRemovePushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class ps extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return le.PNPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e)}}))}}class gs extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return le.PNAddPushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class bs extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return le.PNRemoveAllPushNotificationsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class ms{constructor(e,t,s){this.sendRequest=s,this.logger=e,this.keySet=t}listChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"List push-enabled channels with parameters:"})));const s=new ps(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`List push-enabled channels success. Received ${e.channels.length} channels.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add push-enabled channels with parameters:"})));const s=new gs(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Add push-enabled channels success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove push-enabled channels with parameters:"})));const s=new ds(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Remove push-enabled channels success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}deleteDevice(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove push notifications for device with parameters:"})));const s=new bs(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Remove push notifications for device success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}}class ys extends ue{constructor(e){var t,s,n,r,i,a;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(i=e.include).customFields)&&void 0!==s||(i.customFields=false),null!==(n=(a=e.include).totalCount)&&void 0!==n||(a.totalCount=false),null!==(r=e.limit)&&void 0!==r||(e.limit=100)}operation(){return le.PNGetAllChannelMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class fs extends ue{constructor(e){super({method:re.DELETE}),this.parameters=e}operation(){return le.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${H(t)}`}}class vs extends ue{constructor(e){var t,s,n,r,i,a,o,c,u,l,h,d,p,g,b,m,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(b=e.include).channelFields)&&void 0!==a||(b.channelFields=false),null!==(o=(m=e.include).customChannelFields)&&void 0!==o||(m.customChannelFields=false),null!==(c=(y=e.include).channelStatusField)&&void 0!==c||(y.channelStatusField=false),null!==(u=(f=e.include).channelTypeField)&&void 0!==u||(f.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return le.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${H(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class Ss extends ue{constructor(e){var t,s,n,r,i,a,o,c,u,l,h,d,p,g,b,m,y,f;super({method:re.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(b=e.include).channelFields)&&void 0!==a||(b.channelFields=false),null!==(o=(m=e.include).customChannelFields)&&void 0!==o||(m.customChannelFields=false),null!==(c=(y=e.include).channelStatusField)&&void 0!==c||(y.channelStatusField=false),null!==(u=(f=e.include).channelTypeField)&&void 0!==u||(f.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return le.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${H(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["channel.status","channel.type","status"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class ws extends ue{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(r=e.include).customFields)&&void 0!==s||(r.customFields=false),null!==(n=e.limit)&&void 0!==n||(e.limit=100)}operation(){return le.PNGetAllUUIDMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class Os extends ue{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return le.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${H(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class ks extends ue{constructor(e){var t,s,n;super({method:re.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return le.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${H(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Cs extends ue{constructor(e){super({method:re.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return le.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${H(t)}`}}class Ps extends ue{constructor(e){var t,s,n,r,i,a,o,c,u,l,h,d,p,g,b,m,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(b=e.include).UUIDFields)&&void 0!==a||(b.UUIDFields=false),null!==(o=(m=e.include).customUUIDFields)&&void 0!==o||(m.customUUIDFields=false),null!==(c=(y=e.include).UUIDStatusField)&&void 0!==c||(y.UUIDStatusField=false),null!==(u=(f=e.include).UUIDTypeField)&&void 0!==u||(f.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return le.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${H(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class js extends ue{constructor(e){var t,s,n,r,i,a,o,c,u,l,h,d,p,g,b,m,y,f;super({method:re.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(b=e.include).UUIDFields)&&void 0!==a||(b.UUIDFields=false),null!==(o=(m=e.include).customUUIDFields)&&void 0!==o||(m.customUUIDFields=false),null!==(c=(y=e.include).UUIDStatusField)&&void 0!==c||(y.UUIDStatusField=false),null!==(u=(f=e.include).UUIDTypeField)&&void 0!==u||(f.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return le.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${H(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["uuid.status","uuid.type","type"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class Es extends ue{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return le.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${H(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class Ns extends ue{constructor(e){var t,s,n;super({method:re.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return le.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json"})}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${H(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Ts{constructor(e,t){this.keySet=e.keySet,this.configuration=e,this.sendRequest=t}get logger(){return this.configuration.logger()}getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{},details:"Get all UUID metadata objects with parameters:"}))),this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new ws(Object.assign(Object.assign({},s),{keySet:this.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Get all UUID metadata success. Received ${e.totalCount} UUID metadata objects.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}))}getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{uuid:this.configuration.userId},details:`Get ${e&&"function"!=typeof e?"":" current"} UUID metadata object with parameters:`}))),this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Es(Object.assign(Object.assign({},n),{keySet:this.keySet})),i=e=>{e&&this.logger.debug("PubNub",`Get UUID metadata object success. Received '${n.uuid}' UUID metadata object.`)};return t?this.sendRequest(r,((e,s)=>{i(s),t(e,s)})):this.sendRequest(r).then((e=>(i(e),e)))}))}setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set UUID metadata object with parameters:"}))),this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new Ns(Object.assign(Object.assign({},e),{keySet:this.keySet})),r=t=>{t&&this.logger.debug("PubNub",`Set UUID metadata object success. Updated '${e.uuid}' UUID metadata object.'`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}))}removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{uuid:this.configuration.userId},details:`Remove${e&&"function"!=typeof e?"":" current"} UUID metadata object with parameters:`}))),this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Cs(Object.assign(Object.assign({},n),{keySet:this.keySet})),i=e=>{e&&this.logger.debug("PubNub",`Remove UUID metadata object success. Removed '${n.uuid}' UUID metadata object.`)};return t?this.sendRequest(r,((e,s)=>{i(s),t(e,s)})):this.sendRequest(r).then((e=>(i(e),e)))}))}getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{},details:"Get all Channel metadata objects with parameters:"}))),this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new ys(Object.assign(Object.assign({},s),{keySet:this.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Get all Channel metadata objects success. Received ${e.totalCount} Channel metadata objects.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}))}getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Channel metadata object with parameters:"}))),this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new Os(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Get Channel metadata object success. Received '${e.channel}' Channel metadata object.'`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set Channel metadata object with parameters:"}))),this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new ks(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Set Channel metadata object success. Updated '${e.channel}' Channel metadata object.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Channel metadata object with parameters:"}))),this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new fs(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Remove Channel metadata object success. Removed '${e.channel}' Channel metadata object.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}getChannelMembers(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get channel members with parameters:"})));const s=new Ps(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Get channel members success. Received ${e.totalCount} channel members.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}setChannelMembers(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set channel members with parameters:"})));const s=new js(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Set channel members success. There are ${e.totalCount} channel members now.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}removeChannelMembers(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove channel members with parameters:"})));const s=new js(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Remove channel members success. There are ${e.totalCount} channel members now.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}getMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},n),details:"Get memberships with parameters:"})));const r=new vs(Object.assign(Object.assign({},n),{keySet:this.keySet})),i=e=>{e&&this.logger.debug("PubNub",`Get memberships success. Received ${e.totalCount} memberships.`)};return t?this.sendRequest(r,((e,s)=>{i(s),t(e,s)})):this.sendRequest(r).then((e=>(i(e),e)))}))}setMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set memberships with parameters:"})));const n=new Ss(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Set memberships success. There are ${e.totalCount} memberships now.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove memberships with parameters:"})));const n=new Ss(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Remove memberships success. There are ${e.totalCount} memberships now.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n;if(this.logger.warn("PubNub","'fetchMemberships' is deprecated. Use 'pubnub.objects.getChannelMembers' or 'pubnub.objects.getMemberships' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch memberships with parameters:"}))),"spaceId"in e){const n=e,r={channel:null!==(s=n.spaceId)&&void 0!==s?s:n.channel,filter:n.filter,limit:n.limit,page:n.page,include:Object.assign({},n.include),sort:n.sort?Object.fromEntries(Object.entries(n.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},i=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(r,((e,s)=>{t(e,s?i(s):s)})):this.getChannelMembers(r).then(i)}const r=e,i={uuid:null!==(n=r.userId)&&void 0!==n?n:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},a=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(i,((e,s)=>{t(e,s?a(s):s)})):this.getMemberships(i).then(a)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i,a,o;if(this.logger.warn("PubNub","'addMemberships' is deprecated. Use 'pubnub.objects.setChannelMembers' or 'pubnub.objects.setMemberships' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add memberships with parameters:"}))),"spaceId"in e){const i=e,a={channel:null!==(s=i.spaceId)&&void 0!==s?s:i.channel,uuids:null!==(r=null===(n=i.users)||void 0===n?void 0:n.map((e=>"string"==typeof e?e:{id:e.userId,custom:e.custom})))&&void 0!==r?r:i.uuids,limit:0};return t?this.setChannelMembers(a,t):this.setChannelMembers(a)}const c=e,u={uuid:null!==(i=c.userId)&&void 0!==i?i:c.uuid,channels:null!==(o=null===(a=c.spaces)||void 0===a?void 0:a.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==o?o:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class _s extends ue{constructor(){super()}operation(){return le.PNTimeOperation}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[0]}}))}get path(){return"/time/0"}}class Is extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:s,cryptography:n,name:r,PubNubFile:i}=this.parameters,a=e.headers["content-type"];let o,c=e.body;return i.supportsEncryptFile&&(t||s)&&(t&&n?c=yield n.decrypt(t,c):!t&&s&&(o=yield s.decryptFile(i.create({data:c,name:r,mimeType:a}),i))),o||i.create({data:c,name:r,mimeType:a})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${H(t)}/files/${s}/${n}`}}class Ms{static notificationPayload(e,t){return new we(e,t)}static generateUUID(){return K.createUUID()}constructor(e){if(this.eventHandleCapable={},this.entities={},this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this.logger.debug("PubNub",(()=>({messageType:"object",message:e.configuration,details:"Create with configuration:",ignoredKeys:(e,t)=>"function"==typeof t[e]||e.startsWith("_")}))),this._objects=new Ts(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new ls(this._configuration.logger(),this._configuration.keySet,this.sendRequest.bind(this)),this._push=new ms(this._configuration.logger(),this._configuration.keySet,this.sendRequest.bind(this)),this.eventDispatcher=new ge,this._configuration.enableEventEngine){this.logger.debug("PubNub","Using new subscription loop management.");let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new Ye({heartbeat:(e,t)=>(this.logger.trace("PresenceEventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Heartbeat with parameters:"}))),this.heartbeat(e,t)),leave:e=>{this.logger.trace("PresenceEventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave with parameters:"}))),this.makeUnsubscribe(e,(()=>{}))},heartbeatDelay:()=>new Promise(((t,s)=>{e=this._configuration.getHeartbeatInterval(),e?setTimeout(t,1e3*e):s(new d("Heartbeat interval has been reset."))})),emitStatus:e=>this.emitStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new St({handshake:e=>(this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Handshake with parameters:",ignoredKeys:["abortSignal","crypto","timeout","keySet","getFileUrl"]}))),this.subscribeHandshake(e)),receiveMessages:e=>(this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Receive messages with parameters:",ignoredKeys:["abortSignal","crypto","timeout","keySet","getFileUrl"]}))),this.subscribeReceiveMessages(e)),delay:e=>new Promise((t=>setTimeout(t,e))),join:e=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Join with parameters:"}))),this.join(e)},leave:e=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave with parameters:"}))),this.leave(e)},leaveAll:e=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave all with parameters:"}))),this.leaveAll(e)},presenceReconnect:e=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Reconnect with parameters:"}))),this.presenceReconnect(e)},presenceDisconnect:e=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Disconnect with parameters:"}))),this.presenceDisconnect(e)},presenceState:this.presenceState,config:this._configuration,emitMessages:(e,t)=>{try{this.logger.debug("EventEngine",(()=>({messageType:"object",message:t.map((e=>{const t=e.type===he.Message||e.type===he.Signal?Y(e.data.message):void 0;return t?{type:e.type,data:Object.assign(Object.assign({},e.data),{pn_mfp:t})}:e})),details:"Received events:"}))),t.forEach((t=>this.emitEvent(e,t)))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.emitStatus(t)}},emitStatus:e=>this.emitStatus(e)})}else this.logger.debug("PubNub","Using legacy subscription loop management."),this.subscriptionManager=new ye(this._configuration,((e,t)=>{try{this.emitEvent(e,t)}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.emitStatus(t)}}),this.emitStatus.bind(this),((e,t)=>{this.logger.trace("SubscriptionManager",(()=>({messageType:"object",message:Object.assign({},e),details:"Subscribe with parameters:",ignoredKeys:["crypto","timeout","keySet","getFileUrl"]}))),this.makeSubscribe(e,t)}),((e,t)=>(this.logger.trace("SubscriptionManager",(()=>({messageType:"object",message:Object.assign({},e),details:"Heartbeat with parameters:",ignoredKeys:["crypto","timeout","keySet","getFileUrl"]}))),this.heartbeat(e,t))),((e,t)=>{this.logger.trace("SubscriptionManager",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave with parameters:"}))),this.makeUnsubscribe(e,t)}),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this.logger.debug("PubNub",`Set auth key: ${e}`),this._configuration.setAuthKey(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length){const e=new Error("Missing or invalid userId parameter. Provide a valid string userId");throw this.logger.error("PubNub",(()=>({messageType:"error",message:e}))),e}this.logger.debug("PubNub",`Set user ID: ${e}`),this._configuration.userId=e}getUserId(){return this._configuration.userId}setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length){const e=new Error("Missing or invalid userId parameter. Provide a valid string userId");throw this.logger.error("PubNub",(()=>({messageType:"error",message:e}))),e}this.logger.debug("PubNub",`Set user ID: ${e}`),this._configuration.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this.logger.debug("PubNub",`Set filter expression: ${e}`),this._configuration.setFilterExpression(e)}setFilterExpression(e){this.logger.debug("PubNub",`Set filter expression: ${e}`),this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.logger.debug("PubNub",`Set cipher key: ${e}`),this.cipherKey=e}set heartbeatInterval(e){this.logger.debug("PubNub",`Set heartbeat interval: ${e}`),this._configuration.setHeartbeatInterval(e)}setHeartbeatInterval(e){this.logger.debug("PubNub",`Set heartbeat interval: ${e}`),this.heartbeatInterval=e}get logger(){return this._configuration.logger()}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this.logger.debug("PubNub",`Add '${e}' 'pnsdk' suffix: ${t}`),this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.logger.warn("PubNub","'setUserId` is deprecated, please use 'setUserId' or 'userId' setter instead."),this.logger.debug("PubNub",`Set UUID: ${e}`),this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){let t=this.entities[`${e}_ch`];return t||(t=this.entities[`${e}_ch`]=new rs(e,this)),t}channelGroup(e){let t=this.entities[`${e}_chg`];return t||(t=this.entities[`${e}_chg`]=new ss(e,this)),t}channelMetadata(e){let t=this.entities[`${e}_chm`];return t||(t=this.entities[`${e}_chm`]=new ts(e,this)),t}userMetadata(e){let t=this.entities[`${e}_um`];return t||(t=this.entities[`${e}_um`]=new ns(e,this)),t}subscriptionSet(e){var t,s;{const n=[];return null===(t=e.channels)||void 0===t||t.forEach((e=>n.push(this.channel(e)))),null===(s=e.channelGroups)||void 0===s||s.forEach((e=>n.push(this.channelGroup(e)))),new Qt({client:this,entities:n,options:e.subscriptionOptions})}}sendRequest(e,t){return i(this,void 0,void 0,(function*(){const s=e.validate();if(s){const e=(n=s,p(Object.assign({message:n},{}),h.PNValidationErrorCategory));if(this.logger.error("PubNub",(()=>({messageType:"error",message:e}))),t)return t(e,null);throw new d("Validation failed, check status for details",e)}var n;const r=e.request(),i=e.operation();r.formData&&r.formData.length>0||i===le.PNDownloadFileOperation?r.timeout=this._configuration.getFileTimeout():i===le.PNSubscribeOperation||i===le.PNReceiveMessagesOperation?r.timeout=this._configuration.getSubscribeTimeout():r.timeout=this._configuration.getTransactionTimeout();const a={error:!1,operation:i,category:h.PNAcknowledgmentCategory,statusCode:0},[o,c]=this.transport.makeSendable(r);return e.cancellationController=c||null,o.then((t=>{if(a.statusCode=t.status,200!==t.status&&204!==t.status){const e=Ms.decoder.decode(t.body),s=t.headers["content-type"];if(s||-1!==s.indexOf("javascript")||-1!==s.indexOf("json")){const t=JSON.parse(e);"object"==typeof t&&"error"in t&&t.error&&"object"==typeof t.error&&(a.errorData=t.error)}else a.responseText=e}return e.parse(t)})).then((e=>t?t(a,e):e)).catch((e=>{const s=e instanceof _?e:_.create(e);if(t)return s.category!==h.PNCancelledCategory&&this.logger.error("PubNub",(()=>({messageType:"error",message:s.toPubNubError(i,"REST API request processing error, check status for details")}))),t(s.toStatus(i),null);const n=s.toPubNubError(i,"REST API request processing error, check status for details");throw s.category!==h.PNCancelledCategory&&this.logger.error("PubNub",(()=>({messageType:"error",message:n}))),n}))}))}destroy(e=!1){this.logger.info("PubNub","Destroying PubNub client."),this._globalSubscriptionSet&&(this._globalSubscriptionSet.invalidate(!0),this._globalSubscriptionSet=void 0),Object.values(this.eventHandleCapable).forEach((e=>e.invalidate(!0))),this.eventHandleCapable={},this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.unsubscribeAll(e),this.presenceEventEngine&&this.presenceEventEngine.leaveAll(e)}stop(){this.logger.warn("PubNub","'stop' is deprecated, please use 'destroy' instead."),this.destroy()}publish(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Publish with parameters:"})));const s=!1===e.replicate&&!1===e.storeInHistory,n=new wt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()})),r=e=>{e&&this.logger.debug("PubNub",`${s?"Fire":"Publish"} success with timetoken: ${e.timetoken}`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}}))}signal(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Signal with parameters:"})));const s=new Ot(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Publish success with timetoken: ${e.timetoken}`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}fire(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fire with parameters:"}))),null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}get globalSubscriptionSet(){return this._globalSubscriptionSet||(this._globalSubscriptionSet=this.subscriptionSet({})),this._globalSubscriptionSet}get subscriptionTimetoken(){return this.subscriptionManager?this.subscriptionManager.subscriptionTimetoken:this.eventEngine?this.eventEngine.subscriptionTimetoken:void 0}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}registerEventHandleCapable(e,t,s){{let n;this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign(Object.assign({subscription:e},t?{cursor:t}:[]),s?{subscriptions:s}:{}),details:"Register event handle capable:"}))),this.eventHandleCapable[e.state.id]||(this.eventHandleCapable[e.state.id]=e),s&&0!==s.length?(n=new zt({}),s.forEach((e=>n.add(e.subscriptionInput(!1))))):n=e.subscriptionInput(!1);const r={};r.channels=n.channels,r.channelGroups=n.channelGroups,t&&(r.timetoken=t.timetoken),this.subscriptionManager?this.subscriptionManager.subscribe(r):this.eventEngine&&this.eventEngine.subscribe(r)}}unregisterEventHandleCapable(e,t){{if(!this.eventHandleCapable[e.state.id])return;const s=[];let n;if(this.logger.trace("PubNub",(()=>({messageType:"object",message:{subscription:e,subscriptions:t},details:"Unregister event handle capable:"}))),t&&0!==t.length||delete this.eventHandleCapable[e.state.id],t&&0!==t.length?(n=new zt({}),t.forEach((e=>{const t=e.subscriptionInput(!0);t.isEmpty?s.push(e):n.add(t)}))):(n=e.subscriptionInput(!0),n.isEmpty&&s.push(e)),s.length>0&&this.logger.trace("PubNub",(()=>{const e=[];return s[0]instanceof Qt?s[0].subscriptions.forEach((t=>e.push(t.state.entity))):s.forEach((t=>e.push(t.state.entity))),{messageType:"object",message:{entities:e},details:"Can't unregister event handle capable because entities still in use:"}})),n.isEmpty)return;const r={};r.channels=n.channels,r.channelGroups=n.channelGroups,this.subscriptionManager?this.subscriptionManager.unsubscribe(r):this.eventEngine&&this.eventEngine.unsubscribe(r)}}subscribe(e){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Subscribe with parameters:"})));const t=this.subscriptionSet(Object.assign(Object.assign({},e),{subscriptionOptions:{receivePresenceEvents:e.withPresence}}));this.globalSubscriptionSet.addSubscriptionSet(t),t.dispose();const s="number"==typeof e.timetoken?`${e.timetoken}`:e.timetoken;this.globalSubscriptionSet.subscribe({timetoken:s})}}makeSubscribe(e,t){{const s=new pe(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(s,((e,n)=>{var r;this.subscriptionManager&&(null===(r=this.subscriptionManager.abort)||void 0===r?void 0:r.identifier)===s.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,n)})),this.subscriptionManager){const e=()=>s.abort("Cancel long-poll subscribe request");e.identifier=s.requestIdentifier,this.subscriptionManager.abort=e}}}unsubscribe(e){{if(this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Unsubscribe with parameters:"}))),!this._globalSubscriptionSet)return void this.logger.debug("PubNub","There are no active subscriptions. Ignore.");const t=this.globalSubscriptionSet.subscriptions.filter((t=>{var s,n;const r=t.subscriptionInput(!1);if(r.isEmpty)return!1;for(const t of null!==(s=e.channels)&&void 0!==s?s:[])if(r.contains(t))return!0;for(const t of null!==(n=e.channelGroups)&&void 0!==n?n:[])if(r.contains(t))return!0}));t.length>0&&this.globalSubscriptionSet.removeSubscriptions(t)}}makeUnsubscribe(e,t){{let{channels:s,channelGroups:n}=e;if(this._configuration.getKeepPresenceChannelsInPresenceRequests()||(n&&(n=n.filter((e=>!e.endsWith("-pnpres")))),s&&(s=s.filter((e=>!e.endsWith("-pnpres"))))),0===(null!=n?n:[]).length&&0===(null!=s?s:[]).length)return t({error:!1,operation:le.PNUnsubscribeOperation,category:h.PNAcknowledgmentCategory,statusCode:200});this.sendRequest(new Nt({channels:s,channelGroups:n,keySet:this._configuration.keySet}),t)}}unsubscribeAll(){this.logger.debug("PubNub","Unsubscribe all channels and groups"),this._globalSubscriptionSet&&this._globalSubscriptionSet.invalidate(!1),Object.values(this.eventHandleCapable).forEach((e=>e.invalidate(!1))),this.eventHandleCapable={},this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(e=!1){this.logger.debug("PubNub","Disconnect (while offline? "+(e?"yes":"no")),this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect(e)}reconnect(e){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Reconnect with parameters:"}))),this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return i(this,void 0,void 0,(function*(){{const t=new Ct(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort("Cancel subscribe handshake request")}));return this.sendRequest(t).then((e=>(s(),e.cursor)))}}))}subscribeReceiveMessages(e){return i(this,void 0,void 0,(function*(){{const t=new kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort("Cancel long-poll subscribe request")}));return this.sendRequest(t).then((e=>(s(),e)))}}))}getMessageActions(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get message actions with parameters:"})));const s=new Rt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Get message actions success. Received ${e.data.length} message actions.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}addMessageAction(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add message action with parameters:"})));const s=new Ft(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Message action add success. Message action added with timetoken: ${e.data.actionTimetoken}`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}removeMessageAction(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove message action with parameters:"})));const s=new Dt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Message action remove success. Removed message action with ${e.actionTimetoken} timetoken.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}fetchMessages(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch messages with parameters:"})));const s=new $t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),n=e=>{if(!e)return;const t=Object.values(e.channels).reduce(((e,t)=>e+t.length),0);this.logger.debug("PubNub",`Fetch messages success. Received ${t} messages.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}deleteMessages(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Delete messages with parameters:"})));const s=new It(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub","Delete messages success.")};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}messageCounts(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get messages count with parameters:"})));const s=new Mt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=t=>{if(!t)return;const s=Object.values(t.channels).reduce(((e,t)=>e+t),0);this.logger.debug("PubNub",`Get messages count success. There are ${s} messages since provided reference timetoken${e.channelTimetokens?e.channelTimetokens.join(","):""}.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}history(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch history with parameters:"})));const s=new At(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()})),n=e=>{e&&this.logger.debug("PubNub",`Fetch history success. Received ${e.messages.length} messages.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}hereNow(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Here now with parameters:"})));const s=new _t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Here now success. There are ${e.totalOccupancy} participants in ${e.totalChannels} channels.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}whereNow(e,t){return i(this,void 0,void 0,(function*(){var s;{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Where now with parameters:"})));const n=new Tt({uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet}),r=e=>{e&&this.logger.debug("PubNub",`Where now success. Currently present in ${e.channels.length} channels.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}}))}getState(e,t){return i(this,void 0,void 0,(function*(){var s;{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get presence state with parameters:"})));const n=new Pt(Object.assign(Object.assign({},e),{uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Get presence state success. Received presence state for ${Object.keys(e.channels).length} channels.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}}))}setState(e,t){return i(this,void 0,void 0,(function*(){var s,n;{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set presence state with parameters:"})));const{keySet:r,userId:i}=this._configuration,a=this._configuration.getPresenceTimeout();let o;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(s=e.channels)||void 0===s||s.forEach((s=>t[s]=e.state)),"channelGroups"in e&&(null===(n=e.channelGroups)||void 0===n||n.forEach((s=>t[s]=e.state)))}o="withHeartbeat"in e&&e.withHeartbeat?new Et(Object.assign(Object.assign({},e),{keySet:r,heartbeat:a})):new jt(Object.assign(Object.assign({},e),{keySet:r,uuid:i}));const c=e=>{e&&this.logger.debug("PubNub","Set presence state success."+(o instanceof Et?" Presence state has been set using heartbeat endpoint.":""))};return this.subscriptionManager&&this.subscriptionManager.setState(e),t?this.sendRequest(o,((e,s)=>{c(s),t(e,s)})):this.sendRequest(o).then((e=>(c(e),e)))}}))}presence(e){var t;this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Change presence with parameters:"}))),null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return i(this,void 0,void 0,(function*(){{this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Heartbeat with parameters:"})));let{channels:s,channelGroups:n}=e;if(this._configuration.getKeepPresenceChannelsInPresenceRequests()||(n&&(n=n.filter((e=>!e.endsWith("-pnpres")))),s&&(s=s.filter((e=>!e.endsWith("-pnpres"))))),0===(null!=n?n:[]).length&&0===(null!=s?s:[]).length){const e={error:!1,operation:le.PNHeartbeatOperation,category:h.PNAcknowledgmentCategory,statusCode:200};return this.logger.trace("PubNub","There are no active subscriptions. Ignore."),t?t(e,{}):Promise.resolve(e)}const r=new Et(Object.assign(Object.assign({},e),{channels:s,channelGroups:n,keySet:this._configuration.keySet})),i=e=>{e&&this.logger.trace("PubNub","Heartbeat success.")};return t?this.sendRequest(r,((e,s)=>{i(s),t(e,s)})):this.sendRequest(r).then((e=>(i(e),e)))}}))}join(e){this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Join with parameters:"}))),this.presenceEventEngine?this.presenceEventEngine.join(e):this.heartbeat(Object.assign(Object.assign({channels:e.channels,channelGroups:e.groups},this._configuration.maintainPresenceState&&this.presenceState&&Object.keys(this.presenceState).length>0&&{state:this.presenceState}),{heartbeat:this._configuration.getPresenceTimeout()}),(()=>{}))}presenceReconnect(e){this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Presence reconnect with parameters:"}))),this.presenceEventEngine?this.presenceEventEngine.reconnect():this.heartbeat(Object.assign(Object.assign({channels:e.channels,channelGroups:e.groups},this._configuration.maintainPresenceState&&{state:this.presenceState}),{heartbeat:this._configuration.getPresenceTimeout()}),(()=>{}))}leave(e){var t;this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave with parameters:"}))),this.presenceEventEngine?null===(t=this.presenceEventEngine)||void 0===t||t.leave(e):this.makeUnsubscribe({channels:e.channels,channelGroups:e.groups},(()=>{}))}leaveAll(e={}){this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave all with parameters:"}))),this.presenceEventEngine?this.presenceEventEngine.leaveAll(!!e.isOffline):e.isOffline||this.makeUnsubscribe({channels:e.channels,channelGroups:e.groups},(()=>{}))}presenceDisconnect(e){this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Presence disconnect parameters:"}))),this.presenceEventEngine?this.presenceEventEngine.disconnect(!!e.isOffline):e.isOffline||this.makeUnsubscribe({channels:e.channels,channelGroups:e.groups},(()=>{}))}grantToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Token error: PAM module disabled")}))}revokeToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Revoke Token error: PAM module disabled")}))}get token(){return this.tokenManager&&this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager&&this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager&&this.tokenManager.parseToken(e)}grant(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant error: PAM module disabled")}))}audit(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Permissions error: PAM module disabled")}))}get objects(){return this._objects}fetchUsers(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchUsers' is deprecated. Use 'pubnub.objects.getAllUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{},details:"Fetch all User objects with parameters:"}))),this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchUser' is deprecated. Use 'pubnub.objects.getUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{uuid:this.userId},details:`Fetch${e&&"function"!=typeof e?"":" current"} User object with parameters:`}))),this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'createUser' is deprecated. Use 'pubnub.objects.setUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create User object with parameters:"}))),this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'updateUser' is deprecated. Use 'pubnub.objects.setUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update User object with parameters:"}))),this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'removeUser' is deprecated. Use 'pubnub.objects.removeUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{uuid:this.userId},details:`Remove${e&&"function"!=typeof e?"":" current"} User object with parameters:`}))),this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchSpaces' is deprecated. Use 'pubnub.objects.getAllChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{},details:"Fetch all Space objects with parameters:"}))),this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchSpace' is deprecated. Use 'pubnub.objects.getChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch Space object with parameters:"}))),this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'createSpace' is deprecated. Use 'pubnub.objects.setChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create Space object with parameters:"}))),this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'updateSpace' is deprecated. Use 'pubnub.objects.setChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update Space object with parameters:"}))),this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'removeSpace' is deprecated. Use 'pubnub.objects.removeChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Space object with parameters:"}))),this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'addMemberships' is deprecated. Use 'pubnub.objects.setChannelMembers' or 'pubnub.objects.setMemberships' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update memberships with parameters:"}))),this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r;{if(this.logger.warn("PubNub","'removeMemberships' is deprecated. Use 'pubnub.objects.removeMemberships' or 'pubnub.objects.removeChannelMembers' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove memberships with parameters:"}))),"spaceId"in e){const r=e,i={channel:null!==(s=r.spaceId)&&void 0!==s?s:r.channel,uuids:null!==(n=r.userIds)&&void 0!==n?n:r.uuids,limit:0};return t?this.objects.removeChannelMembers(i,t):this.objects.removeChannelMembers(i)}const i=e,a={uuid:i.userId,channels:null!==(r=i.spaceIds)&&void 0!==r?r:i.channels,limit:0};return t?this.objects.removeMemberships(a,t):this.objects.removeMemberships(a)}}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Send file with parameters:"})));const s=new Bt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),n={error:!1,operation:le.PNPublishFileOperation,category:h.PNAcknowledgmentCategory,statusCode:0},r=e=>{e&&this.logger.debug("PubNub",`Send file success. File shared with ${e.id} ID.`)};return s.process().then((e=>(n.statusCode=e.status,r(e),t?t(n,e):e))).catch((e=>{let s;throw e instanceof d?s=e.status:e instanceof _&&(s=e.toStatus(n.operation)),this.logger.error("PubNub",(()=>({messageType:"error",message:new d("File sending error. Check status for details",s)}))),t&&s&&t(s,null),new d("REST API request processing error. Check status for details",s)}))}}))}publishFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Publish file message with parameters:"})));const s=new xt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()})),n=e=>{e&&this.logger.debug("PubNub",`Publish file message success. File message published with timetoken: ${e.timetoken}`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}listFiles(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"List files with parameters:"})));const s=new Kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`List files success. There are ${e.count} uploaded files.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}getFileUrl(e){var t;{const s=this.transport.request(new Gt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),n=null!==(t=s.queryParameters)&&void 0!==t?t:{},r=Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${H(t)}`)).join("&"):`${e}=${H(t)}`})).join("&");return`${s.origin}${s.path}?${r}`}}downloadFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Download file with parameters:"})));const s=new Is(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()})),n=e=>{e&&this.logger.debug("PubNub","Download file success.")};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):yield this.sendRequest(s).then((e=>(n(e),e)))}}))}deleteFile(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Delete file with parameters:"})));const s=new qt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Delete file success. Deleted file with ${e.id} ID.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}time(e){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub","Get service time.");const t=new _s,s=e=>{e&&this.logger.debug("PubNub",`Get service time success. Current timetoken: ${e.timetoken}`)};return e?this.sendRequest(t,((t,n)=>{s(n),e(t,n)})):this.sendRequest(t).then((e=>(s(e),e)))}))}emitStatus(e){var t;null===(t=this.eventDispatcher)||void 0===t||t.handleStatus(e)}emitEvent(e,t){var s;this._globalSubscriptionSet&&this._globalSubscriptionSet.handleEvent(e,t),null===(s=this.eventDispatcher)||void 0===s||s.handleEvent(t),Object.values(this.eventHandleCapable).forEach((s=>{s.handleEvent(e,t)}))}set onStatus(e){this.eventDispatcher&&(this.eventDispatcher.onStatus=e)}set onMessage(e){this.eventDispatcher&&(this.eventDispatcher.onMessage=e)}set onPresence(e){this.eventDispatcher&&(this.eventDispatcher.onPresence=e)}set onSignal(e){this.eventDispatcher&&(this.eventDispatcher.onSignal=e)}set onObjects(e){this.eventDispatcher&&(this.eventDispatcher.onObjects=e)}set onMessageAction(e){this.eventDispatcher&&(this.eventDispatcher.onMessageAction=e)}set onFile(e){this.eventDispatcher&&(this.eventDispatcher.onFile=e)}addListener(e){this.eventDispatcher&&this.eventDispatcher.addListener(e)}removeListener(e){this.eventDispatcher&&this.eventDispatcher.removeListener(e)}removeAllListeners(){this.eventDispatcher&&this.eventDispatcher.removeAllListeners()}encrypt(e,t){this.logger.warn("PubNub","'encrypt' is deprecated. Use cryptoModule instead.");const s=this._configuration.getCryptoModule();if(!t&&s&&"string"==typeof e){const t=s.encrypt(e);return"string"==typeof t?t:u(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){this.logger.warn("PubNub","'decrypt' is deprecated. Use cryptoModule instead.");const s=this._configuration.getCryptoModule();if(!t&&s){const t=s.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.decryptFile(t,this._configuration.PubNubFile)}))}}Ms.decoder=new TextDecoder,Ms.OPERATIONS=le,Ms.CATEGORIES=h,Ms.Endpoint=U,Ms.ExponentialRetryPolicy=$.ExponentialRetryPolicy,Ms.LinearRetryPolicy=$.LinearRetryPolicy,Ms.NoneRetryPolicy=$.None,Ms.LogLevel=G;class As{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const s=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,n=this.decode(this.base64ToBinary(s));return"object"==typeof n?n:void 0}}class Us extends Ms{constructor(e){var t;const s=void 0!==e.subscriptionWorkerUrl,r=A(e),i=Object.assign(Object.assign({},r),{sdkFamily:"Web"});i.PubNubFile=o;const a=ee(i,(e=>{if(e.cipherKey){return new E({default:new j(Object.assign(Object.assign({},e),e.logger?{}:{logger:a.logger()})),cryptors:[new O({cipherKey:e.cipherKey})]})}}));let u,l,h;a.getCryptoModule()&&(a.getCryptoModule().logger=a.logger()),u=new ne(new As((e=>M(n.decode(e))),c)),(a.getCipherKey()||a.secretKey)&&(l=new C({secretKey:a.secretKey,cipherKey:a.getCipherKey(),useRandomIVs:a.getUseRandomIVs(),customEncrypt:a.getCustomEncrypt(),customDecrypt:a.getCustomDecrypt(),logger:a.logger()})),h=new P;let d=new ce(a.logger(),i.transport);if(r.subscriptionWorkerUrl){const e=new I({clientIdentifier:a._instanceId,subscriptionKey:a.subscribeKey,userId:a.getUserId(),workerUrl:r.subscriptionWorkerUrl,sdkVersion:a.getVersion(),heartbeatInterval:a.getHeartbeatInterval(),workerOfflineClientsCheckInterval:i.subscriptionWorkerOfflineClientsCheckInterval,workerUnsubscribeOfflineClients:i.subscriptionWorkerUnsubscribeOfflineClients,workerLogVerbosity:i.subscriptionWorkerLogVerbosity,tokenManager:u,transport:d,logger:a.logger()});d=e,window.onpagehide=t=>{t.persisted||e.terminate()}}else s&&a.logger().warn("PubNub","SharedWorker not supported in this browser. Fallback to the original transport.");const p=new oe({clientConfiguration:a,tokenManager:u,transport:d});super({configuration:a,transport:p,cryptography:h,tokenManager:u,crypto:l}),(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.logger.debug("PubNub","Network down detected"),this.emitStatus({category:Us.CATEGORIES.PNNetworkDownCategory}),this._configuration.restore?this.disconnect(!0):this.destroy(!0)}networkUpDetected(){this.logger.debug("PubNub","Network up detected"),this.emitStatus({category:Us.CATEGORIES.PNNetworkUpCategory}),this.reconnect()}}return Us.CryptoModule=E,Us})); +/*! lil-uuid - v0.1 - MIT License - https://github.com/lil-js/uuid */!function(e,t){!function(e){var t="0.1.0",s={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 n(){var e,t,s="";for(e=0;e<32;e++)t=16*Math.random()|0,8!==e&&12!==e&&16!==e&&20!==e||(s+="-"),s+=(12===e?4:16===e?3&t|8:t).toString(16);return s}function r(e,t){var n=s[t||"all"];return n&&n.test(e)||!1}n.isUUID=r,n.VERSION=t,e.uuid=n,e.isUUID=r}(t),null!==e&&(e.exports=t.uuid)}(x,x.exports);var G,q=t(x.exports),K={createUUID:()=>q.uuid?q.uuid():q()};!function(e){e[e.Trace=0]="Trace",e[e.Debug=1]="Debug",e[e.Info=2]="Info",e[e.Warn=3]="Warn",e[e.Error=4]="Error",e[e.None=5]="None"}(G||(G={}));class L{constructor(e,t,s){this.pubNubId=e,this.minLogLevel=t,this.loggers=s}get logLevel(){return this.minLogLevel}trace(e,t){this.log(G.Trace,e,t)}debug(e,t){this.log(G.Debug,e,t)}info(e,t){this.log(G.Info,e,t)}warn(e,t){this.log(G.Warn,e,t)}error(e,t){this.log(G.Error,e,t)}log(e,t,s){if(ee[n](r)))}}const H=e=>encodeURIComponent(e).replace(/[!~*'()]/g,(e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`)),B=(e,t)=>{const s=e.map((e=>H(e)));return s.length?s.join(","):null!=t?t:""},W=(e,t)=>{const s=Object.fromEntries(t.map((e=>[e,!1])));return e.filter((e=>!(t.includes(e)&&!s[e])||(s[e]=!0,!1)))},z=(e,t)=>[...e].filter((s=>t.includes(s)&&e.indexOf(s)===e.lastIndexOf(s)&&t.indexOf(s)===t.lastIndexOf(s))),V=e=>Object.keys(e).map((t=>{const s=e[t];return Array.isArray(s)?s.map((e=>`${t}=${H(e)}`)).join("&"):`${t}=${H(s)}`})).join("&"),J=(e,t)=>{if("0"===t||"0"===e)return;const s=Q(`${Date.now()}0000`,t,!1);return Q(e,s,!0)},X=(e,t,s)=>{if(e&&0!==e.length){if(t&&t.length>0&&"0"!==t){const n=Q(e,t,!1);return Q(null!=s?s:`${Date.now()}0000`,n.replace("-",""),Number(n)<0)}return s&&s.length>0&&"0"!==s?s:`${Date.now()}0000`}},Q=(e,t,s)=>{t=t.padStart(17,"0");const n=e.slice(0,10),r=e.slice(10,17),i=t.slice(0,10),a=t.slice(10,17);let o=Number(n),c=Number(r);return o+=Number(i)*(s?1:-1),c+=Number(a)*(s?1:-1),c>=1e7?(o+=Math.floor(c/1e7),c%=1e7):c<0&&(o>0?(o-=1,c+=1e7):o<0&&(c*=-1)),0!==o?`${o}${`${c}`.padStart(7,"0")}`:`${c}`},Y=e=>{const t="string"!=typeof e?JSON.stringify(e):e,s=new Uint32Array(1);let n=0,r=t.length;for(;r-- >0;)s[0]=(s[0]<<5)-s[0]+t.charCodeAt(n++);return s[0].toString(16).padStart(8,"0")};class Z{debug(e){this.log(e)}error(e){this.log(e)}info(e){this.log(e)}trace(e){this.log(e)}warn(e){this.log(e)}log(e){const t=G[e.level],s=t.toLowerCase();console["trace"===s?"debug":s](`${e.timestamp.toISOString()} PubNub-${e.pubNubId} ${t.padEnd(5," ")}${e.location?` ${e.location}`:""} ${this.logMessage(e)}`)}logMessage(e){if("text"===e.messageType)return e.message;if("object"===e.messageType)return`${e.details?`${e.details}\n`:""}${this.formattedObject(e)}`;if("network-request"===e.messageType){const t=!!e.canceled||!!e.failed,s=e.minimumLevel!==G.Trace||t?void 0:this.formattedHeaders(e),n=e.message,r=n.queryParameters&&Object.keys(n.queryParameters).length>0?V(n.queryParameters):void 0,i=`${n.origin}${n.path}${r?`?${r}`:""}`,a=t?void 0:this.formattedBody(e);let o="Sending";t&&(o=`${e.canceled?"Canceled":"Failed"}${e.details?` (${e.details})`:""}`);const c=((null==a?void 0:a.formData)?"FormData":"Method").length;return`${o} HTTP request:\n ${this.paddedString("Method",c)}: ${n.method}\n ${this.paddedString("URL",c)}: ${i}${s?`\n ${this.paddedString("Headers",c)}:\n${s}`:""}${(null==a?void 0:a.formData)?`\n ${this.paddedString("FormData",c)}:\n${a.formData}`:""}${(null==a?void 0:a.body)?`\n ${this.paddedString("Body",c)}:\n${a.body}`:""}`}if("network-response"===e.messageType){const t=e.minimumLevel===G.Trace?this.formattedHeaders(e):void 0,s=this.formattedBody(e),n=((null==s?void 0:s.formData)?"Headers":"Status").length,r=e.message;return`Received HTTP response:\n ${this.paddedString("URL",n)}: ${r.url}\n ${this.paddedString("Status",n)}: ${r.status}${t?`\n ${this.paddedString("Headers",n)}:\n${t}`:""}${(null==s?void 0:s.body)?`\n ${this.paddedString("Body",n)}:\n${s.body}`:""}`}if("error"===e.messageType){const t=this.formattedErrorStatus(e),s=e.message;return`${s.name}: ${s.message}${t?`\n${t}`:""}`}return""}formattedObject(e){const t=(s,n=1,r=!1)=>{const i=10===n,a=" ".repeat(2*n),o=[],c=(t,s)=>!!e.ignoredKeys&&("function"==typeof e.ignoredKeys?e.ignoredKeys(t,s):e.ignoredKeys.includes(t));if("string"==typeof s)o.push(`${a}- ${s}`);else if("number"==typeof s)o.push(`${a}- ${s}`);else if("boolean"==typeof s)o.push(`${a}- ${s}`);else if(null===s)o.push(`${a}- null`);else if(void 0===s)o.push(`${a}- undefined`);else if("function"==typeof s)o.push(`${a}- `);else if("object"==typeof s)if(Array.isArray(s)||"function"!=typeof s.toString||0===s.toString().indexOf("[object"))if(Array.isArray(s))for(const e of s){const s=r?"":a;if(null===e)o.push(`${s}- null`);else if(void 0===e)o.push(`${s}- undefined`);else if("function"==typeof e)o.push(`${s}- `);else if("object"==typeof e){const r=Array.isArray(e),a=i?"...":t(e,n+1,!r);o.push(`${s}-${r&&!i?"\n":" "}${a}`)}else o.push(`${s}- ${e}`);r=!1}else{const e=s,u=Object.keys(e),l=u.reduce(((t,s)=>Math.max(t,c(s,e)?t:s.length)),0);for(const s of u){if(c(s,e))continue;const u=r?"":a,h=e[s],d=s.padEnd(l," ");if(null===h)o.push(`${u}${d}: null`);else if(void 0===h)o.push(`${u}${d}: undefined`);else if("function"==typeof h)o.push(`${u}${d}: `);else if("object"==typeof h){const e=Array.isArray(h),s=e&&0===h.length,r=!e&&"function"==typeof h.toString&&0!==h.toString().indexOf("[object"),a=i?"...":s?"[]":t(h,n+1,r);o.push(`${u}${d}:${i||r||s?" ":"\n"}${a}`)}else o.push(`${u}${d}: ${h}`);r=!1}}else o.push(`${r?"":a}${s.toString()}`),r=!1;return o.join("\n")};return t(e.message)}formattedHeaders(e){if(!e.message.headers)return;const t=e.message.headers,s=Object.keys(t).reduce(((e,t)=>Math.max(e,t.length)),0);return Object.keys(t).map((e=>` - ${e.toLowerCase().padEnd(s," ")}: ${t[e]}`)).join("\n")}formattedBody(e){var t;if(!e.message.headers)return;let s,n;const r=e.message.headers,i=null!==(t=r["content-type"])&&void 0!==t?t:r["Content-Type"],a="formData"in e.message?e.message.formData:void 0,o=e.message.body;if(a){const e=a.reduce(((e,{key:t})=>Math.max(e,t.length)),0);s=a.map((({key:t,value:s})=>` - ${t.padEnd(e," ")}: ${s}`)).join("\n")}return o?(n="string"==typeof o?` ${o}`:o instanceof ArrayBuffer?!i||-1===i.indexOf("javascript")&&-1===i.indexOf("json")?` ArrayBuffer { byteLength: ${o.byteLength} }`:` ${Z.decoder.decode(o)}`:` File { name: ${o.name}${o.contentLength?`, contentLength: ${o.contentLength}`:""}${o.mimeType?`, mimeType: ${o.mimeType}`:""} }`,{body:n,formData:s}):{formData:s}}formattedErrorStatus(e){if(!e.message.status)return;const t=e.message.status,s=t.errorData;let n;if(Z.isError(s))n=` ${s.name}: ${s.message}`,s.stack&&(n+=`\n${s.stack.split("\n").map((e=>` ${e}`)).join("\n")}`);else if(s)try{n=` ${JSON.stringify(s)}`}catch(e){n=` ${s}`}return` Category : ${t.category}\n Operation : ${t.operation}\n Status : ${t.statusCode}${n?`\n Error data:\n${n}`:""}`}paddedString(e,t){return e.padEnd(t-e.length," ")}static isError(e){return!!e&&(e instanceof Error||"[object Error]"===Object.prototype.toString.call(e))}}Z.decoder=new TextDecoder;const ee=(e,t)=>{var s,n,r,i;!e.retryConfiguration&&e.enableEventEngine&&(e.retryConfiguration=$.ExponentialRetryPolicy({minimumDelay:2,maximumDelay:150,maximumRetry:6,excluded:[U.MessageSend,U.Presence,U.Files,U.MessageStorage,U.ChannelGroups,U.DevicePushNotifications,U.AppContext,U.MessageReactions]}));const a=`pn-${K.createUUID()}`;e.logVerbosity?e.logLevel=G.Debug:void 0===e.logLevel&&(e.logLevel=G.None);const o=new L(se(a),e.logLevel,[...null!==(s=e.loggers)&&void 0!==s?s:[],new Z]);void 0!==e.logVerbosity&&o.warn("Configuration","'logVerbosity' is deprecated. Use 'logLevel' instead."),null===(n=e.retryConfiguration)||void 0===n||n.validate(),null!==(r=e.useRandomIVs)&&void 0!==r||(e.useRandomIVs=true),e.useRandomIVs&&o.warn("Configuration","'useRandomIVs' is deprecated. Use 'cryptoModule' instead."),e.origin=te(null!==(i=e.ssl)&&void 0!==i&&i,e.origin);const c=e.cryptoModule;c&&delete e.cryptoModule;const u=Object.assign(Object.assign({},e),{_pnsdkSuffix:{},_loggerManager:o,_instanceId:a,_cryptoModule:void 0,_cipherKey:void 0,_setupCryptoModule:t,get instanceId(){if(e.useInstanceId)return this._instanceId},getInstanceId(){if(e.useInstanceId)return this._instanceId},getUserId(){return this.userId},setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length)throw new Error("Missing or invalid userId parameter. Provide a valid string userId");this.userId=e},logger(){return this._loggerManager},getAuthKey(){return this.authKey},setAuthKey(e){this.authKey=e},getFilterExpression(){return this.filterExpression},setFilterExpression(e){this.filterExpression=e},getCipherKey(){return this._cipherKey},setCipherKey(t){this._cipherKey=t,t||!this._cryptoModule?t&&this._setupCryptoModule&&(this._cryptoModule=this._setupCryptoModule({cipherKey:t,useRandomIVs:e.useRandomIVs,customEncrypt:this.getCustomEncrypt(),customDecrypt:this.getCustomDecrypt(),logger:this.logger()})):this._cryptoModule=void 0},getCryptoModule(){return this._cryptoModule},getUseRandomIVs:()=>e.useRandomIVs,getKeepPresenceChannelsInPresenceRequests:()=>"Web"===e.sdkFamily&&e.subscriptionWorkerUrl,setPresenceTimeout(e){this.heartbeatInterval=e/2-1,this.presenceTimeout=e},getPresenceTimeout(){return this.presenceTimeout},getHeartbeatInterval(){return this.heartbeatInterval},setHeartbeatInterval(e){this.heartbeatInterval=e},getTransactionTimeout(){return this.transactionalRequestTimeout},getSubscribeTimeout(){return this.subscribeRequestTimeout},getFileTimeout(){return this.fileRequestTimeout},get PubNubFile(){return e.PubNubFile},get version(){return"9.6.2"},getVersion(){return this.version},_addPnsdkSuffix(e,t){this._pnsdkSuffix[e]=`${t}`},_getPnsdkSuffix(e){const t=Object.values(this._pnsdkSuffix).join(e);return t.length>0?e+t:""},getUUID(){return this.getUserId()},setUUID(e){this.setUserId(e)},getCustomEncrypt:()=>e.customEncrypt,getCustomDecrypt:()=>e.customDecrypt});return e.cipherKey?(o.warn("Configuration","'cipherKey' is deprecated. Use 'cryptoModule' instead."),u.setCipherKey(e.cipherKey)):c&&(u._cryptoModule=c),u},te=(e,t)=>{const s=e?"https://":"http://";return"string"==typeof t?`${s}${t}`:`${s}${t[Math.floor(Math.random()*t.length)]}`},se=e=>{let t=2166136261;for(let s=0;s>>0;return t.toString(16).padStart(8,"0")};class ne{constructor(e){this.cbor=e}setToken(e){e&&e.length>0?this.token=e:this.token=void 0}getToken(){return this.token}parseToken(e){const t=this.cbor.decodeToken(e);if(void 0!==t){const e=t.res.uuid?Object.keys(t.res.uuid):[],s=Object.keys(t.res.chan),n=Object.keys(t.res.grp),r=t.pat.uuid?Object.keys(t.pat.uuid):[],i=Object.keys(t.pat.chan),a=Object.keys(t.pat.grp),o={version:t.v,timestamp:t.t,ttl:t.ttl,authorized_uuid:t.uuid,signature:t.sig},c=e.length>0,u=s.length>0,l=n.length>0;if(c||u||l){if(o.resources={},c){const s=o.resources.uuids={};e.forEach((e=>s[e]=this.extractPermissions(t.res.uuid[e])))}if(u){const e=o.resources.channels={};s.forEach((s=>e[s]=this.extractPermissions(t.res.chan[s])))}if(l){const e=o.resources.groups={};n.forEach((s=>e[s]=this.extractPermissions(t.res.grp[s])))}}const h=r.length>0,d=i.length>0,p=a.length>0;if(h||d||p){if(o.patterns={},h){const e=o.patterns.uuids={};r.forEach((s=>e[s]=this.extractPermissions(t.pat.uuid[s])))}if(d){const e=o.patterns.channels={};i.forEach((s=>e[s]=this.extractPermissions(t.pat.chan[s])))}if(p){const e=o.patterns.groups={};a.forEach((s=>e[s]=this.extractPermissions(t.pat.grp[s])))}}return t.meta&&Object.keys(t.meta).length>0&&(o.meta=t.meta),o}}extractPermissions(e){const t={read:!1,write:!1,manage:!1,delete:!1,get:!1,update:!1,join:!1};return 128&~e||(t.join=!0),64&~e||(t.update=!0),32&~e||(t.get=!0),8&~e||(t.delete=!0),4&~e||(t.manage=!0),2&~e||(t.write=!0),1&~e||(t.read=!0),t}}var re,ie;!function(e){e.GET="GET",e.POST="POST",e.PATCH="PATCH",e.DELETE="DELETE",e.LOCAL="LOCAL"}(re||(re={}));class ae{constructor(e,t,s,n){this.publishKey=e,this.secretKey=t,this.hasher=s,this.logger=n}signature(e){const t=e.path.startsWith("/publish")?re.GET:e.method;let s=`${t}\n${this.publishKey}\n${e.path}\n${this.queryParameters(e.queryParameters)}\n`;if(t===re.POST||t===re.PATCH){const t=e.body;let n;t&&t instanceof ArrayBuffer?n=ae.textDecoder.decode(t):t&&"object"!=typeof t&&(n=t),n&&(s+=n)}return this.logger.trace(this.constructor.name,(()=>({messageType:"text",message:`Request signature input:\n${s}`}))),`v2.${this.hasher(s,this.secretKey)}`.replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}queryParameters(e){return Object.keys(e).sort().map((t=>{const s=e[t];return Array.isArray(s)?s.sort().map((e=>`${t}=${H(e)}`)).join("&"):`${t}=${H(s)}`})).join("&")}}ae.textDecoder=new TextDecoder("utf-8");class oe{constructor(e){this.configuration=e;const{clientConfiguration:{keySet:t},shaHMAC:s}=e;t.secretKey&&s&&(this.signatureGenerator=new ae(t.publishKey,t.secretKey,s,this.logger))}get logger(){return this.configuration.clientConfiguration.logger()}makeSendable(e){const t=this.configuration.clientConfiguration.retryConfiguration,s=this.configuration.transport;if(void 0!==t){let n,r,i=!1,a=0;const o={abort:e=>{i=!0,n&&clearTimeout(n),r&&r.abort(e)}};return[new Promise(((o,c)=>{const u=()=>{if(i)return;const[l,d]=s.makeSendable(this.request(e));r=d;const p=(s,r)=>{const i=!r||r.category!==h.PNCancelledCategory,l=!s||s.status>=400;let d=-1;i&&l&&t.shouldRetry(e,s,null==r?void 0:r.category,a+1)&&(d=t.getDelay(a,s)),d>0?(a++,this.logger.warn(this.constructor.name,`HTTP request retry #${a} in ${d}ms.`),n=setTimeout((()=>u()),d)):s?o(s):r&&c(r)};l.then((e=>p(e))).catch((e=>p(void 0,e)))};u()})),r?o:void 0]}return s.makeSendable(this.request(e))}request(e){var t;const{clientConfiguration:s}=this.configuration;return(e=this.configuration.transport.request(e)).queryParameters||(e.queryParameters={}),s.useInstanceId&&(e.queryParameters.instanceid=s.getInstanceId()),e.queryParameters.uuid||(e.queryParameters.uuid=s.userId),s.useRequestId&&(e.queryParameters.requestid=e.identifier),e.queryParameters.pnsdk=this.generatePNSDK(),null!==(t=e.origin)&&void 0!==t||(e.origin=s.origin),this.authenticateRequest(e),this.signRequest(e),e}authenticateRequest(e){var t;if(e.path.startsWith("/v2/auth/")||e.path.startsWith("/v3/pam/")||e.path.startsWith("/time"))return;const{clientConfiguration:s,tokenManager:n}=this.configuration,r=null!==(t=n&&n.getToken())&&void 0!==t?t:s.authKey;r&&(e.queryParameters.auth=r)}signRequest(e){this.signatureGenerator&&!e.path.startsWith("/time")&&(e.queryParameters.timestamp=String(Math.floor((new Date).getTime()/1e3)),e.queryParameters.signature=this.signatureGenerator.signature(e))}generatePNSDK(){const{clientConfiguration:e}=this.configuration;if(e.sdkName)return e.sdkName;let t=`PubNub-JS-${e.sdkFamily}`;e.partnerId&&(t+=`-${e.partnerId}`),t+=`/${e.getVersion()}`;const s=e._getPnsdkSuffix(" ");return s.length>0&&(t+=s),t}}class ce{constructor(e,t="fetch"){this.logger=e,this.transport=t,e.debug(this.constructor.name,`Create with configuration:\n - transport: ${t}`),"fetch"!==t||window&&window.fetch||(e.warn(this.constructor.name,`'${t}' not supported in this browser. Fallback to the 'xhr' transport.`),this.transport="xhr"),"fetch"===this.transport&&(ce.originalFetch=fetch.bind(window),this.isFetchMonkeyPatched()&&(ce.originalFetch=ce.getOriginalFetch(),e.warn(this.constructor.name,"Native Web Fetch API 'fetch' function monkey patched."),this.isFetchMonkeyPatched(ce.originalFetch)?e.warn(this.constructor.name,"Unable receive native Web Fetch API. There can be issues with subscribe long-poll cancellation"):e.info(this.constructor.name,"Use native Web Fetch API 'fetch' implementation from iframe as APM workaround.")))}makeSendable(e){const t=new AbortController,s={abortController:t,abort:e=>{t.signal.aborted||(this.logger.trace(this.constructor.name,`On-demand request aborting: ${e}`),t.abort(e))}};return[this.webTransportRequestFromTransportRequest(e).then((t=>(this.logger.debug(this.constructor.name,(()=>({messageType:"network-request",message:e}))),this.sendRequest(t,s).then((e=>e.arrayBuffer().then((t=>[e,t])))).then((e=>{const s=e[1].byteLength>0?e[1]:void 0,{status:n,headers:r}=e[0],i={};r.forEach(((e,t)=>i[t]=e.toLowerCase()));const a={status:n,url:t.url,headers:i,body:s};if(this.logger.debug(this.constructor.name,(()=>({messageType:"network-response",message:a}))),n>=400)throw _.create(a);return a})).catch((t=>{const s=("string"==typeof t?t:t.message).toLowerCase();let n="string"==typeof t?new Error(t):t;throw s.includes("timeout")?this.logger.warn(this.constructor.name,(()=>({messageType:"network-request",message:e,details:"Timeout",canceled:!0}))):s.includes("cancel")||s.includes("abort")?(this.logger.debug(this.constructor.name,(()=>({messageType:"network-request",message:e,details:"Aborted",canceled:!0}))),n=new Error("Aborted"),n.name="AbortError"):s.includes("network")?this.logger.warn(this.constructor.name,(()=>({messageType:"network-request",message:e,details:"Network error",failed:!0}))):this.logger.warn(this.constructor.name,(()=>({messageType:"network-request",message:e,details:_.create(n).message,failed:!0}))),_.create(n)}))))),s]}request(e){return e}sendRequest(e,t){return i(this,void 0,void 0,(function*(){return"fetch"===this.transport?this.sendFetchRequest(e,t):this.sendXHRRequest(e,t)}))}sendFetchRequest(e,t){return i(this,void 0,void 0,(function*(){let s;const n=new Promise(((n,r)=>{s=setTimeout((()=>{clearTimeout(s),r(new Error("Request timeout")),t.abort("Cancel because of timeout")}),1e3*e.timeout)})),r=new Request(e.url,{method:e.method,headers:e.headers,redirect:"follow",body:e.body});return Promise.race([ce.originalFetch(r,{signal:t.abortController.signal,credentials:"omit",cache:"no-cache"}).then((e=>(s&&clearTimeout(s),e))),n])}))}sendXHRRequest(e,t){return i(this,void 0,void 0,(function*(){return new Promise(((s,n)=>{var r;const i=new XMLHttpRequest;i.open(e.method,e.url,!0);let a=!1;i.responseType="arraybuffer",i.timeout=1e3*e.timeout,t.abortController.signal.onabort=()=>{i.readyState!=XMLHttpRequest.DONE&&i.readyState!=XMLHttpRequest.UNSENT&&(a=!0,i.abort())},Object.entries(null!==(r=e.headers)&&void 0!==r?r:{}).forEach((([e,t])=>i.setRequestHeader(e,t))),i.onabort=()=>{n(new Error("Aborted"))},i.ontimeout=()=>{n(new Error("Request timeout"))},i.onerror=()=>{if(!a){const t=this.transportResponseFromXHR(e.url,i);n(new Error(_.create(t).message))}},i.onload=()=>{const e=new Headers;i.getAllResponseHeaders().split("\r\n").forEach((t=>{const[s,n]=t.split(": ");s.length>1&&n.length>1&&e.append(s,n)})),s(new Response(i.response,{status:i.status,headers:e,statusText:i.statusText}))},i.send(e.body)}))}))}webTransportRequestFromTransportRequest(e){return i(this,void 0,void 0,(function*(){let t,s=e.path;if(e.formData&&e.formData.length>0){e.queryParameters={};const s=e.body,n=new FormData;for(const{key:t,value:s}of e.formData)n.append(t,s);try{const e=yield s.toArrayBuffer();n.append("file",new Blob([e],{type:"application/octet-stream"}),s.name)}catch(e){this.logger.warn(this.constructor.name,(()=>({messageType:"error",message:e})));try{const e=yield s.toFileUri();n.append("file",e,s.name)}catch(e){this.logger.error(this.constructor.name,(()=>({messageType:"error",message:e})))}}t=n}else if(e.body&&("string"==typeof e.body||e.body instanceof ArrayBuffer))if(e.compressible&&"undefined"!=typeof CompressionStream){const s="string"==typeof e.body?ce.encoder.encode(e.body):e.body,n=s.byteLength,r=new ReadableStream({start(e){e.enqueue(s),e.close()}});t=yield new Response(r.pipeThrough(new CompressionStream("deflate"))).arrayBuffer(),this.logger.trace(this.constructor.name,(()=>{const e=t.byteLength,s=(e/n).toFixed(2);return{messageType:"text",message:`Body of ${n} bytes, compressed by ${s}x to ${e} bytes.`}}))}else t=e.body;return e.queryParameters&&0!==Object.keys(e.queryParameters).length&&(s=`${s}?${V(e.queryParameters)}`),{url:`${e.origin}${s}`,method:e.method,headers:e.headers,timeout:e.timeout,body:t}}))}isFetchMonkeyPatched(e){return!(null!=e?e:fetch).toString().includes("[native code]")&&"fetch"!==fetch.name}transportResponseFromXHR(e,t){const s=t.getAllResponseHeaders().split("\n"),n={};for(const e of s){const[t,s]=e.trim().split(":");t&&s&&(n[t.toLowerCase()]=s.trim())}return{status:t.status,url:e,headers:n,body:t.response}}static getOriginalFetch(){let e=document.querySelector('iframe[name="pubnub-context-unpatched-fetch"]');return e||(e=document.createElement("iframe"),e.style.display="none",e.name="pubnub-context-unpatched-fetch",e.src="about:blank",document.body.appendChild(e)),e.contentWindow?e.contentWindow.fetch.bind(e.contentWindow):fetch}}ce.encoder=new TextEncoder,ce.decoder=new TextDecoder;class ue{constructor(e){this.params=e,this.requestIdentifier=K.createUUID(),this._cancellationController=null}get cancellationController(){return this._cancellationController}set cancellationController(e){this._cancellationController=e}abort(e){this&&this.cancellationController&&this.cancellationController.abort(e)}operation(){throw Error("Should be implemented by subclass.")}validate(){}parse(e){return i(this,void 0,void 0,(function*(){return this.deserializeResponse(e)}))}request(){var e,t,s,n,r,i;const a={method:null!==(t=null===(e=this.params)||void 0===e?void 0:e.method)&&void 0!==t?t:re.GET,path:this.path,queryParameters:this.queryParameters,cancellable:null!==(n=null===(s=this.params)||void 0===s?void 0:s.cancellable)&&void 0!==n&&n,compressible:null!==(i=null===(r=this.params)||void 0===r?void 0:r.compressible)&&void 0!==i&&i,timeout:10,identifier:this.requestIdentifier},o=this.headers;if(o&&(a.headers=o),a.method===re.POST||a.method===re.PATCH){const[e,t]=[this.body,this.formData];t&&(a.formData=t),e&&(a.body=e)}return a}get headers(){var e,t;return Object.assign({"Accept-Encoding":"gzip, deflate"},null!==(t=null===(e=this.params)||void 0===e?void 0:e.compressible)&&void 0!==t&&t?{"Content-Encoding":"deflate"}:{})}get path(){throw Error("`path` getter should be implemented by subclass.")}get queryParameters(){return{}}get formData(){}get body(){}deserializeResponse(e){const t=ue.decoder.decode(e.body),s=e.headers["content-type"];let n;if(!s||-1===s.indexOf("javascript")&&-1===s.indexOf("json"))throw new d("Service response error, check status for details",g(t,e.status));try{n=JSON.parse(t)}catch(s){throw console.error("Error parsing JSON response:",s),new d("Service response error, check status for details",g(t,e.status))}if("status"in n&&"number"==typeof n.status&&n.status>=400)throw _.create(e);return n}}ue.decoder=new TextDecoder,function(e){e.PNPublishOperation="PNPublishOperation",e.PNSignalOperation="PNSignalOperation",e.PNSubscribeOperation="PNSubscribeOperation",e.PNUnsubscribeOperation="PNUnsubscribeOperation",e.PNWhereNowOperation="PNWhereNowOperation",e.PNHereNowOperation="PNHereNowOperation",e.PNGlobalHereNowOperation="PNGlobalHereNowOperation",e.PNSetStateOperation="PNSetStateOperation",e.PNGetStateOperation="PNGetStateOperation",e.PNHeartbeatOperation="PNHeartbeatOperation",e.PNAddMessageActionOperation="PNAddActionOperation",e.PNRemoveMessageActionOperation="PNRemoveMessageActionOperation",e.PNGetMessageActionsOperation="PNGetMessageActionsOperation",e.PNTimeOperation="PNTimeOperation",e.PNHistoryOperation="PNHistoryOperation",e.PNDeleteMessagesOperation="PNDeleteMessagesOperation",e.PNFetchMessagesOperation="PNFetchMessagesOperation",e.PNMessageCounts="PNMessageCountsOperation",e.PNGetAllUUIDMetadataOperation="PNGetAllUUIDMetadataOperation",e.PNGetUUIDMetadataOperation="PNGetUUIDMetadataOperation",e.PNSetUUIDMetadataOperation="PNSetUUIDMetadataOperation",e.PNRemoveUUIDMetadataOperation="PNRemoveUUIDMetadataOperation",e.PNGetAllChannelMetadataOperation="PNGetAllChannelMetadataOperation",e.PNGetChannelMetadataOperation="PNGetChannelMetadataOperation",e.PNSetChannelMetadataOperation="PNSetChannelMetadataOperation",e.PNRemoveChannelMetadataOperation="PNRemoveChannelMetadataOperation",e.PNGetMembersOperation="PNGetMembersOperation",e.PNSetMembersOperation="PNSetMembersOperation",e.PNGetMembershipsOperation="PNGetMembershipsOperation",e.PNSetMembershipsOperation="PNSetMembershipsOperation",e.PNListFilesOperation="PNListFilesOperation",e.PNGenerateUploadUrlOperation="PNGenerateUploadUrlOperation",e.PNPublishFileOperation="PNPublishFileOperation",e.PNPublishFileMessageOperation="PNPublishFileMessageOperation",e.PNGetFileUrlOperation="PNGetFileUrlOperation",e.PNDownloadFileOperation="PNDownloadFileOperation",e.PNDeleteFileOperation="PNDeleteFileOperation",e.PNAddPushNotificationEnabledChannelsOperation="PNAddPushNotificationEnabledChannelsOperation",e.PNRemovePushNotificationEnabledChannelsOperation="PNRemovePushNotificationEnabledChannelsOperation",e.PNPushNotificationEnabledChannelsOperation="PNPushNotificationEnabledChannelsOperation",e.PNRemoveAllPushNotificationsOperation="PNRemoveAllPushNotificationsOperation",e.PNChannelGroupsOperation="PNChannelGroupsOperation",e.PNRemoveGroupOperation="PNRemoveGroupOperation",e.PNChannelsForGroupOperation="PNChannelsForGroupOperation",e.PNAddChannelsToGroupOperation="PNAddChannelsToGroupOperation",e.PNRemoveChannelsFromGroupOperation="PNRemoveChannelsFromGroupOperation",e.PNAccessManagerGrant="PNAccessManagerGrant",e.PNAccessManagerGrantToken="PNAccessManagerGrantToken",e.PNAccessManagerAudit="PNAccessManagerAudit",e.PNAccessManagerRevokeToken="PNAccessManagerRevokeToken",e.PNHandshakeOperation="PNHandshakeOperation",e.PNReceiveMessagesOperation="PNReceiveMessagesOperation"}(ie||(ie={}));var le=ie;var he;!function(e){e[e.Presence=-2]="Presence",e[e.Message=-1]="Message",e[e.Signal=1]="Signal",e[e.AppContext=2]="AppContext",e[e.MessageAction=3]="MessageAction",e[e.Files=4]="Files"}(he||(he={}));class de extends ue{constructor(e){var t,s,n,r,i,a;super({cancellable:!0}),this.parameters=e,null!==(t=(r=this.parameters).withPresence)&&void 0!==t||(r.withPresence=false),null!==(s=(i=this.parameters).channelGroups)&&void 0!==s||(i.channelGroups=[]),null!==(n=(a=this.parameters).channels)&&void 0!==n||(a.channels=[])}operation(){return le.PNSubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;return e?t||s?void 0:"`channels` and `channelGroups` both should not be empty":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){let t,s;try{s=ue.decoder.decode(e.body);t=JSON.parse(s)}catch(e){console.error("Error parsing JSON response:",e)}if(!t)throw new d("Service response error, check status for details",g(s,e.status));const n=t.m.filter((e=>{const t=void 0===e.b?e.c:e.b;return this.parameters.channels&&this.parameters.channels.includes(t)||this.parameters.channelGroups&&this.parameters.channelGroups.includes(t)})).map((e=>{let{e:t}=e;return null!=t||(t=e.c.endsWith("-pnpres")?he.Presence:he.Message),t!=he.Signal&&"string"==typeof e.d?t==he.Message?{type:he.Message,data:this.messageFromEnvelope(e)}:{type:he.Files,data:this.fileFromEnvelope(e)}:t==he.Message?{type:he.Message,data:this.messageFromEnvelope(e)}:t===he.Presence?{type:he.Presence,data:this.presenceEventFromEnvelope(e)}:t==he.Signal?{type:he.Signal,data:this.signalFromEnvelope(e)}:t===he.AppContext?{type:he.AppContext,data:this.appContextFromEnvelope(e)}:t===he.MessageAction?{type:he.MessageAction,data:this.messageActionFromEnvelope(e)}:{type:he.Files,data:this.fileFromEnvelope(e)}}));return{cursor:{timetoken:t.t.t,region:t.t.r},messages:n}}))}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{accept:"text/javascript"})}presenceEventFromEnvelope(e){var t;const{d:s}=e,[n,r]=this.subscriptionChannelFromEnvelope(e),i=n.replace("-pnpres",""),a=null!==r?i:null,o=null!==r?r:i;return"string"!=typeof s&&("data"in s?(s.state=s.data,delete s.data):"action"in s&&"interval"===s.action&&(s.hereNowRefresh=null!==(t=s.here_now_refresh)&&void 0!==t&&t,delete s.here_now_refresh)),Object.assign({channel:i,subscription:r,actualChannel:a,subscribedChannel:o,timetoken:e.p.t},s)}messageFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d),i={channel:t,subscription:s,actualChannel:null!==s?t:null,subscribedChannel:null!==s?s:t,timetoken:e.p.t,publisher:e.i,message:n};return e.u&&(i.userMetadata=e.u),e.cmt&&(i.customMessageType=e.cmt),r&&(i.error=r),i}signalFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,message:e.d};return e.u&&(n.userMetadata=e.u),e.cmt&&(n.customMessageType=e.cmt),n}messageActionFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,publisher:e.i,event:n.event,data:Object.assign(Object.assign({},n.data),{uuid:e.i})}}appContextFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),n=e.d;return{channel:t,subscription:s,timetoken:e.p.t,message:n}}fileFromEnvelope(e){const[t,s]=this.subscriptionChannelFromEnvelope(e),[n,r]=this.decryptedData(e.d);let i=r;const a={channel:t,subscription:s,timetoken:e.p.t,publisher:e.i};return e.u&&(a.userMetadata=e.u),n?"string"==typeof n?null!=i||(i="Unexpected file information payload data type."):(a.message=n.message,n.file&&(a.file={id:n.file.id,name:n.file.name,url:this.parameters.getFileUrl({id:n.file.id,name:n.file.name,channel:t})})):null!=i||(i="File information payload is missing."),e.cmt&&(a.customMessageType=e.cmt),i&&(a.error=i),a}subscriptionChannelFromEnvelope(e){return[e.c,void 0===e.b?e.c:e.b]}decryptedData(e){if(!this.parameters.crypto||"string"!=typeof e)return[e,void 0];let t,s;try{const s=this.parameters.crypto.decrypt(e);t=s instanceof ArrayBuffer?JSON.parse(pe.decoder.decode(s)):s}catch(e){t=null,s=`Error while decrypting message content: ${e.message}`}return[null!=t?t:e,s]}}class pe extends de{get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/subscribe/${t}/${B(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,heartbeat:s,state:n,timetoken:r,region:i}=this.parameters,a={};return e&&e.length>0&&(a["channel-group"]=e.sort().join(",")),t&&t.length>0&&(a["filter-expr"]=t),s&&(a.heartbeat=s),n&&Object.keys(n).length>0&&(a.state=JSON.stringify(n)),void 0!==r&&"string"==typeof r?r.length>0&&"0"!==r&&(a.tt=r):void 0!==r&&r>0&&(a.tt=r),i&&(a.tr=i),a}}class ge{constructor(){this.hasListeners=!1,this.listeners=[{count:-1,listener:{}}]}set onStatus(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"status"})}set onMessage(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"message"})}set onPresence(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"presence"})}set onSignal(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"signal"})}set onObjects(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"objects"})}set onMessageAction(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"messageAction"})}set onFile(e){this.updateTypeOrObjectListener({add:!!e,listener:e,type:"file"})}handleEvent(e){if(this.hasListeners)if(e.type===he.Message)this.announce("message",e.data);else if(e.type===he.Signal)this.announce("signal",e.data);else if(e.type===he.Presence)this.announce("presence",e.data);else if(e.type===he.AppContext){const{data:t}=e,{message:s}=t;if(this.announce("objects",t),"uuid"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:a,type:o}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"user"})});this.announce("user",u)}else if("channel"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:a,type:o}=s,c=r(s,["event","type"]),u=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",type:"space"})});this.announce("space",u)}else if("membership"===s.type){const{message:e,channel:n}=t,i=r(t,["message","channel"]),{event:a,data:o}=s,c=r(s,["event","data"]),{uuid:u,channel:l}=o,h=r(o,["uuid","channel"]),d=Object.assign(Object.assign({},i),{spaceId:n,message:Object.assign(Object.assign({},c),{event:"set"===a?"updated":"removed",data:Object.assign(Object.assign({},h),{user:u,space:l})})});this.announce("membership",d)}}else e.type===he.MessageAction?this.announce("messageAction",e.data):e.type===he.Files&&this.announce("file",e.data)}handleStatus(e){this.hasListeners&&this.announce("status",e)}addListener(e){this.updateTypeOrObjectListener({add:!0,listener:e})}removeListener(e){this.updateTypeOrObjectListener({add:!1,listener:e})}removeAllListeners(){this.listeners=[{count:-1,listener:{}}],this.hasListeners=!1}updateTypeOrObjectListener(e){if(e.type)"function"==typeof e.listener?this.listeners[0].listener[e.type]=e.listener:delete this.listeners[0].listener[e.type];else if(e.listener&&"function"!=typeof e.listener){let t,s=!1;for(t of this.listeners)if(t.listener===e.listener){e.add?(t.count++,s=!0):(t.count--,0===t.count&&this.listeners.splice(this.listeners.indexOf(t),1));break}e.add&&!s&&this.listeners.push({count:1,listener:e.listener})}this.hasListeners=this.listeners.length>1||Object.keys(this.listeners[0]).length>0}announce(e,t){this.listeners.forEach((({listener:s})=>{const n=s[e];n&&n(t)}))}}class be{constructor(e){this.time=e}onReconnect(e){this.callback=e}startPolling(){this.timeTimer=setInterval((()=>this.callTime()),3e3)}stopPolling(){this.timeTimer&&clearInterval(this.timeTimer),this.timeTimer=null}callTime(){this.time((e=>{e.error||(this.stopPolling(),this.callback&&this.callback())}))}}class me{constructor(e){this.config=e,e.logger().debug(this.constructor.name,(()=>({messageType:"object",message:{maximumCacheSize:e.maximumCacheSize},details:"Create with configuration:"}))),this.maximumCacheSize=e.maximumCacheSize,this.hashHistory=[]}getKey(e){var t;return`${e.timetoken}-${this.hashCode(JSON.stringify(null!==(t=e.message)&&void 0!==t?t:"")).toString()}`}isDuplicate(e){return this.hashHistory.includes(this.getKey(e))}addEntry(e){this.hashHistory.length>=this.maximumCacheSize&&this.hashHistory.shift(),this.hashHistory.push(this.getKey(e))}clearHistory(){this.hashHistory=[]}hashCode(e){let t=0;if(0===e.length)return t;for(let s=0;s{this.pendingChannelSubscriptions.add(e),this.channels[e]={},r&&(this.presenceChannels[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannels[e]={})})),null==s||s.forEach((e=>{this.pendingChannelGroupSubscriptions.add(e),this.channelGroups[e]={},r&&(this.presenceChannelGroups[e]={}),(i||this.configuration.getHeartbeatInterval())&&(this.heartbeatChannelGroups[e]={})})),this.subscriptionStatusAnnounced=!1,this.reconnect()}unsubscribe(e,t=!1){let{channels:s,channelGroups:n}=e;const i=new Set,a=new Set;null==s||s.forEach((e=>{e in this.channels&&(delete this.channels[e],a.add(e),e in this.heartbeatChannels&&delete this.heartbeatChannels[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannels&&(delete this.presenceChannels[e],a.add(e))})),null==n||n.forEach((e=>{e in this.channelGroups&&(delete this.channelGroups[e],i.add(e),e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]),e in this.presenceState&&delete this.presenceState[e],e in this.presenceChannelGroups&&(delete this.presenceChannelGroups[e],i.add(e))})),0===a.size&&0===i.size||(!1!==this.configuration.suppressLeaveEvents||t||(n=Array.from(i),s=Array.from(a),this.leaveCall({channels:s,channelGroups:n},(e=>{const{error:t}=e,i=r(e,["error"]);let a;t&&(e.errorData&&"object"==typeof e.errorData&&"message"in e.errorData&&"string"==typeof e.errorData.message?a=e.errorData.message:"message"in e&&"string"==typeof e.message&&(a=e.message)),this.emitStatus(Object.assign(Object.assign({},i),{error:null!=a&&a,affectedChannels:s,affectedChannelGroups:n,currentTimetoken:this.currentTimetoken,lastTimetoken:this.lastTimetoken}))}))),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.referenceTimetoken=null,this.storedTimetoken=null,this.region=null,this.reconnectionManager.stopPolling()),this.reconnect(!0))}unsubscribeAll(e=!1){this.unsubscribe({channels:this.subscribedChannels,channelGroups:this.subscribedChannelGroups},e)}startSubscribeLoop(e=!1){this.stopSubscribeLoop();const t=[...Object.keys(this.channelGroups)],s=[...Object.keys(this.channels)];Object.keys(this.presenceChannelGroups).forEach((e=>t.push(`${e}-pnpres`))),Object.keys(this.presenceChannels).forEach((e=>s.push(`${e}-pnpres`))),0===s.length&&0===t.length||(this.subscribeCall(Object.assign(Object.assign({channels:s,channelGroups:t,state:this.presenceState,heartbeat:this.configuration.getPresenceTimeout(),timetoken:this.currentTimetoken},null!==this.region?{region:this.region}:{}),this.configuration.filterExpression?{filterExpression:this.configuration.filterExpression}:{}),((e,t)=>{this.processSubscribeResponse(e,t)})),!e&&this.configuration.useSmartHeartbeat&&this.startHeartbeatTimer())}stopSubscribeLoop(){this._subscribeAbort&&(this._subscribeAbort(),this._subscribeAbort=null)}processSubscribeResponse(e,t){if(e.error){if("object"==typeof e.errorData&&"name"in e.errorData&&"AbortError"===e.errorData.name||e.category===h.PNCancelledCategory)return;return void(e.category===h.PNTimeoutCategory?this.startSubscribeLoop():e.category===h.PNNetworkIssuesCategory||e.category===h.PNMalformedResponseCategory?(this.disconnect(),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.emitStatus({category:h.PNNetworkDownCategory})),this.reconnectionManager.onReconnect((()=>{this.configuration.autoNetworkDetection&&!this.isOnline&&(this.isOnline=!0,this.emitStatus({category:h.PNNetworkUpCategory})),this.reconnect(),this.subscriptionStatusAnnounced=!0;const t={category:h.PNReconnectedCategory,operation:e.operation,lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.emitStatus(t)})),this.reconnectionManager.startPolling(),this.emitStatus(Object.assign(Object.assign({},e),{category:h.PNNetworkIssuesCategory}))):e.category===h.PNBadRequestCategory?(this.stopHeartbeatTimer(),this.emitStatus(e)):this.emitStatus(e))}if(this.referenceTimetoken=X(t.cursor.timetoken,this.storedTimetoken),this.storedTimetoken?(this.currentTimetoken=this.storedTimetoken,this.storedTimetoken=null):(this.lastTimetoken=this.currentTimetoken,this.currentTimetoken=t.cursor.timetoken),!this.subscriptionStatusAnnounced){const t={category:h.PNConnectedCategory,operation:e.operation,affectedChannels:Array.from(this.pendingChannelSubscriptions),subscribedChannels:this.subscribedChannels,affectedChannelGroups:Array.from(this.pendingChannelGroupSubscriptions),lastTimetoken:this.lastTimetoken,currentTimetoken:this.currentTimetoken};this.subscriptionStatusAnnounced=!0,this.emitStatus(t),this.pendingChannelGroupSubscriptions.clear(),this.pendingChannelSubscriptions.clear()}const{messages:s}=t,{requestMessageCountThreshold:n,dedupeOnSubscribe:r}=this.configuration;n&&s.length>=n&&this.emitStatus({category:h.PNRequestMessageCountExceededCategory,operation:e.operation});try{const e={timetoken:this.currentTimetoken,region:this.region?this.region:void 0};this.configuration.logger().debug(this.constructor.name,(()=>({messageType:"object",message:s.map((e=>{const t=e.type===he.Message||e.type===he.Signal?Y(e.data.message):void 0;return t?{type:e.type,data:Object.assign(Object.assign({},e.data),{pn_mfp:t})}:e})),details:"Received events:"}))),s.forEach((t=>{if(r&&"message"in t.data&&"timetoken"in t.data){if(this.dedupingManager.isDuplicate(t.data))return void this.configuration.logger().warn(this.constructor.name,(()=>({messageType:"object",message:t.data,details:"Duplicate message detected (skipped):"})));this.dedupingManager.addEntry(t.data)}this.emitEvent(e,t)}))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.emitStatus(t)}this.region=t.cursor.region,this.startSubscribeLoop()}setState(e){const{state:t,channels:s,channelGroups:n}=e;null==s||s.forEach((e=>e in this.channels&&(this.presenceState[e]=t))),null==n||n.forEach((e=>e in this.channelGroups&&(this.presenceState[e]=t)))}changePresence(e){const{connected:t,channels:s,channelGroups:n}=e;t?(null==s||s.forEach((e=>this.heartbeatChannels[e]={})),null==n||n.forEach((e=>this.heartbeatChannelGroups[e]={}))):(null==s||s.forEach((e=>{e in this.heartbeatChannels&&delete this.heartbeatChannels[e]})),null==n||n.forEach((e=>{e in this.heartbeatChannelGroups&&delete this.heartbeatChannelGroups[e]})),!1===this.configuration.suppressLeaveEvents&&this.leaveCall({channels:s,channelGroups:n},(e=>this.emitStatus(e)))),this.reconnect()}startHeartbeatTimer(){this.stopHeartbeatTimer();const e=this.configuration.getHeartbeatInterval();e&&0!==e&&(this.configuration.useSmartHeartbeat||this.sendHeartbeat(),this.heartbeatTimer=setInterval((()=>this.sendHeartbeat()),1e3*e))}stopHeartbeatTimer(){this.heartbeatTimer&&(clearInterval(this.heartbeatTimer),this.heartbeatTimer=null)}sendHeartbeat(){const e=Object.keys(this.heartbeatChannelGroups),t=Object.keys(this.heartbeatChannels);0===t.length&&0===e.length||this.heartbeatCall({channels:t,channelGroups:e,heartbeat:this.configuration.getPresenceTimeout(),state:this.presenceState},(e=>{e.error&&this.configuration.announceFailedHeartbeats&&this.emitStatus(e),e.error&&this.configuration.autoNetworkDetection&&this.isOnline&&(this.isOnline=!1,this.disconnect(),this.emitStatus({category:h.PNNetworkDownCategory}),this.reconnect()),!e.error&&this.configuration.announceSuccessfulHeartbeats&&this.emitStatus(e)}))}}class fe{constructor(e,t,s){this._payload=e,this.setDefaultPayloadStructure(),this.title=t,this.body=s}get payload(){return this._payload}set title(e){this._title=e}set subtitle(e){this._subtitle=e}set body(e){this._body=e}set badge(e){this._badge=e}set sound(e){this._sound=e}setDefaultPayloadStructure(){}toObject(){return{}}}class ve extends fe{constructor(){super(...arguments),this._apnsPushType="apns",this._isSilent=!1}get payload(){return this._payload}set configurations(e){e&&e.length&&(this._configurations=e)}get notification(){return this.payload.aps}get title(){return this._title}set title(e){e&&e.length&&(this.payload.aps.alert.title=e,this._title=e)}get subtitle(){return this._subtitle}set subtitle(e){e&&e.length&&(this.payload.aps.alert.subtitle=e,this._subtitle=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.aps.alert.body=e,this._body=e)}get badge(){return this._badge}set badge(e){null!=e&&(this.payload.aps.badge=e,this._badge=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.aps.sound=e,this._sound=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.aps={alert:{}}}toObject(){const e=Object.assign({},this.payload),{aps:t}=e;let{alert:s}=t;if(this._isSilent&&(t["content-available"]=1),"apns2"===this._apnsPushType){if(!this._configurations||!this._configurations.length)throw new ReferenceError("APNS2 configuration is missing");const t=[];this._configurations.forEach((e=>{t.push(this.objectFromAPNS2Configuration(e))})),t.length&&(e.pn_push=t)}return s&&Object.keys(s).length||delete t.alert,this._isSilent&&(delete t.alert,delete t.badge,delete t.sound,s={}),this._isSilent||s&&Object.keys(s).length?e:null}objectFromAPNS2Configuration(e){if(!e.targets||!e.targets.length)throw new ReferenceError("At least one APNS2 target should be provided");const{collapseId:t,expirationDate:s}=e,n={auth_method:"token",targets:e.targets.map((e=>this.objectFromAPNSTarget(e))),version:"v2"};return t&&t.length&&(n.collapse_id=t),s&&(n.expiration=s.toISOString()),n}objectFromAPNSTarget(e){if(!e.topic||!e.topic.length)throw new TypeError("Target 'topic' undefined.");const{topic:t,environment:s="development",excludedDevices:n=[]}=e,r={topic:t,environment:s};return n.length&&(r.excluded_devices=n),r}}class Se extends fe{get payload(){return this._payload}get notification(){return this.payload.notification}get data(){return this.payload.data}get title(){return this._title}set title(e){e&&e.length&&(this.payload.notification.title=e,this._title=e)}get body(){return this._body}set body(e){e&&e.length&&(this.payload.notification.body=e,this._body=e)}get sound(){return this._sound}set sound(e){e&&e.length&&(this.payload.notification.sound=e,this._sound=e)}get icon(){return this._icon}set icon(e){e&&e.length&&(this.payload.notification.icon=e,this._icon=e)}get tag(){return this._tag}set tag(e){e&&e.length&&(this.payload.notification.tag=e,this._tag=e)}set silent(e){this._isSilent=e}setDefaultPayloadStructure(){this.payload.notification={},this.payload.data={}}toObject(){let e=Object.assign({},this.payload.data),t=null;const s={};if(Object.keys(this.payload).length>2){const t=r(this.payload,["notification","data"]);e=Object.assign(Object.assign({},e),t)}return this._isSilent?e.notification=this.payload.notification:t=this.payload.notification,Object.keys(e).length&&(s.data=e),t&&Object.keys(t).length&&(s.notification=t),Object.keys(s).length?s:null}}class we{constructor(e,t){this._payload={apns:{},fcm:{}},this._title=e,this._body=t,this.apns=new ve(this._payload.apns,e,t),this.fcm=new Se(this._payload.fcm,e,t)}set debugging(e){this._debugging=e}get title(){return this._title}get subtitle(){return this._subtitle}set subtitle(e){this._subtitle=e,this.apns.subtitle=e,this.fcm.subtitle=e}get body(){return this._body}get badge(){return this._badge}set badge(e){this._badge=e,this.apns.badge=e,this.fcm.badge=e}get sound(){return this._sound}set sound(e){this._sound=e,this.apns.sound=e,this.fcm.sound=e}buildPayload(e){const t={};if(e.includes("apns")||e.includes("apns2")){this.apns._apnsPushType=e.includes("apns")?"apns":"apns2";const s=this.apns.toObject();s&&Object.keys(s).length&&(t.pn_apns=s)}if(e.includes("fcm")){const e=this.fcm.toObject();e&&Object.keys(e).length&&(t.pn_gcm=e)}return Object.keys(t).length&&this._debugging&&(t.pn_debug=!0),t}}class Oe{constructor(e=!1){this.sync=e,this.listeners=new Set}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(e){const t=()=>{this.listeners.forEach((t=>{t(e)}))};this.sync?t():setTimeout(t,0)}}class ke{transition(e,t){var s;if(this.transitionMap.has(t.type))return null===(s=this.transitionMap.get(t.type))||void 0===s?void 0:s(e,t)}constructor(e){this.label=e,this.transitionMap=new Map,this.enterEffects=[],this.exitEffects=[]}on(e,t){return this.transitionMap.set(e,t),this}with(e,t){return[this,e,null!=t?t:[]]}onEnter(e){return this.enterEffects.push(e),this}onExit(e){return this.exitEffects.push(e),this}}class Ce extends Oe{constructor(e){super(!0),this.logger=e,this._pendingEvents=[],this._inTransition=!1}get currentState(){return this._currentState}get currentContext(){return this._currentContext}describe(e){return new ke(e)}start(e,t){this._currentState=e,this._currentContext=t,this.notify({type:"engineStarted",state:e,context:t})}transition(e){if(!this._currentState)throw this.logger.error(this.constructor.name,"Finite state machine is not started"),new Error("Start the engine first");if(this._inTransition)return this.logger.trace(this.constructor.name,(()=>({messageType:"object",message:e,details:"Event engine in transition. Enqueue received event:"}))),void this._pendingEvents.push(e);this._inTransition=!0,this.logger.trace(this.constructor.name,(()=>({messageType:"object",message:e,details:"Event engine received event:"}))),this.notify({type:"eventReceived",event:e});const t=this._currentState.transition(this._currentContext,e);if(t){const[s,n,r]=t;this.logger.trace(this.constructor.name,`Exiting state: ${this._currentState.label}`);for(const e of this._currentState.exitEffects)this.notify({type:"invocationDispatched",invocation:e(this._currentContext)});this.logger.trace(this.constructor.name,(()=>({messageType:"object",details:`Entering '${s.label}' state with context:`,message:n})));const i=this._currentState;this._currentState=s;const a=this._currentContext;this._currentContext=n,this.notify({type:"transitionDone",fromState:i,fromContext:a,toState:s,toContext:n,event:e});for(const e of r)this.notify({type:"invocationDispatched",invocation:e});for(const e of this._currentState.enterEffects)this.notify({type:"invocationDispatched",invocation:e(this._currentContext)});if(this._inTransition=!1,this._pendingEvents.length>0){const e=this._pendingEvents.shift();e&&(this.logger.trace(this.constructor.name,(()=>({messageType:"object",message:e,details:"De-queueing pending event:"}))),this.transition(e))}}else this.logger.warn(this.constructor.name,`No transition from '${this._currentState.label}' found for event: ${e.type}`)}}class Pe{constructor(e,t){this.dependencies=e,this.logger=t,this.instances=new Map,this.handlers=new Map}on(e,t){this.handlers.set(e,t)}dispatch(e){if(this.logger.trace(this.constructor.name,`Process invocation: ${e.type}`),"CANCEL"===e.type){if(this.instances.has(e.payload)){const t=this.instances.get(e.payload);null==t||t.cancel(),this.instances.delete(e.payload)}return}const t=this.handlers.get(e.type);if(!t)throw this.logger.error(this.constructor.name,`Unhandled invocation '${e.type}'`),new Error(`Unhandled invocation '${e.type}'`);const s=t(e.payload,this.dependencies);this.logger.trace(this.constructor.name,(()=>({messageType:"object",details:"Call invocation handler with parameters:",message:e.payload,ignoredKeys:["abortSignal"]}))),e.managed&&this.instances.set(e.type,s),s.start()}dispose(){for(const[e,t]of this.instances.entries())t.cancel(),this.instances.delete(e)}}function je(e,t){const s=function(...s){return{type:e,payload:null==t?void 0:t(...s)}};return s.type=e,s}function Ee(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!1});return s.type=e,s}function Ne(e,t){const s=(...s)=>({type:e,payload:t(...s),managed:!0});return s.type=e,s.cancel={type:"CANCEL",payload:e,managed:!1},s}class Te extends Error{constructor(){super("The operation was aborted."),this.name="AbortError",Object.setPrototypeOf(this,new.target.prototype)}}class _e extends Oe{constructor(){super(...arguments),this._aborted=!1}get aborted(){return this._aborted}throwIfAborted(){if(this._aborted)throw new Te}abort(){this._aborted=!0,this.notify(new Te)}}class Ie{constructor(e,t){this.payload=e,this.dependencies=t}}class Me extends Ie{constructor(e,t,s){super(e,t),this.asyncFunction=s,this.abortSignal=new _e}start(){this.asyncFunction(this.payload,this.abortSignal,this.dependencies).catch((e=>{}))}cancel(){this.abortSignal.abort()}}const Ae=e=>(t,s)=>new Me(t,s,e),Ue=Ne("HEARTBEAT",((e,t)=>({channels:e,groups:t}))),$e=Ee("LEAVE",((e,t)=>({channels:e,groups:t}))),Re=Ee("EMIT_STATUS",(e=>e)),Fe=Ne("WAIT",(()=>({}))),De=je("RECONNECT",(()=>({}))),xe=je("DISCONNECT",((e=!1)=>({isOffline:e}))),Ge=je("JOINED",((e,t)=>({channels:e,groups:t}))),qe=je("LEFT",((e,t)=>({channels:e,groups:t}))),Ke=je("LEFT_ALL",((e=!1)=>({isOffline:e}))),Le=je("HEARTBEAT_SUCCESS",(e=>({statusCode:e}))),He=je("HEARTBEAT_FAILURE",(e=>e)),Be=je("TIMES_UP",(()=>({})));class We extends Pe{constructor(e,t){super(t,t.config.logger()),this.on(Ue.type,Ae(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeat:n,presenceState:r,config:i}){try{yield n(Object.assign(Object.assign({channels:t.channels,channelGroups:t.groups},i.maintainPresenceState&&{state:r}),{heartbeat:i.presenceTimeout}));e.transition(Le(200))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;e.transition(He(t))}}}))))),this.on($e.type,Ae(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{leave:s,config:n}){if(!n.suppressLeaveEvents)try{s({channels:e.channels,channelGroups:e.groups})}catch(e){}}))))),this.on(Fe.type,Ae(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{heartbeatDelay:n}){return s.throwIfAborted(),yield n(),s.throwIfAborted(),e.transition(Be())}))))),this.on(Re.type,Ae(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s,config:n}){n.announceFailedHeartbeats&&!0===(null==e?void 0:e.error)?s(Object.assign(Object.assign({},e),{operation:le.PNHeartbeatOperation})):n.announceSuccessfulHeartbeats&&200===e.statusCode&&s(Object.assign(Object.assign({},e),{error:!1,operation:le.PNHeartbeatOperation,category:h.PNAcknowledgmentCategory}))})))))}}const ze=new ke("HEARTBEAT_STOPPED");ze.on(Ge.type,((e,t)=>ze.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),ze.on(qe.type,((e,t)=>ze.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))}))),ze.on(De.type,((e,t)=>Xe.with({channels:e.channels,groups:e.groups}))),ze.on(Ke.type,((e,t)=>Qe.with(void 0)));const Ve=new ke("HEARTBEAT_COOLDOWN");Ve.onEnter((()=>Fe())),Ve.onExit((()=>Fe.cancel)),Ve.on(Be.type,((e,t)=>Xe.with({channels:e.channels,groups:e.groups}))),Ve.on(Ge.type,((e,t)=>Xe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Ve.on(qe.type,((e,t)=>Xe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[$e(t.payload.channels,t.payload.groups)]))),Ve.on(xe.type,((e,t)=>ze.with({channels:e.channels,groups:e.groups},[...t.payload.isOffline?[]:[$e(e.channels,e.groups)]]))),Ve.on(Ke.type,((e,t)=>Qe.with(void 0,[...t.payload.isOffline?[]:[$e(e.channels,e.groups)]])));const Je=new ke("HEARTBEAT_FAILED");Je.on(Ge.type,((e,t)=>Xe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Je.on(qe.type,((e,t)=>Xe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[$e(t.payload.channels,t.payload.groups)]))),Je.on(De.type,((e,t)=>Xe.with({channels:e.channels,groups:e.groups}))),Je.on(xe.type,((e,t)=>ze.with({channels:e.channels,groups:e.groups},[...t.payload.isOffline?[]:[$e(e.channels,e.groups)]]))),Je.on(Ke.type,((e,t)=>Qe.with(void 0,[...t.payload.isOffline?[]:[$e(e.channels,e.groups)]])));const Xe=new ke("HEARTBEATING");Xe.onEnter((e=>Ue(e.channels,e.groups))),Xe.onExit((()=>Ue.cancel)),Xe.on(Le.type,((e,t)=>Ve.with({channels:e.channels,groups:e.groups},[Re(Object.assign({},t.payload))]))),Xe.on(Ge.type,((e,t)=>Xe.with({channels:[...e.channels,...t.payload.channels],groups:[...e.groups,...t.payload.groups]}))),Xe.on(qe.type,((e,t)=>Xe.with({channels:e.channels.filter((e=>!t.payload.channels.includes(e))),groups:e.groups.filter((e=>!t.payload.groups.includes(e)))},[$e(t.payload.channels,t.payload.groups)]))),Xe.on(He.type,((e,t)=>Je.with(Object.assign({},e),[...t.payload.status?[Re(Object.assign({},t.payload.status))]:[]]))),Xe.on(xe.type,((e,t)=>ze.with({channels:e.channels,groups:e.groups},[...t.payload.isOffline?[]:[$e(e.channels,e.groups)]]))),Xe.on(Ke.type,((e,t)=>Qe.with(void 0,[...t.payload.isOffline?[]:[$e(e.channels,e.groups)]])));const Qe=new ke("HEARTBEAT_INACTIVE");Qe.on(Ge.type,((e,t)=>Xe.with({channels:t.payload.channels,groups:t.payload.groups})));class Ye{get _engine(){return this.engine}constructor(e){this.dependencies=e,this.channels=[],this.groups=[],this.engine=new Ce(e.config.logger()),this.dispatcher=new We(this.engine,e),e.config.logger().debug(this.constructor.name,"Create presence event engine."),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(Qe,void 0)}join({channels:e,groups:t}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],this.engine.transition(Ge(this.channels.slice(0),this.groups.slice(0)))}leave({channels:e,groups:t}){this.dependencies.presenceState&&(null==e||e.forEach((e=>delete this.dependencies.presenceState[e])),null==t||t.forEach((e=>delete this.dependencies.presenceState[e]))),this.engine.transition(qe(null!=e?e:[],null!=t?t:[]))}leaveAll(e=!1){this.engine.transition(Ke(e))}reconnect(){this.engine.transition(De())}disconnect(e=!1){this.engine.transition(xe(e))}dispose(){this.disconnect(!0),this._unsubscribeEngine(),this.dispatcher.dispose()}}const Ze=Ne("HANDSHAKE",((e,t)=>({channels:e,groups:t}))),et=Ne("RECEIVE_MESSAGES",((e,t,s)=>({channels:e,groups:t,cursor:s}))),tt=Ee("EMIT_MESSAGES",((e,t)=>({cursor:e,events:t}))),st=Ee("EMIT_STATUS",(e=>e)),nt=je("SUBSCRIPTION_CHANGED",((e,t,s=!1)=>({channels:e,groups:t,isOffline:s}))),rt=je("SUBSCRIPTION_RESTORED",((e,t,s,n)=>({channels:e,groups:t,cursor:{timetoken:s,region:null!=n?n:0}}))),it=je("HANDSHAKE_SUCCESS",(e=>e)),at=je("HANDSHAKE_FAILURE",(e=>e)),ot=je("RECEIVE_SUCCESS",((e,t)=>({cursor:e,events:t}))),ct=je("RECEIVE_FAILURE",(e=>e)),ut=je("DISCONNECT",((e=!1)=>({isOffline:e}))),lt=je("RECONNECT",((e,t)=>({cursor:{timetoken:null!=e?e:"",region:null!=t?t:0}}))),ht=je("UNSUBSCRIBE_ALL",(()=>({}))),dt=new ke("UNSUBSCRIBED");dt.on(nt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):bt.with({channels:t.channels,groups:t.groups}))),dt.on(rt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):bt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region}})));const pt=new ke("HANDSHAKE_STOPPED");pt.on(nt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):pt.with({channels:t.channels,groups:t.groups,cursor:e.cursor}))),pt.on(lt.type,((e,{payload:t})=>bt.with(Object.assign(Object.assign({},e),{cursor:t.cursor||e.cursor})))),pt.on(rt.type,((e,{payload:t})=>{var s;return 0===t.channels.length&&0===t.groups.length?dt.with(void 0):pt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||(null===(s=e.cursor)||void 0===s?void 0:s.region)||0}})})),pt.on(ht.type,(e=>dt.with()));const gt=new ke("HANDSHAKE_FAILED");gt.on(nt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):bt.with({channels:t.channels,groups:t.groups,cursor:e.cursor}))),gt.on(lt.type,((e,{payload:t})=>bt.with(Object.assign(Object.assign({},e),{cursor:t.cursor||e.cursor})))),gt.on(rt.type,((e,{payload:t})=>{var s,n;return 0===t.channels.length&&0===t.groups.length?dt.with(void 0):bt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region?t.cursor.region:null!==(n=null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)&&void 0!==n?n:0}})})),gt.on(ht.type,(e=>dt.with()));const bt=new ke("HANDSHAKING");bt.onEnter((e=>Ze(e.channels,e.groups))),bt.onExit((()=>Ze.cancel)),bt.on(nt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):bt.with({channels:t.channels,groups:t.groups,cursor:e.cursor}))),bt.on(it.type,((e,{payload:t})=>{var s,n,r,i,a;return ft.with({channels:e.channels,groups:e.groups,cursor:{timetoken:(null===(s=e.cursor)||void 0===s?void 0:s.timetoken)?null===(n=e.cursor)||void 0===n?void 0:n.timetoken:t.timetoken,region:t.region},referenceTimetoken:X(t.timetoken,null===(r=e.cursor)||void 0===r?void 0:r.timetoken)},[st({category:h.PNConnectedCategory,affectedChannels:e.channels.slice(0),affectedChannelGroups:e.groups.slice(0),currentTimetoken:(null===(i=e.cursor)||void 0===i?void 0:i.timetoken)?null===(a=e.cursor)||void 0===a?void 0:a.timetoken:t.timetoken})])})),bt.on(at.type,((e,t)=>{var s;return gt.with(Object.assign(Object.assign({},e),{reason:t.payload}),[st({category:h.PNConnectionErrorCategory,error:null===(s=t.payload.status)||void 0===s?void 0:s.category})])})),bt.on(ut.type,((e,t)=>{var s;if(t.payload.isOffline){const t=_.create(new Error("Network connection error")).toPubNubError(le.PNSubscribeOperation);return gt.with(Object.assign(Object.assign({},e),{reason:t}),[st({category:h.PNConnectionErrorCategory,error:null===(s=t.status)||void 0===s?void 0:s.category})])}return pt.with(Object.assign({},e))})),bt.on(rt.type,((e,{payload:t})=>{var s;return 0===t.channels.length&&0===t.groups.length?dt.with(void 0):bt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||(null===(s=null==e?void 0:e.cursor)||void 0===s?void 0:s.region)||0}})})),bt.on(ht.type,(e=>dt.with()));const mt=new ke("RECEIVE_STOPPED");mt.on(nt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):mt.with({channels:t.channels,groups:t.groups,cursor:e.cursor}))),mt.on(rt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):mt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||e.cursor.region}}))),mt.on(lt.type,((e,{payload:t})=>{var s;return bt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.cursor.timetoken?null===(s=t.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.cursor.region||e.cursor.region}})})),mt.on(ht.type,(()=>dt.with(void 0)));const yt=new ke("RECEIVE_FAILED");yt.on(lt.type,((e,{payload:t})=>{var s;return bt.with({channels:e.channels,groups:e.groups,cursor:{timetoken:t.cursor.timetoken?null===(s=t.cursor)||void 0===s?void 0:s.timetoken:e.cursor.timetoken,region:t.cursor.region||e.cursor.region}})})),yt.on(nt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):bt.with({channels:t.channels,groups:t.groups,cursor:e.cursor}))),yt.on(rt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0):bt.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||e.cursor.region}}))),yt.on(ht.type,(e=>dt.with(void 0)));const ft=new ke("RECEIVING");ft.onEnter((e=>et(e.channels,e.groups,e.cursor))),ft.onExit((()=>et.cancel)),ft.on(ot.type,((e,{payload:t})=>ft.with({channels:e.channels,groups:e.groups,cursor:t.cursor,referenceTimetoken:X(t.cursor.timetoken)},[tt(e.cursor,t.events)]))),ft.on(nt.type,((e,{payload:t})=>{var s;if(0===t.channels.length&&0===t.groups.length){let e;return t.isOffline&&(e=null===(s=_.create(new Error("Network connection error")).toPubNubError(le.PNSubscribeOperation).status)||void 0===s?void 0:s.category),dt.with(void 0,[st(Object.assign({category:t.isOffline?h.PNDisconnectedUnexpectedlyCategory:h.PNDisconnectedCategory},e?{error:e}:{}))])}return ft.with({channels:t.channels,groups:t.groups,cursor:e.cursor,referenceTimetoken:e.referenceTimetoken},[st({category:h.PNSubscriptionChangedCategory,affectedChannels:t.channels.slice(0),affectedChannelGroups:t.groups.slice(0),currentTimetoken:e.cursor.timetoken})])})),ft.on(rt.type,((e,{payload:t})=>0===t.channels.length&&0===t.groups.length?dt.with(void 0,[st({category:h.PNDisconnectedCategory})]):ft.with({channels:t.channels,groups:t.groups,cursor:{timetoken:`${t.cursor.timetoken}`,region:t.cursor.region||e.cursor.region},referenceTimetoken:X(e.cursor.timetoken,`${t.cursor.timetoken}`,e.referenceTimetoken)},[st({category:h.PNSubscriptionChangedCategory,affectedChannels:t.channels.slice(0),affectedChannelGroups:t.groups.slice(0),currentTimetoken:t.cursor.timetoken})]))),ft.on(ct.type,((e,{payload:t})=>{var s;return yt.with(Object.assign(Object.assign({},e),{reason:t}),[st({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(s=t.status)||void 0===s?void 0:s.category})])})),ft.on(ut.type,((e,t)=>{var s;if(t.payload.isOffline){const t=_.create(new Error("Network connection error")).toPubNubError(le.PNSubscribeOperation);return yt.with(Object.assign(Object.assign({},e),{reason:t}),[st({category:h.PNDisconnectedUnexpectedlyCategory,error:null===(s=t.status)||void 0===s?void 0:s.category})])}return mt.with(Object.assign({},e),[st({category:h.PNDisconnectedCategory})])})),ft.on(ht.type,(e=>dt.with(void 0,[st({category:h.PNDisconnectedCategory})])));class vt extends Pe{constructor(e,t){super(t,t.config.logger()),this.on(Ze.type,Ae(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{handshake:n,presenceState:r,config:i}){s.throwIfAborted();try{const a=yield n(Object.assign({abortSignal:s,channels:t.channels,channelGroups:t.groups,filterExpression:i.filterExpression},i.maintainPresenceState&&{state:r}));return e.transition(it(a))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;return e.transition(at(t))}}}))))),this.on(et.type,Ae(((t,s,n)=>i(this,[t,s,n],void 0,(function*(t,s,{receiveMessages:n,config:r}){s.throwIfAborted();try{const i=yield n({abortSignal:s,channels:t.channels,channelGroups:t.groups,timetoken:t.cursor.timetoken,region:t.cursor.region,filterExpression:r.filterExpression});e.transition(ot(i.cursor,i.messages))}catch(t){if(t instanceof d){if(t.status&&t.status.category==h.PNCancelledCategory)return;if(!s.aborted)return e.transition(ct(t))}}}))))),this.on(tt.type,Ae(((e,t,s)=>i(this,[e,t,s],void 0,(function*({cursor:e,events:t},s,{emitMessages:n}){t.length>0&&n(e,t)}))))),this.on(st.type,Ae(((e,t,s)=>i(this,[e,t,s],void 0,(function*(e,t,{emitStatus:s}){return s(e)})))))}}class St{get _engine(){return this.engine}constructor(e){this.channels=[],this.groups=[],this.dependencies=e,this.engine=new Ce(e.config.logger()),this.dispatcher=new vt(this.engine,e),e.config.logger().debug(this.constructor.name,"Create subscribe event engine."),this._unsubscribeEngine=this.engine.subscribe((e=>{"invocationDispatched"===e.type&&this.dispatcher.dispatch(e.invocation)})),this.engine.start(dt,void 0)}get subscriptionTimetoken(){const e=this.engine.currentState;if(!e)return;let t,s="0";if(e.label===ft.label){const e=this.engine.currentContext;s=e.cursor.timetoken,t=e.referenceTimetoken}return J(s,null!=t?t:"0")}subscribe({channels:e,channelGroups:t,timetoken:s,withPresence:n}){this.channels=[...this.channels,...null!=e?e:[]],this.groups=[...this.groups,...null!=t?t:[]],n&&(this.channels.map((e=>this.channels.push(`${e}-pnpres`))),this.groups.map((e=>this.groups.push(`${e}-pnpres`)))),s?this.engine.transition(rt(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])),s)):this.engine.transition(nt(Array.from(new Set([...this.channels,...null!=e?e:[]])),Array.from(new Set([...this.groups,...null!=t?t:[]])))),this.dependencies.join&&this.dependencies.join({channels:Array.from(new Set(this.channels.filter((e=>!e.endsWith("-pnpres"))))),groups:Array.from(new Set(this.groups.filter((e=>!e.endsWith("-pnpres")))))})}unsubscribe({channels:e=[],channelGroups:t=[]}){const s=W(this.channels,[...e,...e.map((e=>`${e}-pnpres`))]),n=W(this.groups,[...t,...t.map((e=>`${e}-pnpres`))]);if(new Set(this.channels).size!==new Set(s).size||new Set(this.groups).size!==new Set(n).size){const r=z(this.channels,e),i=z(this.groups,t);this.dependencies.presenceState&&(null==r||r.forEach((e=>delete this.dependencies.presenceState[e])),null==i||i.forEach((e=>delete this.dependencies.presenceState[e]))),this.channels=s,this.groups=n,this.engine.transition(nt(Array.from(new Set(this.channels.slice(0))),Array.from(new Set(this.groups.slice(0))))),this.dependencies.leave&&this.dependencies.leave({channels:r.slice(0),groups:i.slice(0)})}}unsubscribeAll(e=!1){const t=this.getSubscribedChannels(),s=this.getSubscribedChannels();this.channels=[],this.groups=[],this.dependencies.presenceState&&Object.keys(this.dependencies.presenceState).forEach((e=>{delete this.dependencies.presenceState[e]})),this.engine.transition(nt(this.channels.slice(0),this.groups.slice(0),e)),this.dependencies.leaveAll&&this.dependencies.leaveAll({channels:s,groups:t,isOffline:e})}reconnect({timetoken:e,region:t}){const s=this.getSubscribedChannels(),n=this.getSubscribedChannels();this.engine.transition(lt(e,t)),this.dependencies.presenceReconnect&&this.dependencies.presenceReconnect({channels:n,groups:s})}disconnect(e=!1){const t=this.getSubscribedChannels(),s=this.getSubscribedChannels();this.engine.transition(ut(e)),this.dependencies.presenceDisconnect&&this.dependencies.presenceDisconnect({channels:s,groups:t,isOffline:e})}getSubscribedChannels(){return Array.from(new Set(this.channels.slice(0)))}getSubscribedChannelGroups(){return Array.from(new Set(this.groups.slice(0)))}dispose(){this.disconnect(!0),this._unsubscribeEngine(),this.dispatcher.dispose()}}class wt extends ue{constructor(e){var t;const s=null!==(t=e.sendByPost)&&void 0!==t&&t;super({method:s?re.POST:re.GET,compressible:s}),this.parameters=e,this.parameters.sendByPost=s}operation(){return le.PNPublishOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:s}=this.parameters,n=this.prepareMessagePayload(e);return`/publish/${s.publishKey}/${s.subscribeKey}/0/${H(t)}/0${this.parameters.sendByPost?"":`/${H(n)}`}`}get queryParameters(){const{customMessageType:e,meta:t,replicate:s,storeInHistory:n,ttl:r}=this.parameters,i={};return e&&(i.custom_message_type=e),void 0!==n&&(i.store=n?"1":"0"),void 0!==r&&(i.ttl=r),void 0===s||s||(i.norep="true"),t&&"object"==typeof t&&(i.meta=JSON.stringify(t)),i}get headers(){var e;return this.parameters.sendByPost?Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"}):super.headers}get body(){return this.prepareMessagePayload(this.parameters.message)}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Ot extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNSignalOperation}validate(){const{message:e,channel:t,keySet:{publishKey:s}}=this.parameters;return t?e?s?void 0:"Missing 'publishKey'":"Missing 'message'":"Missing 'channel'"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{keySet:{publishKey:e,subscribeKey:t},channel:s,message:n}=this.parameters,r=JSON.stringify(n);return`/signal/${e}/${t}/0/${H(s)}/0/${H(r)}`}get queryParameters(){const{customMessageType:e}=this.parameters,t={};return e&&(t.custom_message_type=e),t}}class kt extends de{operation(){return le.PNReceiveMessagesOperation}validate(){const e=super.validate();return e||(this.parameters.timetoken?this.parameters.region?void 0:"region can not be empty":"timetoken can not be empty")}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${B(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,timetoken:s,region:n}=this.parameters,r={ee:""};return e&&e.length>0&&(r["channel-group"]=e.sort().join(",")),t&&t.length>0&&(r["filter-expr"]=t),"string"==typeof s?s&&"0"!==s&&s.length>0&&(r.tt=s):s&&s>0&&(r.tt=s),n&&(r.tr=n),r}}class Ct extends de{operation(){return le.PNHandshakeOperation}get path(){const{keySet:{subscribeKey:e},channels:t=[]}=this.parameters;return`/v2/subscribe/${e}/${B(t.sort(),",")}/0`}get queryParameters(){const{channelGroups:e,filterExpression:t,state:s}=this.parameters,n={ee:""};return e&&e.length>0&&(n["channel-group"]=e.sort().join(",")),t&&t.length>0&&(n["filter-expr"]=t),s&&Object.keys(s).length>0&&(n.state=JSON.stringify(s)),n}}class Pt extends ue{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=(n=this.parameters).channels)&&void 0!==t||(n.channels=[]),null!==(s=(r=this.parameters).channelGroups)&&void 0!==s||(r.channelGroups=[])}operation(){return le.PNGetStateOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;if(!e)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),{channels:s=[],channelGroups:n=[]}=this.parameters,r={channels:{}};return 1===s.length&&0===n.length?r.channels[s[0]]=t.payload:r.channels=t.payload,r}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${B(null!=s?s:[],",")}/uuid/${t}`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.join(",")}:{}}}class jt extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNSetStateOperation}validate(){const{keySet:{subscribeKey:e},state:t,channels:s=[],channelGroups:n=[]}=this.parameters;return e?t?0===(null==s?void 0:s.length)&&0===(null==n?void 0:n.length)?"Please provide a list of channels and/or channel-groups":void 0:"Missing State":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{state:this.deserializeResponse(e).payload}}))}get path(){const{keySet:{subscribeKey:e},uuid:t,channels:s}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${B(null!=s?s:[],",")}/uuid/${H(t)}/data`}get queryParameters(){const{channelGroups:e,state:t}=this.parameters,s={state:JSON.stringify(t)};return e&&0!==e.length&&(s["channel-group"]=e.join(",")),s}}class Et extends ue{constructor(e){super({cancellable:!0}),this.parameters=e}operation(){return le.PNHeartbeatOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"Please provide a list of channels and/or channel-groups":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channels:t}=this.parameters;return`/v2/presence/sub-key/${e}/channel/${B(null!=t?t:[],",")}/heartbeat`}get queryParameters(){const{channelGroups:e,state:t,heartbeat:s}=this.parameters,n={heartbeat:`${s}`};return e&&0!==e.length&&(n["channel-group"]=e.join(",")),t&&(n.state=JSON.stringify(t)),n}}class Nt extends ue{constructor(e){super(),this.parameters=e,this.parameters.channelGroups&&(this.parameters.channelGroups=Array.from(new Set(this.parameters.channelGroups))),this.parameters.channels&&(this.parameters.channels=Array.from(new Set(this.parameters.channels)))}operation(){return le.PNUnsubscribeOperation}validate(){const{keySet:{subscribeKey:e},channels:t=[],channelGroups:s=[]}=this.parameters;return e?0===t.length&&0===s.length?"At least one `channel` or `channel group` should be provided.":void 0:"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){var e;const{keySet:{subscribeKey:t},channels:s}=this.parameters;return`/v2/presence/sub-key/${t}/channel/${B(null!==(e=null==s?void 0:s.sort())&&void 0!==e?e:[],",")}/leave`}get queryParameters(){const{channelGroups:e}=this.parameters;return e&&0!==e.length?{"channel-group":e.sort().join(",")}:{}}}class Tt extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNWhereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return t.payload?{channels:t.payload.channels}:{channels:[]}}))}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/presence/sub-key/${e}/uuid/${H(t)}`}}class _t extends ue{constructor(e){var t,s,n,r,i,a;super(),this.parameters=e,null!==(t=(r=this.parameters).queryParameters)&&void 0!==t||(r.queryParameters={}),null!==(s=(i=this.parameters).includeUUIDs)&&void 0!==s||(i.includeUUIDs=true),null!==(n=(a=this.parameters).includeState)&&void 0!==n||(a.includeState=false)}operation(){const{channels:e=[],channelGroups:t=[]}=this.parameters;return 0===e.length&&0===t.length?le.PNGlobalHereNowOperation:le.PNHereNowOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t,s;const n=this.deserializeResponse(e),r="occupancy"in n?1:n.payload.total_channels,i="occupancy"in n?n.occupancy:n.payload.total_occupancy,a={};let o={};if("occupancy"in n){const e=this.parameters.channels[0];o[e]={uuids:null!==(t=n.uuids)&&void 0!==t?t:[],occupancy:i}}else o=null!==(s=n.payload.channels)&&void 0!==s?s:{};return Object.keys(o).forEach((e=>{const t=o[e];a[e]={occupants:this.parameters.includeUUIDs?t.uuids.map((e=>"string"==typeof e?{uuid:e,state:null}:e)):[],name:e,occupancy:t.occupancy}})),{totalChannels:r,totalOccupancy:i,channels:a}}))}get path(){const{keySet:{subscribeKey:e},channels:t,channelGroups:s}=this.parameters;let n=`/v2/presence/sub-key/${e}`;return(t&&t.length>0||s&&s.length>0)&&(n+=`/channel/${B(null!=t?t:[],",")}`),n}get queryParameters(){const{channelGroups:e,includeUUIDs:t,includeState:s,queryParameters:n}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign({},t?{}:{disable_uuids:"1"}),null!=s&&s?{state:"1"}:{}),e&&e.length>0?{"channel-group":e.join(",")}:{}),n)}}class It extends ue{constructor(e){super({method:re.DELETE}),this.parameters=e}operation(){return le.PNDeleteMessagesOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v3/history/sub-key/${e}/channel/${H(t)}`}get queryParameters(){const{start:e,end:t}=this.parameters;return Object.assign(Object.assign({},e?{start:e}:{}),t?{end:t}:{})}}class Mt extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNMessageCounts}validate(){const{keySet:{subscribeKey:e},channels:t,timetoken:s,channelTimetokens:n}=this.parameters;return e?t?s&&n?"`timetoken` and `channelTimetokens` are incompatible together":s||n?n&&n.length>1&&n.length!==t.length?"Length of `channelTimetokens` and `channels` do not match":void 0:"`timetoken` or `channelTimetokens` need to be set":"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).channels}}))}get path(){return`/v3/history/sub-key/${this.parameters.keySet.subscribeKey}/message-counts/${B(this.parameters.channels)}`}get queryParameters(){let{channelTimetokens:e}=this.parameters;return this.parameters.timetoken&&(e=[this.parameters.timetoken]),Object.assign(Object.assign({},1===e.length?{timetoken:e[0]}:{}),e.length>1?{channelsTimetoken:e.join(",")}:{})}}class At extends ue{constructor(e){var t,s,n;super(),this.parameters=e,e.count?e.count=Math.min(e.count,100):e.count=100,null!==(t=e.stringifiedTimeToken)&&void 0!==t||(e.stringifiedTimeToken=false),null!==(s=e.includeMeta)&&void 0!==s||(e.includeMeta=false),null!==(n=e.logVerbosity)&&void 0!==n||(e.logVerbosity=false)}operation(){return le.PNHistoryOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e),s=t[0],n=t[1],r=t[2];return Array.isArray(s)?{messages:s.map((e=>{const t=this.processPayload(e.message),s={entry:t.payload,timetoken:e.timetoken};return t.error&&(s.error=t.error),e.meta&&(s.meta=e.meta),s})),startTimeToken:n,endTimeToken:r}:{messages:[],startTimeToken:n,endTimeToken:r}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/history/sub-key/${e}/channel/${H(t)}`}get queryParameters(){const{start:e,end:t,reverse:s,count:n,stringifiedTimeToken:r,includeMeta:i}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:n,include_token:"true"},e?{start:e}:{}),t?{end:t}:{}),r?{string_message_token:"true"}:{}),null!=s?{reverse:s.toString()}:{}),i?{include_meta:"true"}:{})}processPayload(e){const{crypto:t,logVerbosity:s}=this.parameters;if(!t||"string"!=typeof e)return{payload:e};let n,r;try{const s=t.decrypt(e);n=s instanceof ArrayBuffer?JSON.parse(At.decoder.decode(s)):s}catch(t){s&&console.log("decryption error",t.message),n=e,r=`Error while decrypting message content: ${t.message}`}return{payload:n,error:r}}}var Ut;!function(e){e[e.Message=-1]="Message",e[e.Files=4]="Files"}(Ut||(Ut={}));class $t extends ue{constructor(e){var t,s,n,r,i;super(),this.parameters=e;const a=null!==(t=e.includeMessageActions)&&void 0!==t&&t,o=e.channels.length>1||a?25:100;e.count?e.count=Math.min(e.count,o):e.count=o,e.includeUuid?e.includeUUID=e.includeUuid:null!==(s=e.includeUUID)&&void 0!==s||(e.includeUUID=true),null!==(n=e.stringifiedTimeToken)&&void 0!==n||(e.stringifiedTimeToken=false),null!==(r=e.includeMessageType)&&void 0!==r||(e.includeMessageType=true),null!==(i=e.logVerbosity)&&void 0!==i||(e.logVerbosity=false)}operation(){return le.PNFetchMessagesOperation}validate(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return e?t?void 0!==s&&s&&t.length>1?"History can return actions data for a single channel only. Either pass a single channel or disable the includeMessageActions flag.":void 0:"Missing channels":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){var t;const s=this.deserializeResponse(e),n=null!==(t=s.channels)&&void 0!==t?t:{},r={};return Object.keys(n).forEach((e=>{r[e]=n[e].map((t=>{null===t.message_type&&(t.message_type=Ut.Message);const s=this.processPayload(e,t),n=Object.assign(Object.assign({channel:e,timetoken:t.timetoken,message:s.payload,messageType:t.message_type},t.custom_message_type?{customMessageType:t.custom_message_type}:{}),{uuid:t.uuid});if(t.actions){const e=n;e.actions=t.actions,e.data=t.actions}return t.meta&&(n.meta=t.meta),s.error&&(n.error=s.error),n}))})),s.more?{channels:r,more:s.more}:{channels:r}}))}get path(){const{keySet:{subscribeKey:e},channels:t,includeMessageActions:s}=this.parameters;return`/v3/${s?"history-with-actions":"history"}/sub-key/${e}/channel/${B(t)}`}get queryParameters(){const{start:e,end:t,count:s,includeCustomMessageType:n,includeMessageType:r,includeMeta:i,includeUUID:a,stringifiedTimeToken:o}=this.parameters;return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({max:s},e?{start:e}:{}),t?{end:t}:{}),o?{string_message_token:"true"}:{}),void 0!==i&&i?{include_meta:"true"}:{}),a?{include_uuid:"true"}:{}),null!=n?{include_custom_message_type:n?"true":"false"}:{}),r?{include_message_type:"true"}:{})}processPayload(e,t){const{crypto:s,logVerbosity:n}=this.parameters;if(!s||"string"!=typeof t.message)return{payload:t.message};let r,i;try{const e=s.decrypt(t.message);r=e instanceof ArrayBuffer?JSON.parse($t.decoder.decode(e)):e}catch(e){n&&console.log("decryption error",e.message),r=t.message,i=`Error while decrypting message content: ${e.message}`}if(!i&&r&&t.message_type==Ut.Files&&"object"==typeof r&&this.isFileMessage(r)){const t=r;return{payload:{message:t.message,file:Object.assign(Object.assign({},t.file),{url:this.parameters.getFileUrl({channel:e,id:t.file.id,name:t.file.name})})},error:i}}return{payload:r,error:i}}isFileMessage(e){return void 0!==e.file}}class Rt extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNGetMessageActionsOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channel?void 0:"Missing message channel":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);let s=null,n=null;return t.data.length>0&&(s=t.data[0].actionTimetoken,n=t.data[t.data.length-1].actionTimetoken),{data:t.data,more:t.more,start:s,end:n}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/message-actions/${e}/channel/${H(t)}`}get queryParameters(){const{limit:e,start:t,end:s}=this.parameters;return Object.assign(Object.assign(Object.assign({},t?{start:t}:{}),s?{end:s}:{}),e?{limit:e}:{})}}class Ft extends ue{constructor(e){super({method:re.POST}),this.parameters=e}operation(){return le.PNAddMessageActionOperation}validate(){const{keySet:{subscribeKey:e},action:t,channel:s,messageTimetoken:n}=this.parameters;return e?s?n?t?t.value?t.type?t.type.length>15?"Action.type value exceed maximum length of 15":void 0:"Missing Action.type":"Missing Action.value":"Missing Action":"Missing message timetoken":"Missing message channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s}=this.parameters;return`/v1/message-actions/${e}/channel/${H(t)}/message/${s}`}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"})}get body(){return JSON.stringify(this.parameters.action)}}class Dt extends ue{constructor(e){super({method:re.DELETE}),this.parameters=e}operation(){return le.PNRemoveMessageActionOperation}validate(){const{keySet:{subscribeKey:e},channel:t,messageTimetoken:s,actionTimetoken:n}=this.parameters;return e?t?s?n?void 0:"Missing action timetoken":"Missing message timetoken":"Missing message action channel":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((({data:e})=>({data:e})))}))}get path(){const{keySet:{subscribeKey:e},channel:t,actionTimetoken:s,messageTimetoken:n}=this.parameters;return`/v1/message-actions/${e}/channel/${H(t)}/message/${n}/action/${s}`}}class xt extends ue{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).storeInHistory)&&void 0!==t||(s.storeInHistory=true)}operation(){return le.PNPublishFileMessageOperation}validate(){const{channel:e,fileId:t,fileName:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[2]}}))}get path(){const{message:e,channel:t,keySet:{publishKey:s,subscribeKey:n},fileId:r,fileName:i}=this.parameters,a=Object.assign({file:{name:i,id:r}},e?{message:e}:{});return`/v1/files/publish-file/${s}/${n}/0/${H(t)}/0/${H(this.prepareMessagePayload(a))}`}get queryParameters(){const{customMessageType:e,storeInHistory:t,ttl:s,meta:n}=this.parameters;return Object.assign(Object.assign(Object.assign({store:t?"1":"0"},e?{custom_message_type:e}:{}),s?{ttl:s}:{}),n&&"object"==typeof n?{meta:JSON.stringify(n)}:{})}prepareMessagePayload(e){const{crypto:t}=this.parameters;if(!t)return JSON.stringify(e)||"";const s=t.encrypt(JSON.stringify(e));return JSON.stringify("string"==typeof s?s:u(s))}}class Gt extends ue{constructor(e){super({method:re.LOCAL}),this.parameters=e}operation(){return le.PNGetFileUrlOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return e.url}))}get path(){const{channel:e,id:t,name:s,keySet:{subscribeKey:n}}=this.parameters;return`/v1/files/${n}/channels/${H(e)}/files/${t}/${s}`}}class qt extends ue{constructor(e){super({method:re.DELETE}),this.parameters=e}operation(){return le.PNDeleteFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},id:t,channel:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${H(s)}/files/${t}/${n}`}}class Kt extends ue{constructor(e){var t,s;super(),this.parameters=e,null!==(t=(s=this.parameters).limit)&&void 0!==t||(s.limit=100)}operation(){return le.PNListFilesOperation}validate(){if(!this.parameters.channel)return"channel can't be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${H(t)}/files`}get queryParameters(){const{limit:e,next:t}=this.parameters;return Object.assign({limit:e},t?{next:t}:{})}}class Lt extends ue{constructor(e){super({method:re.POST}),this.parameters=e}operation(){return le.PNGenerateUploadUrlOperation}validate(){return this.parameters.channel?this.parameters.name?void 0:"'name' can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const t=this.deserializeResponse(e);return{id:t.data.id,name:t.data.name,url:t.file_upload_request.url,formFields:t.file_upload_request.form_fields}}))}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v1/files/${e}/channels/${H(t)}/generate-upload-url`}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"})}get body(){return JSON.stringify({name:this.parameters.name})}}class Ht extends ue{constructor(e){super({method:re.POST}),this.parameters=e;const t=e.file.mimeType;t&&(e.formFields=e.formFields.map((e=>"Content-Type"===e.name?{name:e.name,value:t}:e)))}operation(){return le.PNPublishFileOperation}validate(){const{fileId:e,fileName:t,file:s,uploadUrl:n}=this.parameters;return e?t?s?n?void 0:"Validation failed: file upload 'url' can't be empty":"Validation failed: 'file' can't be empty":"Validation failed: file 'name' can't be empty":"Validation failed: file 'id' can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){return{status:e.status,message:e.body?Ht.decoder.decode(e.body):"OK"}}))}request(){return Object.assign(Object.assign({},super.request()),{origin:new URL(this.parameters.uploadUrl).origin,timeout:300})}get path(){const{pathname:e,search:t}=new URL(this.parameters.uploadUrl);return`${e}${t}`}get body(){return this.parameters.file}get formData(){return this.parameters.formFields}}class Bt{constructor(e){var t;if(this.parameters=e,this.file=null===(t=this.parameters.PubNubFile)||void 0===t?void 0:t.create(e.file),!this.file)throw new Error("File upload error: unable to create File object.")}process(){return i(this,void 0,void 0,(function*(){let e,t;return this.generateFileUploadUrl().then((s=>(e=s.name,t=s.id,this.uploadFile(s)))).then((e=>{if(204!==e.status)throw new d("Upload to bucket was unsuccessful",{error:!0,statusCode:e.status,category:h.PNUnknownCategory,operation:le.PNPublishFileOperation,errorData:{message:e.message}})})).then((()=>this.publishFileMessage(t,e))).catch((e=>{if(e instanceof d)throw e;const t=e instanceof _?e:_.create(e);throw new d("File upload error.",t.toStatus(le.PNPublishFileOperation))}))}))}generateFileUploadUrl(){return i(this,void 0,void 0,(function*(){const e=new Lt(Object.assign(Object.assign({},this.parameters),{name:this.file.name,keySet:this.parameters.keySet}));return this.parameters.sendRequest(e)}))}uploadFile(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,PubNubFile:s,crypto:n,cryptography:r}=this.parameters,{id:i,name:a,url:o,formFields:c}=e;return this.parameters.PubNubFile.supportsEncryptFile&&(!t&&n?this.file=yield n.encryptFile(this.file,s):t&&r&&(this.file=yield r.encryptFile(t,this.file,s))),this.parameters.sendRequest(new Ht({fileId:i,fileName:a,file:this.file,uploadUrl:o,formFields:c}))}))}publishFileMessage(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i;let a,o={timetoken:"0"},c=this.parameters.fileUploadPublishRetryLimit,u=!1;do{try{o=yield this.parameters.publishFile(Object.assign(Object.assign({},this.parameters),{fileId:e,fileName:t})),u=!0}catch(e){e instanceof d&&(a=e),c-=1}}while(!u&&c>0);if(u)return{status:200,timetoken:o.timetoken,id:e,name:t};throw new d("Publish failed. You may want to execute that operation manually using pubnub.publishFile",{error:!0,category:null!==(n=null===(s=a.status)||void 0===s?void 0:s.category)&&void 0!==n?n:h.PNUnknownCategory,statusCode:null!==(i=null===(r=a.status)||void 0===r?void 0:r.statusCode)&&void 0!==i?i:0,channel:this.parameters.channel,id:e,name:t})}))}}var Wt;!function(e){e[e.Channel=0]="Channel",e[e.ChannelGroup=1]="ChannelGroup"}(Wt||(Wt={}));class zt{constructor({channels:e,channelGroups:t}){this.isEmpty=!0,this._channelGroups=new Set((null!=t?t:[]).filter((e=>e.length>0))),this._channels=new Set((null!=e?e:[]).filter((e=>e.length>0))),this.isEmpty=0===this._channels.size&&0===this._channelGroups.size}get channels(){return this.isEmpty?[]:Array.from(this._channels)}get channelGroups(){return this.isEmpty?[]:Array.from(this._channelGroups)}contains(e){return!this.isEmpty&&(this._channels.has(e)||this._channelGroups.has(e))}with(e){return new zt({channels:[...this._channels,...e._channels],channelGroups:[...this._channelGroups,...e._channelGroups]})}without(e){return new zt({channels:[...this._channels].filter((t=>!e._channels.has(t))),channelGroups:[...this._channelGroups].filter((t=>!e._channelGroups.has(t)))})}add(e){return e._channelGroups.size>0&&(this._channelGroups=new Set([...this._channelGroups,...e._channelGroups])),e._channels.size>0&&(this._channels=new Set([...this._channels,...e._channels])),this.isEmpty=0===this._channels.size&&0===this._channelGroups.size,this}remove(e){return e._channelGroups.size>0&&(this._channelGroups=new Set([...this._channelGroups].filter((t=>!e._channelGroups.has(t))))),e._channels.size>0&&(this._channels=new Set([...this._channels].filter((t=>!e._channels.has(t))))),this}removeAll(){return this._channels.clear(),this._channelGroups.clear(),this.isEmpty=!0,this}toString(){return`SubscriptionInput { channels: [${this.channels.join(", ")}], channelGroups: [${this.channelGroups.join(", ")}], is empty: ${this.isEmpty?"true":"false"}} }`}}class Vt{constructor(e,t,s,n){this._isSubscribed=!1,this.clones={},this.parents=[],this._id=K.createUUID(),this.referenceTimetoken=n,this.subscriptionInput=t,this.options=s,this.client=e}get id(){return this._id}get isLastClone(){return 1===Object.keys(this.clones).length}get isSubscribed(){return!!this._isSubscribed||this.parents.length>0&&this.parents.some((e=>e.isSubscribed))}set isSubscribed(e){this.isSubscribed!==e&&(this._isSubscribed=e)}addParentState(e){this.parents.includes(e)||this.parents.push(e)}removeParentState(e){const t=this.parents.indexOf(e);-1!==t&&this.parents.splice(t,1)}storeClone(e,t){this.clones[e]||(this.clones[e]=t)}}class Jt{constructor(e){this.id=K.createUUID(),this.eventDispatcher=new ge,this._state=e}get state(){return this._state}get channels(){return this.state.subscriptionInput.channels.slice(0)}get channelGroups(){return this.state.subscriptionInput.channelGroups.slice(0)}set onMessage(e){this.eventDispatcher.onMessage=e}set onPresence(e){this.eventDispatcher.onPresence=e}set onSignal(e){this.eventDispatcher.onSignal=e}set onObjects(e){this.eventDispatcher.onObjects=e}set onMessageAction(e){this.eventDispatcher.onMessageAction=e}set onFile(e){this.eventDispatcher.onFile=e}addListener(e){this.eventDispatcher.addListener(e)}removeListener(e){this.eventDispatcher.removeListener(e)}removeAllListeners(){this.eventDispatcher.removeAllListeners()}handleEvent(e,t){var s;if((!this.state.cursor||e>this.state.cursor)&&(this.state.cursor=e),this.state.referenceTimetoken&&t.data.timetoken({messageType:"text",message:`Event timetoken (${t.data.timetoken}) is older than reference timetoken (${this.state.referenceTimetoken}) for ${this.id} subscription object. Ignoring event.`})));if((null===(s=this.state.options)||void 0===s?void 0:s.filter)&&!this.state.options.filter(t))return void this.state.client.logger.trace(this.constructor.name,`Event filtered out by filter function for ${this.id} subscription object. Ignoring event.`);const n=Object.values(this.state.clones);n.length>0&&this.state.client.logger.trace(this.constructor.name,`Notify ${this.id} subscription object clones (count: ${n.length}) about received event.`),n.forEach((e=>e.eventDispatcher.handleEvent(t)))}dispose(){const e=Object.keys(this.state.clones);e.length>1?(this.state.client.logger.debug(this.constructor.name,`Remove subscription object clone on dispose: ${this.id}`),delete this.state.clones[this.id]):1===e.length&&this.state.clones[this.id]&&(this.state.client.logger.debug(this.constructor.name,`Unsubscribe subscription object on dispose: ${this.id}`),this.unsubscribe())}invalidate(e=!1){this.state._isSubscribed=!1,e&&(delete this.state.clones[this.id],0===Object.keys(this.state.clones).length&&(this.state.client.logger.trace(this.constructor.name,"Last clone removed. Reset shared subscription state."),this.state.subscriptionInput.removeAll(),this.state.parents=[]))}subscribe(e){this.state.isSubscribed?this.state.client.logger.trace(this.constructor.name,"Already subscribed. Ignoring subscribe request."):(this.state.client.logger.debug(this.constructor.name,(()=>e?{messageType:"object",message:e,details:"Subscribe with parameters:"}:{messageType:"text",message:"Subscribe"})),this.state.isSubscribed=!0,this.updateSubscription({subscribing:!0,timetoken:null==e?void 0:e.timetoken}))}unsubscribe(){if(!this.state._isSubscribed||this.state.isSubscribed){if(!this.state._isSubscribed&&this.state.parents.length>0&&this.state.isSubscribed)return void this.state.client.logger.warn(this.constructor.name,(()=>({messageType:"object",details:"Subscription is subscribed as part of a subscription set. Remove from active sets to unsubscribe:",message:this.state.parents.filter((e=>e.isSubscribed))})));if(!this.state._isSubscribed)return void this.state.client.logger.trace(this.constructor.name,"Not subscribed. Ignoring unsubscribe request.")}this.state.client.logger.debug(this.constructor.name,"Unsubscribe"),this.state.isSubscribed=!0,delete this.state.cursor,this.updateSubscription({subscribing:!1})}updateSubscription(e){var t,s;(null==e?void 0:e.timetoken)&&((null===(t=this.state.cursor)||void 0===t?void 0:t.timetoken)&&"0"!==(null===(s=this.state.cursor)||void 0===s?void 0:s.timetoken)?"0"!==e.timetoken&&e.timetoken>this.state.cursor.timetoken&&(this.state.cursor.timetoken=e.timetoken):this.state.cursor={timetoken:e.timetoken});const n=e.subscriptions&&e.subscriptions.length>0?e.subscriptions:void 0;e.subscribing?this.register(Object.assign(Object.assign({},e.timetoken?{cursor:this.state.cursor}:{}),n?{subscriptions:n}:{})):this.unregister(n)}}class Xt extends Vt{constructor(e){const t=new zt({});e.subscriptions.forEach((e=>t.add(e.state.subscriptionInput))),super(e.client,t,e.options,e.client.subscriptionTimetoken),this.subscriptions=e.subscriptions}addSubscription(e){this.subscriptions.includes(e)||(e.state.addParentState(this),this.subscriptions.push(e),this.subscriptionInput.add(e.state.subscriptionInput))}removeSubscription(e,t){const s=this.subscriptions.indexOf(e);-1!==s&&(this.subscriptions.splice(s,1),t||e.state.removeParentState(this),this.subscriptionInput.remove(e.state.subscriptionInput))}removeAllSubscriptions(){this.subscriptions.forEach((e=>e.state.removeParentState(this))),this.subscriptions.splice(0,this.subscriptions.length),this.subscriptionInput.removeAll()}}class Qt extends Jt{constructor(e){let t;if("client"in e){let s=[];!e.subscriptions&&e.entities?e.entities.forEach((t=>s.push(t.subscription(e.options)))):e.subscriptions&&(s=e.subscriptions),t=new Xt({client:e.client,subscriptions:s,options:e.options}),s.forEach((e=>e.state.addParentState(t))),t.client.logger.debug("SubscriptionSet",(()=>({messageType:"object",details:"Create subscription set with parameters:",message:Object.assign({subscriptions:t.subscriptions},e.options?e.options:{})})))}else t=e.state,t.client.logger.debug("SubscriptionSet","Create subscription set clone");super(t),this.state.storeClone(this.id,this),t.subscriptions.forEach((e=>e.addParentSet(this)))}get state(){return super.state}get subscriptions(){return this.state.subscriptions.slice(0)}handleEvent(e,t){var s;this.state.subscriptionInput.contains(null!==(s=t.data.subscription)&&void 0!==s?s:t.data.channel)&&(this.state._isSubscribed?(super.handleEvent(e,t),this.state.subscriptions.length>0&&this.state.client.logger.trace(this.constructor.name,`Notify ${this.id} subscription set subscriptions (count: ${this.state.subscriptions.length}) about received event.`),this.state.subscriptions.forEach((s=>s.handleEvent(e,t)))):this.state.client.logger.trace(this.constructor.name,`Subscription set ${this.id} is not subscribed. Ignoring event.`))}subscriptionInput(e=!1){let t=this.state.subscriptionInput;return this.state.subscriptions.forEach((s=>{e&&s.state.entity.subscriptionsCount>0&&(t=t.without(s.state.subscriptionInput))})),t}cloneEmpty(){return new Qt({state:this.state})}dispose(){const e=this.state.isLastClone;this.state.subscriptions.forEach((t=>{t.removeParentSet(this),e&&t.state.removeParentState(this.state)})),super.dispose()}invalidate(e=!1){(e?this.state.subscriptions.slice(0):this.state.subscriptions).forEach((t=>{e&&(t.state.entity.decreaseSubscriptionCount(this.state.id),t.removeParentSet(this)),t.invalidate(e)})),e&&this.state.removeAllSubscriptions(),super.invalidate()}addSubscription(e){this.addSubscriptions([e])}addSubscriptions(e){const t=[],s=[];this.state.client.logger.debug(this.constructor.name,(()=>{const t=[],s=[];return e.forEach((e=>{this.state.subscriptions.includes(e)?t.push(e):s.push(e)})),{messageType:"object",details:`Add subscriptions to ${this.id} (subscriptions count: ${this.state.subscriptions.length+s.length}):`,message:{addedSubscriptions:s,ignoredSubscriptions:t}}})),e.filter((e=>!this.state.subscriptions.includes(e))).forEach((e=>{e.state.isSubscribed?s.push(e):t.push(e),e.addParentSet(this),this.state.addSubscription(e)})),0===s.length&&0===t.length||!this.state.isSubscribed||(s.forEach((({state:e})=>e.entity.increaseSubscriptionCount(this.state.id))),t.length>0&&this.updateSubscription({subscribing:!0,subscriptions:t}))}removeSubscription(e){this.removeSubscriptions([e])}removeSubscriptions(e){const t=[];this.state.client.logger.debug(this.constructor.name,(()=>{const t=[],s=[];return e.forEach((e=>{this.state.subscriptions.includes(e)?s.push(e):t.push(e)})),{messageType:"object",details:`Remove subscriptions from ${this.id} (subscriptions count: ${this.state.subscriptions.length}):`,message:{removedSubscriptions:s,ignoredSubscriptions:t}}})),e.filter((e=>this.state.subscriptions.includes(e))).forEach((e=>{e.state.isSubscribed&&t.push(e),e.removeParentSet(this),this.state.removeSubscription(e,e.parentSetsCount>1)})),0!==t.length&&this.state.isSubscribed&&this.updateSubscription({subscribing:!1,subscriptions:t})}addSubscriptionSet(e){this.addSubscriptions(e.subscriptions)}removeSubscriptionSet(e){this.removeSubscriptions(e.subscriptions)}register(e){var t;const s=null!==(t=e.subscriptions)&&void 0!==t?t:this.state.subscriptions;s.forEach((({state:e})=>e.entity.increaseSubscriptionCount(this.state.id))),this.state.client.logger.trace(this.constructor.name,(()=>({messageType:"text",message:`Register subscription for real-time events: ${this}`}))),this.state.client.registerEventHandleCapable(this,e.cursor,s)}unregister(e){const t=null!=e?e:this.state.subscriptions;t.forEach((({state:e})=>e.entity.decreaseSubscriptionCount(this.state.id))),this.state.client.logger.trace(this.constructor.name,(()=>({messageType:"text",message:`Unregister subscription from real-time events: ${this}`}))),this.state.client.unregisterEventHandleCapable(this,t)}toString(){const e=this.state;return`${this.constructor.name} { id: ${this.id}, stateId: ${e.id}, clonesCount: ${Object.keys(this.state.clones).length}, isSubscribed: ${e.isSubscribed}, subscriptions: [${e.subscriptions.map((e=>e.toString())).join(", ")}] }`}}class Yt extends Vt{constructor(e){var t,s;const n=e.entity.subscriptionNames(null!==(s=null===(t=e.options)||void 0===t?void 0:t.receivePresenceEvents)&&void 0!==s&&s),r=new zt({[e.entity.subscriptionType==Wt.Channel?"channels":"channelGroups"]:n});super(e.client,r,e.options,e.client.subscriptionTimetoken),this.entity=e.entity}}class Zt extends Jt{constructor(e){"client"in e?e.client.logger.debug("Subscription",(()=>({messageType:"object",details:"Create subscription with parameters:",message:Object.assign({entity:e.entity},e.options?e.options:{})}))):e.state.client.logger.debug("Subscription","Create subscription clone"),super("state"in e?e.state:new Yt(e)),this.parents=[],this.handledUpdates=[],this.state.storeClone(this.id,this)}get state(){return super.state}get parentSetsCount(){return this.parents.length}handleEvent(e,t){var s;if(this.state.isSubscribed){if(this.parentSetsCount>0){const e=Y(t.data);if(this.handledUpdates.includes(e))return void this.state.client.logger.trace(this.constructor.name,`Message (${e}) already handled. Ignoring.`);this.handledUpdates.push(e),this.handledUpdates.length>10&&this.handledUpdates.shift()}this.state.subscriptionInput.contains(null!==(s=t.data.subscription)&&void 0!==s?s:t.data.channel)&&super.handleEvent(e,t)}}subscriptionInput(e=!1){return e&&this.state.entity.subscriptionsCount>0?new zt({}):this.state.subscriptionInput}cloneEmpty(){return new Zt({state:this.state})}dispose(){this.parentSetsCount>0?this.state.client.logger.debug(this.constructor.name,(()=>({messageType:"text",message:`'${this.state.entity.subscriptionNames()}' subscription still in use. Ignore dispose request.`}))):(this.handledUpdates.splice(0,this.handledUpdates.length),super.dispose())}invalidate(e=!1){e&&this.state.entity.decreaseSubscriptionCount(this.state.id),this.handledUpdates.splice(0,this.handledUpdates.length),super.invalidate(e)}addParentSet(e){this.parents.includes(e)||(this.parents.push(e),this.state.client.logger.trace(this.constructor.name,`Add parent subscription set for ${this.id}: ${e.id}. Parent subscription set count: ${this.parentSetsCount}`))}removeParentSet(e){const t=this.parents.indexOf(e);-1!==t&&(this.parents.splice(t,1),this.state.client.logger.trace(this.constructor.name,`Remove parent subscription set from ${this.id}: ${e.id}. Parent subscription set count: ${this.parentSetsCount}`)),0===this.parentSetsCount&&this.handledUpdates.splice(0,this.handledUpdates.length)}addSubscription(e){this.state.client.logger.debug(this.constructor.name,(()=>({messageType:"text",message:`Create set with subscription: ${e}`})));const t=new Qt({client:this.state.client,subscriptions:[this,e],options:this.state.options});return this.state.isSubscribed||e.state.isSubscribed?(this.state.client.logger.trace(this.constructor.name,"Subscribe resulting set because the receiver is already subscribed."),t.subscribe(),t):t}register(e){this.state.entity.increaseSubscriptionCount(this.state.id),this.state.client.logger.trace(this.constructor.name,(()=>({messageType:"text",message:`Register subscription for real-time events: ${this}`}))),this.state.client.registerEventHandleCapable(this,e.cursor)}unregister(e){this.state.entity.decreaseSubscriptionCount(this.state.id),this.state.client.logger.trace(this.constructor.name,(()=>({messageType:"text",message:`Unregister subscription from real-time events: ${this}`}))),this.handledUpdates.splice(0,this.handledUpdates.length),this.state.client.unregisterEventHandleCapable(this)}toString(){const e=this.state;return`${this.constructor.name} { id: ${this.id}, stateId: ${e.id}, entity: ${e.entity.subscriptionNames(!1).pop()}, clonesCount: ${Object.keys(e.clones).length}, isSubscribed: ${e.isSubscribed}, parentSetsCount: ${this.parentSetsCount}, cursor: ${e.cursor?e.cursor.timetoken:"not set"}, referenceTimetoken: ${e.referenceTimetoken?e.referenceTimetoken:"not set"} }`}}class es{constructor(e,t){this.subscriptionStateIds=[],this.client=t,this._nameOrId=e}get subscriptionType(){return Wt.Channel}subscriptionNames(e){return[this._nameOrId,...e&&!this._nameOrId.endsWith("-pnpres")?[`${this._nameOrId}-pnpres`]:[]]}subscription(e){return new Zt({client:this.client,entity:this,options:e})}get subscriptionsCount(){return this.subscriptionStateIds.length}increaseSubscriptionCount(e){this.subscriptionStateIds.includes(e)||this.subscriptionStateIds.push(e)}decreaseSubscriptionCount(e){{const t=this.subscriptionStateIds.indexOf(e);t>=0&&this.subscriptionStateIds.splice(t,1)}}toString(){return`${this.constructor.name} { nameOrId: ${this._nameOrId}, subscriptionsCount: ${this.subscriptionsCount} }`}}class ts extends es{get id(){return this._nameOrId}subscriptionNames(e){return[this.id]}}class ss extends es{get name(){return this._nameOrId}get subscriptionType(){return Wt.ChannelGroup}}class ns extends es{get id(){return this._nameOrId}subscriptionNames(e){return[this.id]}}class rs extends es{get name(){return this._nameOrId}}class is extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNRemoveChannelsFromGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${H(t)}`}get queryParameters(){return{remove:this.parameters.channels.join(",")}}}class as extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNAddChannelsToGroupOperation}validate(){const{keySet:{subscribeKey:e},channels:t,channelGroup:s}=this.parameters;return e?s?t?void 0:"Missing channels":"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${H(t)}`}get queryParameters(){return{add:this.parameters.channels.join(",")}}}class os extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNChannelsForGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e).payload.channels}}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${H(t)}`}}class cs extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNRemoveGroupOperation}validate(){return this.parameters.keySet.subscribeKey?this.parameters.channelGroup?void 0:"Missing Channel Group":"Missing Subscribe Key"}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}get path(){const{keySet:{subscribeKey:e},channelGroup:t}=this.parameters;return`/v1/channel-registration/sub-key/${e}/channel-group/${H(t)}/remove`}}class us extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNChannelGroupsOperation}validate(){if(!this.parameters.keySet.subscribeKey)return"Missing Subscribe Key"}parse(e){return i(this,void 0,void 0,(function*(){return{groups:this.deserializeResponse(e).payload.groups}}))}get path(){return`/v1/channel-registration/sub-key/${this.parameters.keySet.subscribeKey}/channel-group`}}class ls{constructor(e,t,s){this.sendRequest=s,this.logger=e,this.keySet=t}listChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"List channel group channels with parameters:"})));const s=new os(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=e=>{e&&this.logger.info("PubNub",`List channel group channels success. Received ${e.channels.length} channels.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}listGroups(e){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub","List all channel groups.");const t=new us({keySet:this.keySet}),s=e=>{e&&this.logger.info("PubNub",`List all channel groups success. Received ${e.groups.length} groups.`)};return e?this.sendRequest(t,((t,n)=>{s(n),e(t,n)})):this.sendRequest(t).then((e=>(s(e),e)))}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add channels to the channel group with parameters:"})));const s=new as(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.info("PubNub","Add channels to the channel group success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove channels from the channel group with parameters:"})));const s=new is(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.info("PubNub","Remove channels from the channel group success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}deleteGroup(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove a channel group with parameters:"})));const s=new cs(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.info("PubNub",`Remove a channel group success. Removed '${e.channelGroup}' channel group.'`)};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}}class hs extends ue{constructor(e){var t,s;super(),this.parameters=e,"apns2"===this.parameters.pushGateway&&(null!==(t=(s=this.parameters).environment)&&void 0!==t||(s.environment="development")),this.parameters.count&&this.parameters.count>1e3&&(this.parameters.count=1e3)}operation(){throw Error("Should be implemented in subclass.")}validate(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;return e?s?"add"!==t&&"remove"!==t||"channels"in this.parameters&&0!==this.parameters.channels.length?n?"apns2"!==this.parameters.pushGateway||this.parameters.topic?void 0:"Missing APNS2 topic":"Missing GW Type (pushGateway: gcm or apns2)":"Missing Channels":"Missing Device ID (device)":"Missing Subscribe Key"}get path(){const{keySet:{subscribeKey:e},action:t,device:s,pushGateway:n}=this.parameters;let r="apns2"===n?`/v2/push/sub-key/${e}/devices-apns2/${s}`:`/v1/push/sub-key/${e}/devices/${s}`;return"remove-device"===t&&(r=`${r}/remove`),r}get queryParameters(){const{start:e,count:t}=this.parameters;let s=Object.assign(Object.assign({type:this.parameters.pushGateway},e?{start:e}:{}),t&&t>0?{count:t}:{});if("channels"in this.parameters&&(s[this.parameters.action]=this.parameters.channels.join(",")),"apns2"===this.parameters.pushGateway){const{environment:e,topic:t}=this.parameters;s=Object.assign(Object.assign({},s),{environment:e,topic:t})}return s}}class ds extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove"}))}operation(){return le.PNRemovePushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class ps extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"list"}))}operation(){return le.PNPushNotificationEnabledChannelsOperation}parse(e){return i(this,void 0,void 0,(function*(){return{channels:this.deserializeResponse(e)}}))}}class gs extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"add"}))}operation(){return le.PNAddPushNotificationEnabledChannelsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class bs extends hs{constructor(e){super(Object.assign(Object.assign({},e),{action:"remove-device"}))}operation(){return le.PNRemoveAllPushNotificationsOperation}parse(e){const t=Object.create(null,{parse:{get:()=>super.parse}});return i(this,void 0,void 0,(function*(){return t.parse.call(this,e).then((e=>({})))}))}}class ms{constructor(e,t,s){this.sendRequest=s,this.logger=e,this.keySet=t}listChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"List push-enabled channels with parameters:"})));const s=new ps(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`List push-enabled channels success. Received ${e.channels.length} channels.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}addChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add push-enabled channels with parameters:"})));const s=new gs(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Add push-enabled channels success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}removeChannels(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove push-enabled channels with parameters:"})));const s=new ds(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Remove push-enabled channels success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}deleteDevice(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove push notifications for device with parameters:"})));const s=new bs(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=()=>{this.logger.debug("PubNub","Remove push notifications for device success.")};return t?this.sendRequest(s,(e=>{e.error||n(),t(e)})):this.sendRequest(s).then((e=>(n(),e)))}))}}class ys extends ue{constructor(e){var t,s,n,r,i,a;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(i=e.include).customFields)&&void 0!==s||(i.customFields=false),null!==(n=(a=e.include).totalCount)&&void 0!==n||(a.totalCount=false),null!==(r=e.limit)&&void 0!==r||(e.limit=100)}operation(){return le.PNGetAllChannelMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(","),count:`${e.totalCount}`},s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class fs extends ue{constructor(e){super({method:re.DELETE}),this.parameters=e}operation(){return le.PNRemoveChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${H(t)}`}}class vs extends ue{constructor(e){var t,s,n,r,i,a,o,c,u,l,h,d,p,g,b,m,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(b=e.include).channelFields)&&void 0!==a||(b.channelFields=false),null!==(o=(m=e.include).customChannelFields)&&void 0!==o||(m.customChannelFields=false),null!==(c=(y=e.include).channelStatusField)&&void 0!==c||(y.channelStatusField=false),null!==(u=(f=e.include).channelTypeField)&&void 0!==u||(f.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return le.PNGetMembershipsOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${H(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class Ss extends ue{constructor(e){var t,s,n,r,i,a,o,c,u,l,h,d,p,g,b,m,y,f;super({method:re.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(b=e.include).channelFields)&&void 0!==a||(b.channelFields=false),null!==(o=(m=e.include).customChannelFields)&&void 0!==o||(m.customChannelFields=false),null!==(c=(y=e.include).channelStatusField)&&void 0!==c||(y.channelStatusField=false),null!==(u=(f=e.include).channelTypeField)&&void 0!==u||(f.channelTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return le.PNSetMembershipsOperation}validate(){const{uuid:e,channels:t}=this.parameters;return e?t&&0!==t.length?void 0:"Channels cannot be empty":"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${H(t)}/channels`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["channel.status","channel.type","status"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.channelFields&&a.push("channel"),e.channelStatusField&&a.push("channel.status"),e.channelTypeField&&a.push("channel.type"),e.customChannelFields&&a.push("channel.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"})}get body(){const{channels:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{channel:{id:e}}:{channel:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class ws extends ue{constructor(e){var t,s,n,r;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(r=e.include).customFields)&&void 0!==s||(r.customFields=false),null!==(n=e.limit)&&void 0!==n||(e.limit=100)}operation(){return le.PNGetAllUUIDMetadataOperation}get path(){return`/v2/objects/${this.parameters.keySet.subscribeKey}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";return i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e)),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({include:["status","type",...e.customFields?["custom"]:[]].join(",")},void 0!==e.totalCount?{count:`${e.totalCount}`}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class Os extends ue{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return le.PNGetChannelMetadataOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${H(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}}class ks extends ue{constructor(e){var t,s,n;super({method:re.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true)}operation(){return le.PNSetChannelMetadataOperation}validate(){return this.parameters.channel?this.parameters.data?void 0:"Data cannot be empty":"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${H(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Cs extends ue{constructor(e){super({method:re.DELETE}),this.parameters=e,this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return le.PNRemoveUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${H(t)}`}}class Ps extends ue{constructor(e){var t,s,n,r,i,a,o,c,u,l,h,d,p,g,b,m,y,f;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(b=e.include).UUIDFields)&&void 0!==a||(b.UUIDFields=false),null!==(o=(m=e.include).customUUIDFields)&&void 0!==o||(m.customUUIDFields=false),null!==(c=(y=e.include).UUIDStatusField)&&void 0!==c||(y.UUIDStatusField=false),null!==(u=(f=e.include).UUIDTypeField)&&void 0!==u||(f.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return le.PNSetMembersOperation}validate(){if(!this.parameters.channel)return"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${H(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=[];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}}class js extends ue{constructor(e){var t,s,n,r,i,a,o,c,u,l,h,d,p,g,b,m,y,f;super({method:re.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(h=e.include).customFields)&&void 0!==s||(h.customFields=false),null!==(n=(d=e.include).totalCount)&&void 0!==n||(d.totalCount=false),null!==(r=(p=e.include).statusField)&&void 0!==r||(p.statusField=false),null!==(i=(g=e.include).typeField)&&void 0!==i||(g.typeField=false),null!==(a=(b=e.include).UUIDFields)&&void 0!==a||(b.UUIDFields=false),null!==(o=(m=e.include).customUUIDFields)&&void 0!==o||(m.customUUIDFields=false),null!==(c=(y=e.include).UUIDStatusField)&&void 0!==c||(y.UUIDStatusField=false),null!==(u=(f=e.include).UUIDTypeField)&&void 0!==u||(f.UUIDTypeField=false),null!==(l=e.limit)&&void 0!==l||(e.limit=100)}operation(){return le.PNSetMembersOperation}validate(){const{channel:e,uuids:t}=this.parameters;return e?t&&0!==t.length?void 0:"UUIDs cannot be empty":"Channel cannot be empty"}get path(){const{keySet:{subscribeKey:e},channel:t}=this.parameters;return`/v2/objects/${e}/channels/${H(t)}/uuids`}get queryParameters(){const{include:e,page:t,filter:s,sort:n,limit:r}=this.parameters;let i="";i="string"==typeof n?n:Object.entries(null!=n?n:{}).map((([e,t])=>null!==t?`${e}:${t}`:e));const a=["uuid.status","uuid.type","type"];return e.statusField&&a.push("status"),e.typeField&&a.push("type"),e.customFields&&a.push("custom"),e.UUIDFields&&a.push("uuid"),e.UUIDStatusField&&a.push("uuid.status"),e.UUIDTypeField&&a.push("uuid.type"),e.customUUIDFields&&a.push("uuid.custom"),Object.assign(Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({count:`${e.totalCount}`},a.length>0?{include:a.join(",")}:{}),s?{filter:s}:{}),(null==t?void 0:t.next)?{start:t.next}:{}),(null==t?void 0:t.prev)?{end:t.prev}:{}),r?{limit:r}:{}),i.length?{sort:i}:{})}get headers(){var e;return Object.assign(Object.assign({},null!==(e=super.headers)&&void 0!==e?e:{}),{"Content-Type":"application/json"})}get body(){const{uuids:e,type:t}=this.parameters;return JSON.stringify({[`${t}`]:e.map((e=>"string"==typeof e?{uuid:{id:e}}:{uuid:{id:e.id},status:e.status,type:e.type,custom:e.custom}))})}}class Es extends ue{constructor(e){var t,s,n;super(),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return le.PNGetUUIDMetadataOperation}validate(){if(!this.parameters.uuid)return"'uuid' cannot be empty"}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${H(t)}`}get queryParameters(){const{include:e}=this.parameters;return{include:["status","type",...e.customFields?["custom"]:[]].join(",")}}}class Ns extends ue{constructor(e){var t,s,n;super({method:re.PATCH}),this.parameters=e,null!==(t=e.include)&&void 0!==t||(e.include={}),null!==(s=(n=e.include).customFields)&&void 0!==s||(n.customFields=true),this.parameters.userId&&(this.parameters.uuid=this.parameters.userId)}operation(){return le.PNSetUUIDMetadataOperation}validate(){return this.parameters.uuid?this.parameters.data?void 0:"Data cannot be empty":"'uuid' cannot be empty"}get headers(){var e;let t=null!==(e=super.headers)&&void 0!==e?e:{};return this.parameters.ifMatchesEtag&&(t=Object.assign(Object.assign({},t),{"If-Match":this.parameters.ifMatchesEtag})),Object.assign(Object.assign({},t),{"Content-Type":"application/json"})}get path(){const{keySet:{subscribeKey:e},uuid:t}=this.parameters;return`/v2/objects/${e}/uuids/${H(t)}`}get queryParameters(){return{include:["status","type",...this.parameters.include.customFields?["custom"]:[]].join(",")}}get body(){return JSON.stringify(this.parameters.data)}}class Ts{constructor(e,t){this.keySet=e.keySet,this.configuration=e,this.sendRequest=t}get logger(){return this.configuration.logger()}getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{},details:"Get all UUID metadata objects with parameters:"}))),this._getAllUUIDMetadata(e,t)}))}_getAllUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new ws(Object.assign(Object.assign({},s),{keySet:this.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Get all UUID metadata success. Received ${e.totalCount} UUID metadata objects.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}))}getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{uuid:this.configuration.userId},details:`Get ${e&&"function"!=typeof e?"":" current"} UUID metadata object with parameters:`}))),this._getUUIDMetadata(e,t)}))}_getUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Es(Object.assign(Object.assign({},n),{keySet:this.keySet})),i=e=>{e&&this.logger.debug("PubNub",`Get UUID metadata object success. Received '${n.uuid}' UUID metadata object.`)};return t?this.sendRequest(r,((e,s)=>{i(s),t(e,s)})):this.sendRequest(r).then((e=>(i(e),e)))}))}setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set UUID metadata object with parameters:"}))),this._setUUIDMetadata(e,t)}))}_setUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId);const n=new Ns(Object.assign(Object.assign({},e),{keySet:this.keySet})),r=t=>{t&&this.logger.debug("PubNub",`Set UUID metadata object success. Updated '${e.uuid}' UUID metadata object.'`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}))}removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{uuid:this.configuration.userId},details:`Remove${e&&"function"!=typeof e?"":" current"} UUID metadata object with parameters:`}))),this._removeUUIDMetadata(e,t)}))}_removeUUIDMetadata(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId);const r=new Cs(Object.assign(Object.assign({},n),{keySet:this.keySet})),i=e=>{e&&this.logger.debug("PubNub",`Remove UUID metadata object success. Removed '${n.uuid}' UUID metadata object.`)};return t?this.sendRequest(r,((e,s)=>{i(s),t(e,s)})):this.sendRequest(r).then((e=>(i(e),e)))}))}getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{},details:"Get all Channel metadata objects with parameters:"}))),this._getAllChannelMetadata(e,t)}))}_getAllChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0);const n=new ys(Object.assign(Object.assign({},s),{keySet:this.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Get all Channel metadata objects success. Received ${e.totalCount} Channel metadata objects.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}))}getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get Channel metadata object with parameters:"}))),this._getChannelMetadata(e,t)}))}_getChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new Os(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Get Channel metadata object success. Received '${e.channel}' Channel metadata object.'`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set Channel metadata object with parameters:"}))),this._setChannelMetadata(e,t)}))}_setChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new ks(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Set Channel metadata object success. Updated '${e.channel}' Channel metadata object.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Channel metadata object with parameters:"}))),this._removeChannelMetadata(e,t)}))}_removeChannelMetadata(e,t){return i(this,void 0,void 0,(function*(){const s=new fs(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Remove Channel metadata object success. Removed '${e.channel}' Channel metadata object.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}getChannelMembers(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get channel members with parameters:"})));const s=new Ps(Object.assign(Object.assign({},e),{keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Get channel members success. Received ${e.totalCount} channel members.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}setChannelMembers(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set channel members with parameters:"})));const s=new js(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Set channel members success. There are ${e.totalCount} channel members now.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}removeChannelMembers(e,t){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove channel members with parameters:"})));const s=new js(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Remove channel members success. There are ${e.totalCount} channel members now.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}))}getMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;const n=e&&"function"!=typeof e?e:{};null!=t||(t="function"==typeof e?e:void 0),n.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),n.uuid=n.userId),null!==(s=n.uuid)&&void 0!==s||(n.uuid=this.configuration.userId),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},n),details:"Get memberships with parameters:"})));const r=new vs(Object.assign(Object.assign({},n),{keySet:this.keySet})),i=e=>{e&&this.logger.debug("PubNub",`Get memberships success. Received ${e.totalCount} memberships.`)};return t?this.sendRequest(r,((e,s)=>{i(s),t(e,s)})):this.sendRequest(r).then((e=>(i(e),e)))}))}setMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set memberships with parameters:"})));const n=new Ss(Object.assign(Object.assign({},e),{type:"set",keySet:this.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Set memberships success. There are ${e.totalCount} memberships now.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s;e.userId&&(this.logger.warn("PubNub","'userId' parameter is deprecated. Use 'uuid' instead."),e.uuid=e.userId),null!==(s=e.uuid)&&void 0!==s||(e.uuid=this.configuration.userId),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove memberships with parameters:"})));const n=new Ss(Object.assign(Object.assign({},e),{type:"delete",keySet:this.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Remove memberships success. There are ${e.totalCount} memberships now.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n;if(this.logger.warn("PubNub","'fetchMemberships' is deprecated. Use 'pubnub.objects.getChannelMembers' or 'pubnub.objects.getMemberships' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch memberships with parameters:"}))),"spaceId"in e){const n=e,r={channel:null!==(s=n.spaceId)&&void 0!==s?s:n.channel,filter:n.filter,limit:n.limit,page:n.page,include:Object.assign({},n.include),sort:n.sort?Object.fromEntries(Object.entries(n.sort).map((([e,t])=>[e.replace("user","uuid"),t]))):void 0},i=e=>({status:e.status,data:e.data.map((e=>({user:e.uuid,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getChannelMembers(r,((e,s)=>{t(e,s?i(s):s)})):this.getChannelMembers(r).then(i)}const r=e,i={uuid:null!==(n=r.userId)&&void 0!==n?n:r.uuid,filter:r.filter,limit:r.limit,page:r.page,include:Object.assign({},r.include),sort:r.sort?Object.fromEntries(Object.entries(r.sort).map((([e,t])=>[e.replace("space","channel"),t]))):void 0},a=e=>({status:e.status,data:e.data.map((e=>({space:e.channel,custom:e.custom,updated:e.updated,eTag:e.eTag}))),totalCount:e.totalCount,next:e.next,prev:e.prev});return t?this.getMemberships(i,((e,s)=>{t(e,s?a(s):s)})):this.getMemberships(i).then(a)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r,i,a,o;if(this.logger.warn("PubNub","'addMemberships' is deprecated. Use 'pubnub.objects.setChannelMembers' or 'pubnub.objects.setMemberships' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add memberships with parameters:"}))),"spaceId"in e){const i=e,a={channel:null!==(s=i.spaceId)&&void 0!==s?s:i.channel,uuids:null!==(r=null===(n=i.users)||void 0===n?void 0:n.map((e=>"string"==typeof e?e:{id:e.userId,custom:e.custom})))&&void 0!==r?r:i.uuids,limit:0};return t?this.setChannelMembers(a,t):this.setChannelMembers(a)}const c=e,u={uuid:null!==(i=c.userId)&&void 0!==i?i:c.uuid,channels:null!==(o=null===(a=c.spaces)||void 0===a?void 0:a.map((e=>"string"==typeof e?e:{id:e.spaceId,custom:e.custom})))&&void 0!==o?o:c.channels,limit:0};return t?this.setMemberships(u,t):this.setMemberships(u)}))}}class _s extends ue{constructor(){super()}operation(){return le.PNTimeOperation}parse(e){return i(this,void 0,void 0,(function*(){return{timetoken:this.deserializeResponse(e)[0]}}))}get path(){return"/time/0"}}class Is extends ue{constructor(e){super(),this.parameters=e}operation(){return le.PNDownloadFileOperation}validate(){const{channel:e,id:t,name:s}=this.parameters;return e?t?s?void 0:"file name can't be empty":"file id can't be empty":"channel can't be empty"}parse(e){return i(this,void 0,void 0,(function*(){const{cipherKey:t,crypto:s,cryptography:n,name:r,PubNubFile:i}=this.parameters,a=e.headers["content-type"];let o,c=e.body;return i.supportsEncryptFile&&(t||s)&&(t&&n?c=yield n.decrypt(t,c):!t&&s&&(o=yield s.decryptFile(i.create({data:c,name:r,mimeType:a}),i))),o||i.create({data:c,name:r,mimeType:a})}))}get path(){const{keySet:{subscribeKey:e},channel:t,id:s,name:n}=this.parameters;return`/v1/files/${e}/channels/${H(t)}/files/${s}/${n}`}}class Ms{static notificationPayload(e,t){return new we(e,t)}static generateUUID(){return K.createUUID()}constructor(e){if(this.eventHandleCapable={},this.entities={},this._configuration=e.configuration,this.cryptography=e.cryptography,this.tokenManager=e.tokenManager,this.transport=e.transport,this.crypto=e.crypto,this.logger.debug("PubNub",(()=>({messageType:"object",message:e.configuration,details:"Create with configuration:",ignoredKeys:(e,t)=>"function"==typeof t[e]||e.startsWith("_")}))),this._objects=new Ts(this._configuration,this.sendRequest.bind(this)),this._channelGroups=new ls(this._configuration.logger(),this._configuration.keySet,this.sendRequest.bind(this)),this._push=new ms(this._configuration.logger(),this._configuration.keySet,this.sendRequest.bind(this)),this.eventDispatcher=new ge,this._configuration.enableEventEngine){this.logger.debug("PubNub","Using new subscription loop management.");let e=this._configuration.getHeartbeatInterval();this.presenceState={},e&&(this.presenceEventEngine=new Ye({heartbeat:(e,t)=>(this.logger.trace("PresenceEventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Heartbeat with parameters:"}))),this.heartbeat(e,t)),leave:e=>{this.logger.trace("PresenceEventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave with parameters:"}))),this.makeUnsubscribe(e,(()=>{}))},heartbeatDelay:()=>new Promise(((t,s)=>{e=this._configuration.getHeartbeatInterval(),e?setTimeout(t,1e3*e):s(new d("Heartbeat interval has been reset."))})),emitStatus:e=>this.emitStatus(e),config:this._configuration,presenceState:this.presenceState})),this.eventEngine=new St({handshake:e=>(this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Handshake with parameters:",ignoredKeys:["abortSignal","crypto","timeout","keySet","getFileUrl"]}))),this.subscribeHandshake(e)),receiveMessages:e=>(this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Receive messages with parameters:",ignoredKeys:["abortSignal","crypto","timeout","keySet","getFileUrl"]}))),this.subscribeReceiveMessages(e)),delay:e=>new Promise((t=>setTimeout(t,e))),join:e=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Join with parameters:"}))),this.join(e)},leave:e=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave with parameters:"}))),this.leave(e)},leaveAll:e=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave all with parameters:"}))),this.leaveAll(e)},presenceReconnect:e=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Reconnect with parameters:"}))),this.presenceReconnect(e)},presenceDisconnect:e=>{this.logger.trace("EventEngine",(()=>({messageType:"object",message:Object.assign({},e),details:"Disconnect with parameters:"}))),this.presenceDisconnect(e)},presenceState:this.presenceState,config:this._configuration,emitMessages:(e,t)=>{try{this.logger.debug("EventEngine",(()=>({messageType:"object",message:t.map((e=>{const t=e.type===he.Message||e.type===he.Signal?Y(e.data.message):void 0;return t?{type:e.type,data:Object.assign(Object.assign({},e.data),{pn_mfp:t})}:e})),details:"Received events:"}))),t.forEach((t=>this.emitEvent(e,t)))}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.emitStatus(t)}},emitStatus:e=>this.emitStatus(e)})}else this.logger.debug("PubNub","Using legacy subscription loop management."),this.subscriptionManager=new ye(this._configuration,((e,t)=>{try{this.emitEvent(e,t)}catch(e){const t={error:!0,category:h.PNUnknownCategory,errorData:e,statusCode:0};this.emitStatus(t)}}),this.emitStatus.bind(this),((e,t)=>{this.logger.trace("SubscriptionManager",(()=>({messageType:"object",message:Object.assign({},e),details:"Subscribe with parameters:",ignoredKeys:["crypto","timeout","keySet","getFileUrl"]}))),this.makeSubscribe(e,t)}),((e,t)=>(this.logger.trace("SubscriptionManager",(()=>({messageType:"object",message:Object.assign({},e),details:"Heartbeat with parameters:",ignoredKeys:["crypto","timeout","keySet","getFileUrl"]}))),this.heartbeat(e,t))),((e,t)=>{this.logger.trace("SubscriptionManager",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave with parameters:"}))),this.makeUnsubscribe(e,t)}),this.time.bind(this))}get configuration(){return this._configuration}get _config(){return this.configuration}get authKey(){var e;return null!==(e=this._configuration.authKey)&&void 0!==e?e:void 0}getAuthKey(){return this.authKey}setAuthKey(e){this.logger.debug("PubNub",`Set auth key: ${e}`),this._configuration.setAuthKey(e)}get userId(){return this._configuration.userId}set userId(e){if(!e||"string"!=typeof e||0===e.trim().length){const e=new Error("Missing or invalid userId parameter. Provide a valid string userId");throw this.logger.error("PubNub",(()=>({messageType:"error",message:e}))),e}this.logger.debug("PubNub",`Set user ID: ${e}`),this._configuration.userId=e}getUserId(){return this._configuration.userId}setUserId(e){if(!e||"string"!=typeof e||0===e.trim().length){const e=new Error("Missing or invalid userId parameter. Provide a valid string userId");throw this.logger.error("PubNub",(()=>({messageType:"error",message:e}))),e}this.logger.debug("PubNub",`Set user ID: ${e}`),this._configuration.userId=e}get filterExpression(){var e;return null!==(e=this._configuration.getFilterExpression())&&void 0!==e?e:void 0}getFilterExpression(){return this.filterExpression}set filterExpression(e){this.logger.debug("PubNub",`Set filter expression: ${e}`),this._configuration.setFilterExpression(e)}setFilterExpression(e){this.logger.debug("PubNub",`Set filter expression: ${e}`),this.filterExpression=e}get cipherKey(){return this._configuration.getCipherKey()}set cipherKey(e){this._configuration.setCipherKey(e)}setCipherKey(e){this.logger.debug("PubNub",`Set cipher key: ${e}`),this.cipherKey=e}set heartbeatInterval(e){this.logger.debug("PubNub",`Set heartbeat interval: ${e}`),this._configuration.setHeartbeatInterval(e)}setHeartbeatInterval(e){this.logger.debug("PubNub",`Set heartbeat interval: ${e}`),this.heartbeatInterval=e}get logger(){return this._configuration.logger()}getVersion(){return this._configuration.getVersion()}_addPnsdkSuffix(e,t){this.logger.debug("PubNub",`Add '${e}' 'pnsdk' suffix: ${t}`),this._configuration._addPnsdkSuffix(e,t)}getUUID(){return this.userId}setUUID(e){this.logger.warn("PubNub","'setUserId` is deprecated, please use 'setUserId' or 'userId' setter instead."),this.logger.debug("PubNub",`Set UUID: ${e}`),this.userId=e}get customEncrypt(){return this._configuration.getCustomEncrypt()}get customDecrypt(){return this._configuration.getCustomDecrypt()}channel(e){let t=this.entities[`${e}_ch`];return t||(t=this.entities[`${e}_ch`]=new rs(e,this)),t}channelGroup(e){let t=this.entities[`${e}_chg`];return t||(t=this.entities[`${e}_chg`]=new ss(e,this)),t}channelMetadata(e){let t=this.entities[`${e}_chm`];return t||(t=this.entities[`${e}_chm`]=new ts(e,this)),t}userMetadata(e){let t=this.entities[`${e}_um`];return t||(t=this.entities[`${e}_um`]=new ns(e,this)),t}subscriptionSet(e){var t,s;{const n=[];return null===(t=e.channels)||void 0===t||t.forEach((e=>n.push(this.channel(e)))),null===(s=e.channelGroups)||void 0===s||s.forEach((e=>n.push(this.channelGroup(e)))),new Qt({client:this,entities:n,options:e.subscriptionOptions})}}sendRequest(e,t){return i(this,void 0,void 0,(function*(){const s=e.validate();if(s){const e=(n=s,p(Object.assign({message:n},{}),h.PNValidationErrorCategory));if(this.logger.error("PubNub",(()=>({messageType:"error",message:e}))),t)return t(e,null);throw new d("Validation failed, check status for details",e)}var n;const r=e.request(),i=e.operation();r.formData&&r.formData.length>0||i===le.PNDownloadFileOperation?r.timeout=this._configuration.getFileTimeout():i===le.PNSubscribeOperation||i===le.PNReceiveMessagesOperation?r.timeout=this._configuration.getSubscribeTimeout():r.timeout=this._configuration.getTransactionTimeout();const a={error:!1,operation:i,category:h.PNAcknowledgmentCategory,statusCode:0},[o,c]=this.transport.makeSendable(r);return e.cancellationController=c||null,o.then((t=>{if(a.statusCode=t.status,200!==t.status&&204!==t.status){const e=Ms.decoder.decode(t.body),s=t.headers["content-type"];if(s||-1!==s.indexOf("javascript")||-1!==s.indexOf("json")){const t=JSON.parse(e);"object"==typeof t&&"error"in t&&t.error&&"object"==typeof t.error&&(a.errorData=t.error)}else a.responseText=e}return e.parse(t)})).then((e=>t?t(a,e):e)).catch((e=>{const s=e instanceof _?e:_.create(e);if(t)return s.category!==h.PNCancelledCategory&&this.logger.error("PubNub",(()=>({messageType:"error",message:s.toPubNubError(i,"REST API request processing error, check status for details")}))),t(s.toStatus(i),null);const n=s.toPubNubError(i,"REST API request processing error, check status for details");throw s.category!==h.PNCancelledCategory&&this.logger.error("PubNub",(()=>({messageType:"error",message:n}))),n}))}))}destroy(e=!1){this.logger.info("PubNub","Destroying PubNub client."),this._globalSubscriptionSet&&(this._globalSubscriptionSet.invalidate(!0),this._globalSubscriptionSet=void 0),Object.values(this.eventHandleCapable).forEach((e=>e.invalidate(!0))),this.eventHandleCapable={},this.subscriptionManager?(this.subscriptionManager.unsubscribeAll(e),this.subscriptionManager.disconnect()):this.eventEngine&&this.eventEngine.unsubscribeAll(e),this.presenceEventEngine&&this.presenceEventEngine.leaveAll(e)}stop(){this.logger.warn("PubNub","'stop' is deprecated, please use 'destroy' instead."),this.destroy()}publish(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Publish with parameters:"})));const s=!1===e.replicate&&!1===e.storeInHistory,n=new wt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()})),r=e=>{e&&this.logger.debug("PubNub",`${s?"Fire":"Publish"} success with timetoken: ${e.timetoken}`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}}))}signal(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Signal with parameters:"})));const s=new Ot(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Publish success with timetoken: ${e.timetoken}`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}fire(e,t){return i(this,void 0,void 0,(function*(){return this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fire with parameters:"}))),null!=t||(t=()=>{}),this.publish(Object.assign(Object.assign({},e),{replicate:!1,storeInHistory:!1}),t)}))}get globalSubscriptionSet(){return this._globalSubscriptionSet||(this._globalSubscriptionSet=this.subscriptionSet({})),this._globalSubscriptionSet}get subscriptionTimetoken(){return this.subscriptionManager?this.subscriptionManager.subscriptionTimetoken:this.eventEngine?this.eventEngine.subscriptionTimetoken:void 0}getSubscribedChannels(){return this.subscriptionManager?this.subscriptionManager.subscribedChannels:this.eventEngine?this.eventEngine.getSubscribedChannels():[]}getSubscribedChannelGroups(){return this.subscriptionManager?this.subscriptionManager.subscribedChannelGroups:this.eventEngine?this.eventEngine.getSubscribedChannelGroups():[]}registerEventHandleCapable(e,t,s){{let n;this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign(Object.assign({subscription:e},t?{cursor:t}:[]),s?{subscriptions:s}:{}),details:"Register event handle capable:"}))),this.eventHandleCapable[e.state.id]||(this.eventHandleCapable[e.state.id]=e),s&&0!==s.length?(n=new zt({}),s.forEach((e=>n.add(e.subscriptionInput(!1))))):n=e.subscriptionInput(!1);const r={};r.channels=n.channels,r.channelGroups=n.channelGroups,t&&(r.timetoken=t.timetoken),this.subscriptionManager?this.subscriptionManager.subscribe(r):this.eventEngine&&this.eventEngine.subscribe(r)}}unregisterEventHandleCapable(e,t){{if(!this.eventHandleCapable[e.state.id])return;const s=[];let n;if(this.logger.trace("PubNub",(()=>({messageType:"object",message:{subscription:e,subscriptions:t},details:"Unregister event handle capable:"}))),t&&0!==t.length||delete this.eventHandleCapable[e.state.id],t&&0!==t.length?(n=new zt({}),t.forEach((e=>{const t=e.subscriptionInput(!0);t.isEmpty?s.push(e):n.add(t)}))):(n=e.subscriptionInput(!0),n.isEmpty&&s.push(e)),s.length>0&&this.logger.trace("PubNub",(()=>{const e=[];return s[0]instanceof Qt?s[0].subscriptions.forEach((t=>e.push(t.state.entity))):s.forEach((t=>e.push(t.state.entity))),{messageType:"object",message:{entities:e},details:"Can't unregister event handle capable because entities still in use:"}})),n.isEmpty)return;const r={};r.channels=n.channels,r.channelGroups=n.channelGroups,this.subscriptionManager?this.subscriptionManager.unsubscribe(r):this.eventEngine&&this.eventEngine.unsubscribe(r)}}subscribe(e){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Subscribe with parameters:"})));const t=this.subscriptionSet(Object.assign(Object.assign({},e),{subscriptionOptions:{receivePresenceEvents:e.withPresence}}));this.globalSubscriptionSet.addSubscriptionSet(t),t.dispose();const s="number"==typeof e.timetoken?`${e.timetoken}`:e.timetoken;this.globalSubscriptionSet.subscribe({timetoken:s})}}makeSubscribe(e,t){{const s=new pe(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)}));if(this.sendRequest(s,((e,n)=>{var r;this.subscriptionManager&&(null===(r=this.subscriptionManager.abort)||void 0===r?void 0:r.identifier)===s.requestIdentifier&&(this.subscriptionManager.abort=null),t(e,n)})),this.subscriptionManager){const e=()=>s.abort("Cancel long-poll subscribe request");e.identifier=s.requestIdentifier,this.subscriptionManager.abort=e}}}unsubscribe(e){{if(this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Unsubscribe with parameters:"}))),!this._globalSubscriptionSet)return void this.logger.debug("PubNub","There are no active subscriptions. Ignore.");const t=this.globalSubscriptionSet.subscriptions.filter((t=>{var s,n;const r=t.subscriptionInput(!1);if(r.isEmpty)return!1;for(const t of null!==(s=e.channels)&&void 0!==s?s:[])if(r.contains(t))return!0;for(const t of null!==(n=e.channelGroups)&&void 0!==n?n:[])if(r.contains(t))return!0}));t.length>0&&this.globalSubscriptionSet.removeSubscriptions(t)}}makeUnsubscribe(e,t){{let{channels:s,channelGroups:n}=e;if(this._configuration.getKeepPresenceChannelsInPresenceRequests()||(n&&(n=n.filter((e=>!e.endsWith("-pnpres")))),s&&(s=s.filter((e=>!e.endsWith("-pnpres"))))),0===(null!=n?n:[]).length&&0===(null!=s?s:[]).length)return t({error:!1,operation:le.PNUnsubscribeOperation,category:h.PNAcknowledgmentCategory,statusCode:200});this.sendRequest(new Nt({channels:s,channelGroups:n,keySet:this._configuration.keySet}),t)}}unsubscribeAll(){this.logger.debug("PubNub","Unsubscribe all channels and groups"),this._globalSubscriptionSet&&this._globalSubscriptionSet.invalidate(!1),Object.values(this.eventHandleCapable).forEach((e=>e.invalidate(!1))),this.eventHandleCapable={},this.subscriptionManager?this.subscriptionManager.unsubscribeAll():this.eventEngine&&this.eventEngine.unsubscribeAll()}disconnect(e=!1){this.logger.debug("PubNub","Disconnect (while offline? "+(e?"yes":"no")),this.subscriptionManager?this.subscriptionManager.disconnect():this.eventEngine&&this.eventEngine.disconnect(e)}reconnect(e){this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Reconnect with parameters:"}))),this.subscriptionManager?this.subscriptionManager.reconnect():this.eventEngine&&this.eventEngine.reconnect(null!=e?e:{})}subscribeHandshake(e){return i(this,void 0,void 0,(function*(){{const t=new Ct(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort("Cancel subscribe handshake request")}));return this.sendRequest(t).then((e=>(s(),e.cursor)))}}))}subscribeReceiveMessages(e){return i(this,void 0,void 0,(function*(){{const t=new kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),s=e.abortSignal.subscribe((e=>{t.abort("Cancel long-poll subscribe request")}));return this.sendRequest(t).then((e=>(s(),e)))}}))}getMessageActions(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get message actions with parameters:"})));const s=new Rt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Get message actions success. Received ${e.data.length} message actions.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}addMessageAction(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Add message action with parameters:"})));const s=new Ft(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Message action add success. Message action added with timetoken: ${e.data.actionTimetoken}`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}removeMessageAction(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove message action with parameters:"})));const s=new Dt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Message action remove success. Removed message action with ${e.actionTimetoken} timetoken.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}fetchMessages(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch messages with parameters:"})));const s=new $t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule(),getFileUrl:this.getFileUrl.bind(this)})),n=e=>{if(!e)return;const t=Object.values(e.channels).reduce(((e,t)=>e+t.length),0);this.logger.debug("PubNub",`Fetch messages success. Received ${t} messages.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}deleteMessages(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Delete messages with parameters:"})));const s=new It(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub","Delete messages success.")};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}messageCounts(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get messages count with parameters:"})));const s=new Mt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=t=>{if(!t)return;const s=Object.values(t.channels).reduce(((e,t)=>e+t),0);this.logger.debug("PubNub",`Get messages count success. There are ${s} messages since provided reference timetoken${e.channelTimetokens?e.channelTimetokens.join(","):""}.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}history(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch history with parameters:"})));const s=new At(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()})),n=e=>{e&&this.logger.debug("PubNub",`Fetch history success. Received ${e.messages.length} messages.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}hereNow(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Here now with parameters:"})));const s=new _t(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`Here now success. There are ${e.totalOccupancy} participants in ${e.totalChannels} channels.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}whereNow(e,t){return i(this,void 0,void 0,(function*(){var s;{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Where now with parameters:"})));const n=new Tt({uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet}),r=e=>{e&&this.logger.debug("PubNub",`Where now success. Currently present in ${e.channels.length} channels.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}}))}getState(e,t){return i(this,void 0,void 0,(function*(){var s;{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Get presence state with parameters:"})));const n=new Pt(Object.assign(Object.assign({},e),{uuid:null!==(s=e.uuid)&&void 0!==s?s:this._configuration.userId,keySet:this._configuration.keySet})),r=e=>{e&&this.logger.debug("PubNub",`Get presence state success. Received presence state for ${Object.keys(e.channels).length} channels.`)};return t?this.sendRequest(n,((e,s)=>{r(s),t(e,s)})):this.sendRequest(n).then((e=>(r(e),e)))}}))}setState(e,t){return i(this,void 0,void 0,(function*(){var s,n;{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Set presence state with parameters:"})));const{keySet:r,userId:i}=this._configuration,a=this._configuration.getPresenceTimeout();let o;if(this._configuration.enableEventEngine&&this.presenceState){const t=this.presenceState;null===(s=e.channels)||void 0===s||s.forEach((s=>t[s]=e.state)),"channelGroups"in e&&(null===(n=e.channelGroups)||void 0===n||n.forEach((s=>t[s]=e.state)))}o="withHeartbeat"in e&&e.withHeartbeat?new Et(Object.assign(Object.assign({},e),{keySet:r,heartbeat:a})):new jt(Object.assign(Object.assign({},e),{keySet:r,uuid:i}));const c=e=>{e&&this.logger.debug("PubNub","Set presence state success."+(o instanceof Et?" Presence state has been set using heartbeat endpoint.":""))};return this.subscriptionManager&&this.subscriptionManager.setState(e),t?this.sendRequest(o,((e,s)=>{c(s),t(e,s)})):this.sendRequest(o).then((e=>(c(e),e)))}}))}presence(e){var t;this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Change presence with parameters:"}))),null===(t=this.subscriptionManager)||void 0===t||t.changePresence(e)}heartbeat(e,t){return i(this,void 0,void 0,(function*(){{this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Heartbeat with parameters:"})));let{channels:s,channelGroups:n}=e;if(this._configuration.getKeepPresenceChannelsInPresenceRequests()||(n&&(n=n.filter((e=>!e.endsWith("-pnpres")))),s&&(s=s.filter((e=>!e.endsWith("-pnpres"))))),0===(null!=n?n:[]).length&&0===(null!=s?s:[]).length){const e={error:!1,operation:le.PNHeartbeatOperation,category:h.PNAcknowledgmentCategory,statusCode:200};return this.logger.trace("PubNub","There are no active subscriptions. Ignore."),t?t(e,{}):Promise.resolve(e)}const r=new Et(Object.assign(Object.assign({},e),{channels:s,channelGroups:n,keySet:this._configuration.keySet})),i=e=>{e&&this.logger.trace("PubNub","Heartbeat success.")};return t?this.sendRequest(r,((e,s)=>{i(s),t(e,s)})):this.sendRequest(r).then((e=>(i(e),e)))}}))}join(e){this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Join with parameters:"}))),this.presenceEventEngine?this.presenceEventEngine.join(e):this.heartbeat(Object.assign(Object.assign({channels:e.channels,channelGroups:e.groups},this._configuration.maintainPresenceState&&this.presenceState&&Object.keys(this.presenceState).length>0&&{state:this.presenceState}),{heartbeat:this._configuration.getPresenceTimeout()}),(()=>{}))}presenceReconnect(e){this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Presence reconnect with parameters:"}))),this.presenceEventEngine?this.presenceEventEngine.reconnect():this.heartbeat(Object.assign(Object.assign({channels:e.channels,channelGroups:e.groups},this._configuration.maintainPresenceState&&{state:this.presenceState}),{heartbeat:this._configuration.getPresenceTimeout()}),(()=>{}))}leave(e){var t;this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave with parameters:"}))),this.presenceEventEngine?null===(t=this.presenceEventEngine)||void 0===t||t.leave(e):this.makeUnsubscribe({channels:e.channels,channelGroups:e.groups},(()=>{}))}leaveAll(e={}){this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Leave all with parameters:"}))),this.presenceEventEngine?this.presenceEventEngine.leaveAll(!!e.isOffline):e.isOffline||this.makeUnsubscribe({channels:e.channels,channelGroups:e.groups},(()=>{}))}presenceDisconnect(e){this.logger.trace("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Presence disconnect parameters:"}))),this.presenceEventEngine?this.presenceEventEngine.disconnect(!!e.isOffline):e.isOffline||this.makeUnsubscribe({channels:e.channels,channelGroups:e.groups},(()=>{}))}grantToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Token error: PAM module disabled")}))}revokeToken(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Revoke Token error: PAM module disabled")}))}get token(){return this.tokenManager&&this.tokenManager.getToken()}getToken(){return this.token}set token(e){this.tokenManager&&this.tokenManager.setToken(e)}setToken(e){this.token=e}parseToken(e){return this.tokenManager&&this.tokenManager.parseToken(e)}grant(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant error: PAM module disabled")}))}audit(e,t){return i(this,void 0,void 0,(function*(){throw new Error("Grant Permissions error: PAM module disabled")}))}get objects(){return this._objects}fetchUsers(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchUsers' is deprecated. Use 'pubnub.objects.getAllUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{},details:"Fetch all User objects with parameters:"}))),this.objects._getAllUUIDMetadata(e,t)}))}fetchUser(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchUser' is deprecated. Use 'pubnub.objects.getUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{uuid:this.userId},details:`Fetch${e&&"function"!=typeof e?"":" current"} User object with parameters:`}))),this.objects._getUUIDMetadata(e,t)}))}createUser(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'createUser' is deprecated. Use 'pubnub.objects.setUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create User object with parameters:"}))),this.objects._setUUIDMetadata(e,t)}))}updateUser(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'updateUser' is deprecated. Use 'pubnub.objects.setUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update User object with parameters:"}))),this.objects._setUUIDMetadata(e,t)}))}removeUser(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'removeUser' is deprecated. Use 'pubnub.objects.removeUUIDMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{uuid:this.userId},details:`Remove${e&&"function"!=typeof e?"":" current"} User object with parameters:`}))),this.objects._removeUUIDMetadata(e,t)}))}fetchSpaces(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchSpaces' is deprecated. Use 'pubnub.objects.getAllChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:e&&"function"!=typeof e?e:{},details:"Fetch all Space objects with parameters:"}))),this.objects._getAllChannelMetadata(e,t)}))}fetchSpace(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'fetchSpace' is deprecated. Use 'pubnub.objects.getChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Fetch Space object with parameters:"}))),this.objects._getChannelMetadata(e,t)}))}createSpace(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'createSpace' is deprecated. Use 'pubnub.objects.setChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Create Space object with parameters:"}))),this.objects._setChannelMetadata(e,t)}))}updateSpace(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'updateSpace' is deprecated. Use 'pubnub.objects.setChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update Space object with parameters:"}))),this.objects._setChannelMetadata(e,t)}))}removeSpace(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'removeSpace' is deprecated. Use 'pubnub.objects.removeChannelMetadata' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove Space object with parameters:"}))),this.objects._removeChannelMetadata(e,t)}))}fetchMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.fetchMemberships(e,t)}))}addMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.objects.addMemberships(e,t)}))}updateMemberships(e,t){return i(this,void 0,void 0,(function*(){return this.logger.warn("PubNub","'addMemberships' is deprecated. Use 'pubnub.objects.setChannelMembers' or 'pubnub.objects.setMemberships' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Update memberships with parameters:"}))),this.objects.addMemberships(e,t)}))}removeMemberships(e,t){return i(this,void 0,void 0,(function*(){var s,n,r;{if(this.logger.warn("PubNub","'removeMemberships' is deprecated. Use 'pubnub.objects.removeMemberships' or 'pubnub.objects.removeChannelMembers' instead."),this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Remove memberships with parameters:"}))),"spaceId"in e){const r=e,i={channel:null!==(s=r.spaceId)&&void 0!==s?s:r.channel,uuids:null!==(n=r.userIds)&&void 0!==n?n:r.uuids,limit:0};return t?this.objects.removeChannelMembers(i,t):this.objects.removeChannelMembers(i)}const i=e,a={uuid:i.userId,channels:null!==(r=i.spaceIds)&&void 0!==r?r:i.channels,limit:0};return t?this.objects.removeMemberships(a,t):this.objects.removeMemberships(a)}}))}get channelGroups(){return this._channelGroups}get push(){return this._push}sendFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Send file with parameters:"})));const s=new Bt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,fileUploadPublishRetryLimit:this._configuration.fileUploadPublishRetryLimit,file:e.file,sendRequest:this.sendRequest.bind(this),publishFile:this.publishFile.bind(this),crypto:this._configuration.getCryptoModule(),cryptography:this.cryptography?this.cryptography:void 0})),n={error:!1,operation:le.PNPublishFileOperation,category:h.PNAcknowledgmentCategory,statusCode:0},r=e=>{e&&this.logger.debug("PubNub",`Send file success. File shared with ${e.id} ID.`)};return s.process().then((e=>(n.statusCode=e.status,r(e),t?t(n,e):e))).catch((e=>{let s;throw e instanceof d?s=e.status:e instanceof _&&(s=e.toStatus(n.operation)),this.logger.error("PubNub",(()=>({messageType:"error",message:new d("File sending error. Check status for details",s)}))),t&&s&&t(s,null),new d("REST API request processing error. Check status for details",s)}))}}))}publishFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Publish file message with parameters:"})));const s=new xt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,crypto:this._configuration.getCryptoModule()})),n=e=>{e&&this.logger.debug("PubNub",`Publish file message success. File message published with timetoken: ${e.timetoken}`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}listFiles(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"List files with parameters:"})));const s=new Kt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=e=>{e&&this.logger.debug("PubNub",`List files success. There are ${e.count} uploaded files.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}getFileUrl(e){var t;{const s=this.transport.request(new Gt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})).request()),n=null!==(t=s.queryParameters)&&void 0!==t?t:{},r=Object.keys(n).map((e=>{const t=n[e];return Array.isArray(t)?t.map((t=>`${e}=${H(t)}`)).join("&"):`${e}=${H(t)}`})).join("&");return`${s.origin}${s.path}?${r}`}}downloadFile(e,t){return i(this,void 0,void 0,(function*(){{if(!this._configuration.PubNubFile)throw new Error("Validation failed: 'PubNubFile' not configured or file upload not supported by the platform.");this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Download file with parameters:"})));const s=new Is(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet,PubNubFile:this._configuration.PubNubFile,cryptography:this.cryptography?this.cryptography:void 0,crypto:this._configuration.getCryptoModule()})),n=e=>{e&&this.logger.debug("PubNub","Download file success.")};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):yield this.sendRequest(s).then((e=>(n(e),e)))}}))}deleteFile(e,t){return i(this,void 0,void 0,(function*(){{this.logger.debug("PubNub",(()=>({messageType:"object",message:Object.assign({},e),details:"Delete file with parameters:"})));const s=new qt(Object.assign(Object.assign({},e),{keySet:this._configuration.keySet})),n=t=>{t&&this.logger.debug("PubNub",`Delete file success. Deleted file with ${e.id} ID.`)};return t?this.sendRequest(s,((e,s)=>{n(s),t(e,s)})):this.sendRequest(s).then((e=>(n(e),e)))}}))}time(e){return i(this,void 0,void 0,(function*(){this.logger.debug("PubNub","Get service time.");const t=new _s,s=e=>{e&&this.logger.debug("PubNub",`Get service time success. Current timetoken: ${e.timetoken}`)};return e?this.sendRequest(t,((t,n)=>{s(n),e(t,n)})):this.sendRequest(t).then((e=>(s(e),e)))}))}emitStatus(e){var t;null===(t=this.eventDispatcher)||void 0===t||t.handleStatus(e)}emitEvent(e,t){var s;this._globalSubscriptionSet&&this._globalSubscriptionSet.handleEvent(e,t),null===(s=this.eventDispatcher)||void 0===s||s.handleEvent(t),Object.values(this.eventHandleCapable).forEach((s=>{s.handleEvent(e,t)}))}set onStatus(e){this.eventDispatcher&&(this.eventDispatcher.onStatus=e)}set onMessage(e){this.eventDispatcher&&(this.eventDispatcher.onMessage=e)}set onPresence(e){this.eventDispatcher&&(this.eventDispatcher.onPresence=e)}set onSignal(e){this.eventDispatcher&&(this.eventDispatcher.onSignal=e)}set onObjects(e){this.eventDispatcher&&(this.eventDispatcher.onObjects=e)}set onMessageAction(e){this.eventDispatcher&&(this.eventDispatcher.onMessageAction=e)}set onFile(e){this.eventDispatcher&&(this.eventDispatcher.onFile=e)}addListener(e){this.eventDispatcher&&this.eventDispatcher.addListener(e)}removeListener(e){this.eventDispatcher&&this.eventDispatcher.removeListener(e)}removeAllListeners(){this.eventDispatcher&&this.eventDispatcher.removeAllListeners()}encrypt(e,t){this.logger.warn("PubNub","'encrypt' is deprecated. Use cryptoModule instead.");const s=this._configuration.getCryptoModule();if(!t&&s&&"string"==typeof e){const t=s.encrypt(e);return"string"==typeof t?t:u(t)}if(!this.crypto)throw new Error("Encryption error: cypher key not set");return this.crypto.encrypt(e,t)}decrypt(e,t){this.logger.warn("PubNub","'decrypt' is deprecated. Use cryptoModule instead.");const s=this._configuration.getCryptoModule();if(!t&&s){const t=s.decrypt(e);return t instanceof ArrayBuffer?JSON.parse((new TextDecoder).decode(t)):t}if(!this.crypto)throw new Error("Decryption error: cypher key not set");return this.crypto.decrypt(e,t)}encryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File encryption error. File constructor not configured.");if("string"!=typeof e&&!this._configuration.getCryptoModule())throw new Error("File encryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File encryption error. File encryption not available");return this.cryptography.encryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.encryptFile(t,this._configuration.PubNubFile)}))}decryptFile(e,t){return i(this,void 0,void 0,(function*(){var s;if("string"!=typeof e&&(t=e),!t)throw new Error("File encryption error. Source file is missing.");if(!this._configuration.PubNubFile)throw new Error("File decryption error. File constructor not configured.");if("string"==typeof e&&!this._configuration.getCryptoModule())throw new Error("File decryption error. Crypto module not configured.");if("string"==typeof e){if(!this.cryptography)throw new Error("File decryption error. File decryption not available");return this.cryptography.decryptFile(e,t,this._configuration.PubNubFile)}return null===(s=this._configuration.getCryptoModule())||void 0===s?void 0:s.decryptFile(t,this._configuration.PubNubFile)}))}}Ms.decoder=new TextDecoder,Ms.OPERATIONS=le,Ms.CATEGORIES=h,Ms.Endpoint=U,Ms.ExponentialRetryPolicy=$.ExponentialRetryPolicy,Ms.LinearRetryPolicy=$.LinearRetryPolicy,Ms.NoneRetryPolicy=$.None,Ms.LogLevel=G;class As{constructor(e,t){this.decode=e,this.base64ToBinary=t}decodeToken(e){let t="";e.length%4==3?t="=":e.length%4==2&&(t="==");const s=e.replace(/-/gi,"+").replace(/_/gi,"/")+t,n=this.decode(this.base64ToBinary(s));return"object"==typeof n?n:void 0}}class Us extends Ms{constructor(e){var t;const s=void 0!==e.subscriptionWorkerUrl,r=A(e),i=Object.assign(Object.assign({},r),{sdkFamily:"Web"});i.PubNubFile=o;const a=ee(i,(e=>{if(e.cipherKey){return new E({default:new j(Object.assign(Object.assign({},e),e.logger?{}:{logger:a.logger()})),cryptors:[new O({cipherKey:e.cipherKey})]})}}));let u,l,h;a.getCryptoModule()&&(a.getCryptoModule().logger=a.logger()),u=new ne(new As((e=>M(n.decode(e))),c)),(a.getCipherKey()||a.secretKey)&&(l=new C({secretKey:a.secretKey,cipherKey:a.getCipherKey(),useRandomIVs:a.getUseRandomIVs(),customEncrypt:a.getCustomEncrypt(),customDecrypt:a.getCustomDecrypt(),logger:a.logger()})),h=new P;let d=new ce(a.logger(),i.transport);if(r.subscriptionWorkerUrl){const e=new I({clientIdentifier:a._instanceId,subscriptionKey:a.subscribeKey,userId:a.getUserId(),workerUrl:r.subscriptionWorkerUrl,sdkVersion:a.getVersion(),heartbeatInterval:a.getHeartbeatInterval(),workerOfflineClientsCheckInterval:i.subscriptionWorkerOfflineClientsCheckInterval,workerUnsubscribeOfflineClients:i.subscriptionWorkerUnsubscribeOfflineClients,workerLogVerbosity:i.subscriptionWorkerLogVerbosity,tokenManager:u,transport:d,logger:a.logger()});d=e,window.onpagehide=t=>{t.persisted||e.terminate()}}else s&&a.logger().warn("PubNub","SharedWorker not supported in this browser. Fallback to the original transport.");const p=new oe({clientConfiguration:a,tokenManager:u,transport:d});super({configuration:a,transport:p,cryptography:h,tokenManager:u,crypto:l}),(null===(t=e.listenToBrowserNetworkEvents)||void 0===t||t)&&(window.addEventListener("offline",(()=>{this.networkDownDetected()})),window.addEventListener("online",(()=>{this.networkUpDetected()})))}networkDownDetected(){this.logger.debug("PubNub","Network down detected"),this.emitStatus({category:Us.CATEGORIES.PNNetworkDownCategory}),this._configuration.restore?this.disconnect(!0):this.destroy(!0)}networkUpDetected(){this.logger.debug("PubNub","Network up detected"),this.emitStatus({category:Us.CATEGORIES.PNNetworkUpCategory}),this.reconnect()}}return Us.CryptoModule=E,Us})); diff --git a/lib/core/components/configuration.js b/lib/core/components/configuration.js index fa22fb4da..1d0ec0bc3 100644 --- a/lib/core/components/configuration.js +++ b/lib/core/components/configuration.js @@ -164,7 +164,7 @@ const makeConfiguration = (base, setupCryptoModule) => { return base.PubNubFile; }, get version() { - return '9.6.1'; + return '9.6.2'; }, getVersion() { return this.version; diff --git a/lib/types/index.d.ts b/lib/types/index.d.ts index 0ff777ed2..4c706eb17 100644 --- a/lib/types/index.d.ts +++ b/lib/types/index.d.ts @@ -521,6 +521,7 @@ declare class PubNubCore< * @param parameters - Request configuration parameters. * * @returns Asynchronous delete messages response. + * */ deleteMessages(parameters: PubNub.History.DeleteMessagesParameters): Promise; /** diff --git a/package.json b/package.json index 4d933f06d..b46f3061f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "pubnub", - "version": "9.6.1", + "version": "9.6.2", "author": "PubNub ", "description": "Publish & Subscribe Real-time Messaging with PubNub", "scripts": { diff --git a/src/core/components/configuration.ts b/src/core/components/configuration.ts index f939810a0..755b5fdbe 100644 --- a/src/core/components/configuration.ts +++ b/src/core/components/configuration.ts @@ -232,7 +232,7 @@ export const makeConfiguration = ( return base.PubNubFile; }, get version(): string { - return '9.6.1'; + return '9.6.2'; }, getVersion(): string { return this.version;