-
Notifications
You must be signed in to change notification settings - Fork 401
/
Copy pathpubnub-common.js
2182 lines (2182 loc) · 91.8 KB
/
pubnub-common.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
/**
* Core PubNub API module.
*/
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.PubNubCore = void 0;
// region Imports
// region Components
const listener_manager_1 = require("./components/listener_manager");
const subscription_manager_1 = require("./components/subscription-manager");
const push_payload_1 = __importDefault(require("./components/push_payload"));
const eventEmitter_1 = __importDefault(require("./components/eventEmitter"));
const base64_codec_1 = require("./components/base64_codec");
const uuid_1 = __importDefault(require("./components/uuid"));
// endregion
// region Constants
const operations_1 = __importDefault(require("./constants/operations"));
const categories_1 = __importDefault(require("./constants/categories"));
// endregion
const pubnub_error_1 = require("../errors/pubnub-error");
const pubnub_api_error_1 = require("../errors/pubnub-api-error");
// region Event Engine
const presence_1 = require("../event-engine/presence/presence");
const retryPolicy_1 = require("../event-engine/core/retryPolicy");
const event_engine_1 = require("../event-engine");
// endregion
// region Publish & Signal
const Publish = __importStar(require("./endpoints/publish"));
const Signal = __importStar(require("./endpoints/signal"));
// endregion
// region Subscription
const subscribe_1 = require("./endpoints/subscribe");
const receiveMessages_1 = require("./endpoints/subscriptionUtils/receiveMessages");
const handshake_1 = require("./endpoints/subscriptionUtils/handshake");
// endregion
// region Presence
const get_state_1 = require("./endpoints/presence/get_state");
const set_state_1 = require("./endpoints/presence/set_state");
const heartbeat_1 = require("./endpoints/presence/heartbeat");
const leave_1 = require("./endpoints/presence/leave");
const where_now_1 = require("./endpoints/presence/where_now");
const here_now_1 = require("./endpoints/presence/here_now");
// endregion
// region Message Storage
const delete_messages_1 = require("./endpoints/history/delete_messages");
const message_counts_1 = require("./endpoints/history/message_counts");
const get_history_1 = require("./endpoints/history/get_history");
const fetch_messages_1 = require("./endpoints/fetch_messages");
// endregion
// region Message Actions
const get_message_actions_1 = require("./endpoints/actions/get_message_actions");
const add_message_action_1 = require("./endpoints/actions/add_message_action");
const remove_message_action_1 = require("./endpoints/actions/remove_message_action");
// endregion
// region File sharing
const publish_file_1 = require("./endpoints/file_upload/publish_file");
const get_file_url_1 = require("./endpoints/file_upload/get_file_url");
const delete_file_1 = require("./endpoints/file_upload/delete_file");
const list_files_1 = require("./endpoints/file_upload/list_files");
const send_file_1 = require("./endpoints/file_upload/send_file");
// endregion
// region PubNub Access Manager
const revoke_token_1 = require("./endpoints/access_manager/revoke_token");
const grant_token_1 = require("./endpoints/access_manager/grant_token");
const grant_1 = require("./endpoints/access_manager/grant");
const audit_1 = require("./endpoints/access_manager/audit");
const ChannelMetadata_1 = require("../entities/ChannelMetadata");
const SubscriptionSet_1 = require("../entities/SubscriptionSet");
const ChannelGroup_1 = require("../entities/ChannelGroup");
const UserMetadata_1 = require("../entities/UserMetadata");
const Channel_1 = require("../entities/Channel");
// endregion
// region Channel Groups
const pubnub_channel_groups_1 = __importDefault(require("./pubnub-channel-groups"));
// endregion
// region Push Notifications
const pubnub_push_1 = __importDefault(require("./pubnub-push"));
const pubnub_objects_1 = __importDefault(require("./pubnub-objects"));
// endregion
// region Time
const Time = __importStar(require("./endpoints/time"));
// endregion
const utils_1 = require("./utils");
const download_file_1 = require("./endpoints/file_upload/download_file");
// endregion
/**
* Platform-agnostic PubNub client core.
*/
class PubNubCore {
/**
* Construct notification payload which will trigger push notification.
*
* @param title - Title which will be shown on notification.
* @param body - Payload which will be sent as part of notification.
*
* @returns Pre-formatted message payload which will trigger push notification.
*/
static notificationPayload(title, body) {
if (process.env.PUBLISH_MODULE !== 'disabled') {
return new push_payload_1.default(title, body);
}
else
throw new Error('Notification Payload error: publish module disabled');
}
/**
* Generate unique identifier.
*
* @returns Unique identifier.
*/
static generateUUID() {
return uuid_1.default.createUUID();
}
// endregion
/**
* Create and configure PubNub client core.
*
* @param configuration - PubNub client core configuration.
* @returns Configured and ready to use PubNub client.
*
* @internal
*/
constructor(configuration) {
this._configuration = configuration.configuration;
this.cryptography = configuration.cryptography;
this.tokenManager = configuration.tokenManager;
this.transport = configuration.transport;
this.crypto = configuration.crypto;
// API group entry points initialization.
if (process.env.APP_CONTEXT_MODULE !== 'disabled')
this._objects = new pubnub_objects_1.default(this._configuration, this.sendRequest.bind(this));
if (process.env.CHANNEL_GROUPS_MODULE !== 'disabled')
this._channelGroups = new pubnub_channel_groups_1.default(this._configuration.keySet, this.sendRequest.bind(this));
if (process.env.MOBILE_PUSH_MODULE !== 'disabled')
this._push = new pubnub_push_1.default(this._configuration.keySet, this.sendRequest.bind(this));
if (process.env.SUBSCRIBE_MODULE !== 'disabled') {
// Prepare for real-time events announcement.
this.listenerManager = new listener_manager_1.ListenerManager();
this.eventEmitter = new eventEmitter_1.default(this.listenerManager);
this.subscribeCapable = new Set();
if (this._configuration.enableEventEngine) {
if (process.env.SUBSCRIBE_EVENT_ENGINE_MODULE !== 'disabled') {
let heartbeatInterval = this._configuration.getHeartbeatInterval();
this.presenceState = {};
if (process.env.PRESENCE_MODULE !== 'disabled') {
if (heartbeatInterval) {
this.presenceEventEngine = new presence_1.PresenceEventEngine({
heartbeat: this.heartbeat.bind(this),
leave: (parameters) => this.makeUnsubscribe(parameters, () => { }),
heartbeatDelay: () => new Promise((resolve, reject) => {
heartbeatInterval = this._configuration.getHeartbeatInterval();
if (!heartbeatInterval)
reject(new pubnub_error_1.PubNubError('Heartbeat interval has been reset.'));
else
setTimeout(resolve, heartbeatInterval * 1000);
}),
retryDelay: (amount) => new Promise((resolve) => setTimeout(resolve, amount)),
emitStatus: (status) => this.listenerManager.announceStatus(status),
config: this._configuration,
presenceState: this.presenceState,
});
}
}
this.eventEngine = new event_engine_1.EventEngine({
handshake: this.subscribeHandshake.bind(this),
receiveMessages: this.subscribeReceiveMessages.bind(this),
delay: (amount) => new Promise((resolve) => setTimeout(resolve, amount)),
join: this.join.bind(this),
leave: this.leave.bind(this),
leaveAll: this.leaveAll.bind(this),
presenceState: this.presenceState,
config: this._configuration,
emitMessages: (events) => {
try {
events.forEach((event) => this.eventEmitter.emitEvent(event));
}
catch (e) {
const errorStatus = {
error: true,
category: categories_1.default.PNUnknownCategory,
errorData: e,
statusCode: 0,
};
this.listenerManager.announceStatus(errorStatus);
}
},
emitStatus: (status) => this.listenerManager.announceStatus(status),
});
}
else
throw new Error('Event Engine error: subscription event engine module disabled');
}
else {
if (process.env.SUBSCRIBE_MANAGER_MODULE !== 'disabled') {
this.subscriptionManager = new subscription_manager_1.SubscriptionManager(this._configuration, this.listenerManager, this.eventEmitter, this.makeSubscribe.bind(this), this.heartbeat.bind(this), this.makeUnsubscribe.bind(this), this.time.bind(this));
}
else
throw new Error('Subscription Manager error: subscription manager module disabled');
}
}
}
// --------------------------------------------------------
// -------------------- Configuration ----------------------
// --------------------------------------------------------
// region Configuration
/**
* PubNub client configuration.
*
* @returns Currently user PubNub client configuration.
*/
get configuration() {
return this._configuration;
}
/**
* Current PubNub client configuration.
*
* @returns Currently user PubNub client configuration.
*
* @deprecated Use {@link configuration} getter instead.
*/
get _config() {
return this.configuration;
}
/**
* REST API endpoint access authorization key.
*
* It is required to have `authorization key` with required permissions to access REST API
* endpoints when `PAM` enabled for user key set.
*/
get authKey() {
var _a;
return (_a = this._configuration.authKey) !== null && _a !== void 0 ? _a : undefined;
}
/**
* REST API endpoint access authorization key.
*
* It is required to have `authorization key` with required permissions to access REST API
* endpoints when `PAM` enabled for user key set.
*/
getAuthKey() {
return this.authKey;
}
/**
* Change REST API endpoint access authorization key.
*
* @param authKey - New authorization key which should be used with new requests.
*/
setAuthKey(authKey) {
this._configuration.setAuthKey(authKey);
}
/**
* Get a PubNub client user identifier.
*
* @returns Current PubNub client user identifier.
*/
get userId() {
return this._configuration.userId;
}
/**
* Change the current PubNub client user identifier.
*
* **Important:** Change won't affect ongoing REST API calls.
*
* @param value - New PubNub client user identifier.
*
* @throws Error empty user identifier has been provided.
*/
set userId(value) {
if (!value || typeof value !== 'string' || value.trim().length === 0)
throw new Error('Missing or invalid userId parameter. Provide a valid string userId');
this._configuration.userId = value;
}
/**
* Get a PubNub client user identifier.
*
* @returns Current PubNub client user identifier.
*/
getUserId() {
return this._configuration.userId;
}
/**
* Change the current PubNub client user identifier.
*
* **Important:** Change won't affect ongoing REST API calls.
*
* @param value - New PubNub client user identifier.
*
* @throws Error empty user identifier has been provided.
*/
setUserId(value) {
if (!value || typeof value !== 'string' || value.trim().length === 0)
throw new Error('Missing or invalid userId parameter. Provide a valid string userId');
this._configuration.userId = value;
}
/**
* Real-time updates filtering expression.
*
* @returns Filtering expression.
*/
get filterExpression() {
var _a;
return (_a = this._configuration.getFilterExpression()) !== null && _a !== void 0 ? _a : undefined;
}
/**
* Real-time updates filtering expression.
*
* @returns Filtering expression.
*/
getFilterExpression() {
return this.filterExpression;
}
/**
* Update real-time updates filtering expression.
*
* @param expression - New expression which should be used or `undefined` to disable filtering.
*/
set filterExpression(expression) {
this._configuration.setFilterExpression(expression);
}
/**
* Update real-time updates filtering expression.
*
* @param expression - New expression which should be used or `undefined` to disable filtering.
*/
setFilterExpression(expression) {
this.filterExpression = expression;
}
/**
* Dta encryption / decryption key.
*
* @returns Currently used key for data encryption / decryption.
*/
get cipherKey() {
return this._configuration.getCipherKey();
}
/**
* Change data encryption / decryption key.
*
* @param key - New key which should be used for data encryption / decryption.
*/
set cipherKey(key) {
this._configuration.setCipherKey(key);
}
/**
* Change data encryption / decryption key.
*
* @param key - New key which should be used for data encryption / decryption.
*/
setCipherKey(key) {
this.cipherKey = key;
}
/**
* Change heartbeat requests interval.
*
* @param interval - New presence request heartbeat intervals.
*/
set heartbeatInterval(interval) {
this._configuration.setHeartbeatInterval(interval);
}
/**
* Change heartbeat requests interval.
*
* @param interval - New presence request heartbeat intervals.
*/
setHeartbeatInterval(interval) {
this.heartbeatInterval = interval;
}
/**
* Get PubNub SDK version.
*
* @returns Current SDK version.
*/
getVersion() {
return this._configuration.getVersion();
}
/**
* Add framework's prefix.
*
* @param name - Name of the framework which would want to add own data into `pnsdk` suffix.
* @param suffix - Suffix with information about framework.
*/
_addPnsdkSuffix(name, suffix) {
this._configuration._addPnsdkSuffix(name, suffix);
}
// --------------------------------------------------------
// ---------------------- Deprecated ----------------------
// --------------------------------------------------------
// region Deprecated
/**
* Get a PubNub client user identifier.
*
* @returns Current PubNub client user identifier.
*
* @deprecated Use the {@link getUserId} or {@link userId} getter instead.
*/
getUUID() {
return this.userId;
}
/**
* Change the current PubNub client user identifier.
*
* **Important:** Change won't affect ongoing REST API calls.
*
* @param value - New PubNub client user identifier.
*
* @throws Error empty user identifier has been provided.
*
* @deprecated Use the {@link PubNubCore#setUserId} or {@link PubNubCore#userId} setter instead.
*/
setUUID(value) {
this.userId = value;
}
/**
* Custom data encryption method.
*
* @deprecated Instead use {@link cryptoModule} for data encryption.
*/
get customEncrypt() {
return this._configuration.getCustomEncrypt();
}
/**
* Custom data decryption method.
*
* @deprecated Instead use {@link cryptoModule} for data decryption.
*/
get customDecrypt() {
return this._configuration.getCustomDecrypt();
}
// endregion
// endregion
// --------------------------------------------------------
// ---------------------- Entities ------------------------
// --------------------------------------------------------
// region Entities
/**
* Create a `Channel` entity.
*
* Entity can be used for the interaction with the following API:
* - `subscribe`
*
* @param name - Unique channel name.
* @returns `Channel` entity.
*/
channel(name) {
return new Channel_1.Channel(name, this.eventEmitter, this);
}
/**
* Create a `ChannelGroup` entity.
*
* Entity can be used for the interaction with the following API:
* - `subscribe`
*
* @param name - Unique channel group name.
* @returns `ChannelGroup` entity.
*/
channelGroup(name) {
return new ChannelGroup_1.ChannelGroup(name, this.eventEmitter, this);
}
/**
* Create a `ChannelMetadata` entity.
*
* Entity can be used for the interaction with the following API:
* - `subscribe`
*
* @param id - Unique channel metadata object identifier.
* @returns `ChannelMetadata` entity.
*/
channelMetadata(id) {
return new ChannelMetadata_1.ChannelMetadata(id, this.eventEmitter, this);
}
/**
* Create a `UserMetadata` entity.
*
* Entity can be used for the interaction with the following API:
* - `subscribe`
*
* @param id - Unique user metadata object identifier.
* @returns `UserMetadata` entity.
*/
userMetadata(id) {
return new UserMetadata_1.UserMetadata(id, this.eventEmitter, this);
}
/**
* Create subscriptions set object.
*
* @param parameters - Subscriptions set configuration parameters.
*/
subscriptionSet(parameters) {
if (process.env.SUBSCRIBE_EVENT_ENGINE_MODULE !== 'disabled') {
return new SubscriptionSet_1.SubscriptionSet(Object.assign(Object.assign({}, parameters), { eventEmitter: this.eventEmitter, pubnub: this }));
}
else
throw new Error('Subscription error: subscription event engine module disabled');
}
/**
* Schedule request execution.
*
* @internal
*
* @param request - REST API request.
* @param [callback] - Request completion handler callback.
*
* @returns Asynchronous request execution and response parsing result or `void` in case if
* `callback` provided.
*
* @throws PubNubError in case of request processing error.
*/
sendRequest(request, callback) {
return __awaiter(this, void 0, void 0, function* () {
// Validate user-input.
const validationResult = request.validate();
if (validationResult) {
if (callback)
return callback((0, pubnub_error_1.createValidationError)(validationResult), null);
throw new pubnub_error_1.PubNubError('Validation failed, check status for details', (0, pubnub_error_1.createValidationError)(validationResult));
}
// Complete request configuration.
const transportRequest = request.request();
const operation = request.operation();
if ((transportRequest.formData && transportRequest.formData.length > 0) ||
operation === operations_1.default.PNDownloadFileOperation) {
// Set file upload / download request delay.
transportRequest.timeout = this._configuration.getFileTimeout();
}
else {
if (operation === operations_1.default.PNSubscribeOperation ||
operation === operations_1.default.PNReceiveMessagesOperation)
transportRequest.timeout = this._configuration.getSubscribeTimeout();
else
transportRequest.timeout = this._configuration.getTransactionTimeout();
}
// API request processing status.
const status = {
error: false,
operation,
category: categories_1.default.PNAcknowledgmentCategory,
statusCode: 0,
};
const [sendableRequest, cancellationController] = this.transport.makeSendable(transportRequest);
/**
* **Important:** Because of multiple environments where JS SDK can be used control over
* cancellation had to be inverted to let transport provider solve request cancellation task
* more efficiently. As result, cancellation controller can be retrieved and used only after
* request will be scheduled by transport provider.
*/
request.cancellationController = cancellationController ? cancellationController : null;
return sendableRequest
.then((response) => {
status.statusCode = response.status;
// Handle special case when request completed but not fully processed by PubNub service.
if (response.status !== 200 && response.status !== 204) {
const responseText = PubNubCore.decoder.decode(response.body);
const contentType = response.headers['content-type'];
if (contentType || contentType.indexOf('javascript') !== -1 || contentType.indexOf('json') !== -1) {
const json = JSON.parse(responseText);
if (typeof json === 'object' && 'error' in json && json.error && typeof json.error === 'object')
status.errorData = json.error;
}
else
status.responseText = responseText;
}
return request.parse(response);
})
.then((parsed) => {
// Notify callback (if possible).
if (callback)
return callback(status, parsed);
return parsed;
})
.catch((error) => {
const apiError = !(error instanceof pubnub_api_error_1.PubNubAPIError) ? pubnub_api_error_1.PubNubAPIError.create(error) : error;
// Notify callback (if possible).
if (callback)
return callback(apiError.toStatus(operation), null);
throw apiError.toPubNubError(operation, 'REST API request processing error, check status for details');
});
});
}
/**
* Unsubscribe from all channels and groups.
*
* @param [isOffline] - Whether `offline` presence should be notified or not.
*/
destroy(isOffline) {
var _a;
if (process.env.SUBSCRIBE_MODULE !== 'disabled') {
if (process.env.SUBSCRIBE_EVENT_ENGINE_MODULE !== 'disabled')
(_a = this.subscribeCapable) === null || _a === void 0 ? void 0 : _a.clear();
if (this.subscriptionManager) {
this.subscriptionManager.unsubscribeAll(isOffline);
this.subscriptionManager.disconnect();
}
else if (this.eventEngine)
this.eventEngine.dispose();
}
}
/**
* Unsubscribe from all channels and groups.
*
* @deprecated Use {@link destroy} method instead.
*/
stop() {
this.destroy();
}
// endregion
// --------------------------------------------------------
// ----------------------- Listener -----------------------
// --------------------------------------------------------
// region Listener
/**
* Register real-time events listener.
*
* @param listener - Listener with event callbacks to handle different types of events.
*/
addListener(listener) {
if (process.env.SUBSCRIBE_MODULE !== 'disabled')
this.listenerManager.addListener(listener);
else
throw new Error('Subscription error: subscription module disabled');
}
/**
* Remove real-time event listener.
*
* @param listener - Event listeners which should be removed.
*/
removeListener(listener) {
if (process.env.SUBSCRIBE_MODULE !== 'disabled')
this.listenerManager.removeListener(listener);
else
throw new Error('Subscription error: subscription module disabled');
}
/**
* Clear all real-time event listeners.
*/
removeAllListeners() {
if (process.env.SUBSCRIBE_MODULE !== 'disabled')
this.listenerManager.removeAllListeners();
else
throw new Error('Subscription error: subscription module disabled');
}
/**
* Publish data to a specific channel.
*
* @param parameters - Request configuration parameters.
* @param [callback] - Request completion handler callback.
*
* @returns Asynchronous publish data response or `void` in case if `callback` provided.
*/
publish(parameters, callback) {
return __awaiter(this, void 0, void 0, function* () {
if (process.env.PUBLISH_MODULE !== 'disabled') {
const request = new Publish.PublishRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet, crypto: this._configuration.getCryptoModule() }));
if (callback)
return this.sendRequest(request, callback);
return this.sendRequest(request);
}
else
throw new Error('Publish error: publish module disabled');
});
}
/**
* Signal data to a specific channel.
*
* @param parameters - Request configuration parameters.
* @param [callback] - Request completion handler callback.
*
* @returns Asynchronous signal data response or `void` in case if `callback` provided.
*/
signal(parameters, callback) {
return __awaiter(this, void 0, void 0, function* () {
if (process.env.PUBLISH_MODULE !== 'disabled') {
const request = new Signal.SignalRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet }));
if (callback)
return this.sendRequest(request, callback);
return this.sendRequest(request);
}
else
throw new Error('Publish error: publish module disabled');
});
}
/**
* `Fire` a data to a specific channel.
*
* @param parameters - Request configuration parameters.
* @param [callback] - Request completion handler callback.
*
* @returns Asynchronous signal data response or `void` in case if `callback` provided.
*
* @deprecated Use {@link publish} method instead.
*/
fire(parameters, callback) {
return __awaiter(this, void 0, void 0, function* () {
callback !== null && callback !== void 0 ? callback : (callback = () => { });
return this.publish(Object.assign(Object.assign({}, parameters), { replicate: false, storeInHistory: false }), callback);
});
}
// endregion
// --------------------------------------------------------
// -------------------- Subscribe API ---------------------
// --------------------------------------------------------
// region Subscribe API
/**
* Get list of channels on which PubNub client currently subscribed.
*
* @returns List of active channels.
*/
getSubscribedChannels() {
if (process.env.SUBSCRIBE_MODULE !== 'disabled') {
if (this.subscriptionManager)
return this.subscriptionManager.subscribedChannels;
else if (this.eventEngine)
return this.eventEngine.getSubscribedChannels();
}
else
throw new Error('Subscription error: subscription module disabled');
return [];
}
/**
* Get list of channel groups on which PubNub client currently subscribed.
*
* @returns List of active channel groups.
*/
getSubscribedChannelGroups() {
if (process.env.SUBSCRIBE_MODULE !== 'disabled') {
if (this.subscriptionManager)
return this.subscriptionManager.subscribedChannelGroups;
else if (this.eventEngine)
return this.eventEngine.getSubscribedChannelGroups();
}
else
throw new Error('Subscription error: subscription module disabled');
return [];
}
/**
* Register subscribe capable object with active subscription.
*
* @param subscribeCapable - {@link Subscription} or {@link SubscriptionSet} object.
*
* @internal
*/
registerSubscribeCapable(subscribeCapable) {
if (process.env.SUBSCRIBE_EVENT_ENGINE_MODULE !== 'disabled') {
if (!this.subscribeCapable || this.subscribeCapable.has(subscribeCapable))
return;
this.subscribeCapable.add(subscribeCapable);
}
else
throw new Error('Subscription error: subscription event engine module disabled');
}
/**
* Unregister subscribe capable object with inactive subscription.
*
* @param subscribeCapable - {@link Subscription} or {@link SubscriptionSet} object.
*
* @internal
*/
unregisterSubscribeCapable(subscribeCapable) {
if (process.env.SUBSCRIBE_EVENT_ENGINE_MODULE !== 'disabled') {
if (!this.subscribeCapable || !this.subscribeCapable.has(subscribeCapable))
return;
this.subscribeCapable.delete(subscribeCapable);
}
else
throw new Error('Subscription error: subscription event engine module disabled');
}
/**
* Retrieve list of subscribe capable entities currently used in subscription.
*
* @returns Channels and channel groups currently used in subscription.
*
* @internal
*/
getSubscribeCapableEntities() {
if (process.env.SUBSCRIBE_EVENT_ENGINE_MODULE !== 'disabled') {
const entities = { channels: [], channelGroups: [] };
if (!this.subscribeCapable)
return entities;
for (const subscribeCapable of this.subscribeCapable) {
entities.channelGroups.push(...subscribeCapable.channelGroups);
entities.channels.push(...subscribeCapable.channels);
}
return entities;
}
else
throw new Error('Subscription error: subscription event engine module disabled');
}
/**
* Subscribe to specified channels and groups real-time events.
*
* @param parameters - Request configuration parameters.
*/
subscribe(parameters) {
if (process.env.SUBSCRIBE_MODULE !== 'disabled') {
if (this.subscriptionManager)
this.subscriptionManager.subscribe(parameters);
else if (this.eventEngine)
this.eventEngine.subscribe(parameters);
}
else
throw new Error('Subscription error: subscription module disabled');
}
/**
* Perform subscribe request.
*
* **Note:** Method passed into managers to let them use it when required.
*
* @internal
*
* @param parameters - Request configuration parameters.
* @param callback - Request completion handler callback.
*/
makeSubscribe(parameters, callback) {
if (process.env.SUBSCRIBE_MANAGER_MODULE !== 'disabled') {
const request = new subscribe_1.SubscribeRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet, crypto: this._configuration.getCryptoModule(), getFileUrl: this.getFileUrl.bind(this) }));
this.sendRequest(request, (status, result) => {
var _a;
if (this.subscriptionManager && ((_a = this.subscriptionManager.abort) === null || _a === void 0 ? void 0 : _a.identifier) === request.requestIdentifier)
this.subscriptionManager.abort = null;
callback(status, result);
});
/**
* Allow subscription cancellation.
*
* **Note:** Had to be done after scheduling because transport provider return cancellation
* controller only when schedule new request.
*/
if (this.subscriptionManager) {
// Creating identifiable abort caller.
const callableAbort = () => request.abort('Cancel long-poll subscribe request');
callableAbort.identifier = request.requestIdentifier;
this.subscriptionManager.abort = callableAbort;
}
}
else
throw new Error('Subscription error: subscription manager module disabled');
}
/**
* Unsubscribe from specified channels and groups real-time events.
*
* @param parameters - Request configuration parameters.
*/
unsubscribe(parameters) {
if (process.env.SUBSCRIBE_MODULE !== 'disabled') {
if (this.subscriptionManager)
this.subscriptionManager.unsubscribe(parameters);
else if (this.eventEngine)
this.eventEngine.unsubscribe(parameters);
}
else
throw new Error('Unsubscription error: subscription module disabled');
}
/**
* Perform unsubscribe request.
*
* **Note:** Method passed into managers to let them use it when required.
*
* @internal
*
* @param parameters - Request configuration parameters.
* @param callback - Request completion handler callback.
*/
makeUnsubscribe(parameters, callback) {
if (process.env.PRESENCE_MODULE !== 'disabled') {
// Filtering out presence channels and groups.
let { channels, channelGroups } = parameters;
// Remove `-pnpres` channels / groups if they not acceptable in current PubNub client configuration.
if (!this._configuration.getKeepPresenceChannelsInPresenceRequests()) {
if (channelGroups)
channelGroups = channelGroups.filter((channelGroup) => !channelGroup.endsWith('-pnpres'));
if (channels)
channels = channels.filter((channel) => !channel.endsWith('-pnpres'));
}
// Complete immediately request only for presence channels.
if ((channelGroups !== null && channelGroups !== void 0 ? channelGroups : []).length === 0 && (channels !== null && channels !== void 0 ? channels : []).length === 0) {
return callback({
error: false,
operation: operations_1.default.PNUnsubscribeOperation,
category: categories_1.default.PNAcknowledgmentCategory,
statusCode: 200,
});
}
this.sendRequest(new leave_1.PresenceLeaveRequest({ channels, channelGroups, keySet: this._configuration.keySet }), callback);
}
else
throw new Error('Unsubscription error: presence module disabled');
}
/**
* Unsubscribe from all channels and groups.
*/
unsubscribeAll() {
var _a;
if (process.env.SUBSCRIBE_MODULE !== 'disabled') {
if (process.env.SUBSCRIBE_EVENT_ENGINE_MODULE !== 'disabled')
(_a = this.subscribeCapable) === null || _a === void 0 ? void 0 : _a.clear();
if (this.subscriptionManager)
this.subscriptionManager.unsubscribeAll();
else if (this.eventEngine)
this.eventEngine.unsubscribeAll();
}
else
throw new Error('Unsubscription error: subscription module disabled');
}
/**
* Temporarily disconnect from real-time events stream.
*/
disconnect() {
if (process.env.SUBSCRIBE_MODULE !== 'disabled') {
if (this.subscriptionManager)
this.subscriptionManager.disconnect();
else if (this.eventEngine)
this.eventEngine.disconnect();
}
else
throw new Error('Disconnection error: subscription module disabled');
}
/**
* Restore connection to the real-time events stream.
*
* @param parameters - Reconnection catch up configuration. **Note:** available only with
* enabled event engine.
*/
reconnect(parameters) {
if (process.env.SUBSCRIBE_MODULE !== 'disabled') {
if (this.subscriptionManager)
this.subscriptionManager.reconnect();
else if (this.eventEngine)
this.eventEngine.reconnect(parameters !== null && parameters !== void 0 ? parameters : {});
}
else
throw new Error('Reconnection error: subscription module disabled');
}
/**
* Event engine handshake subscribe.
*
* @internal
*
* @param parameters - Request configuration parameters.
*/
subscribeHandshake(parameters) {
return __awaiter(this, void 0, void 0, function* () {
if (process.env.SUBSCRIBE_EVENT_ENGINE_MODULE !== 'disabled') {
const request = new handshake_1.HandshakeSubscribeRequest(Object.assign(Object.assign({}, parameters), { keySet: this._configuration.keySet, crypto: this._configuration.getCryptoModule(), getFileUrl: this.getFileUrl.bind(this) }));
const abortUnsubscribe = parameters.abortSignal.subscribe((err) => {
request.abort('Cancel subscribe handshake request');
});
/**
* Allow subscription cancellation.
*
* **Note:** Had to be done after scheduling because transport provider return cancellation
* controller only when schedule new request.
*/
const handshakeResponse = this.sendRequest(request);
return handshakeResponse.then((response) => {
abortUnsubscribe();
return response.cursor;
});