forked from SocketCluster/socketcluster-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
socketcluster.js
6642 lines (5686 loc) · 177 KB
/
socketcluster.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
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.socketCluster = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
(function (global){
var base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
var arrayBufferToBase64 = function (arraybuffer) {
var bytes = new Uint8Array(arraybuffer);
var len = bytes.length;
var base64 = '';
for (var i = 0; i < len; i += 3) {
base64 += base64Chars[bytes[i] >> 2];
base64 += base64Chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64 += base64Chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64 += base64Chars[bytes[i + 2] & 63];
}
if ((len % 3) === 2) {
base64 = base64.substring(0, base64.length - 1) + '=';
} else if (len % 3 === 1) {
base64 = base64.substring(0, base64.length - 2) + '==';
}
return base64;
};
var binaryToBase64Replacer = function (key, value) {
if (global.ArrayBuffer && value instanceof global.ArrayBuffer) {
return {
base64: true,
data: arrayBufferToBase64(value)
};
} else if (global.Buffer) {
if (value instanceof global.Buffer){
return {
base64: true,
data: value.toString('base64')
};
}
// Some versions of Node.js convert Buffers to Objects before they are passed to
// the replacer function - Because of this, we need to rehydrate Buffers
// before we can convert them to base64 strings.
if (value && value.type == 'Buffer' && value.data instanceof Array) {
var rehydratedBuffer;
if (global.Buffer.from) {
rehydratedBuffer = global.Buffer.from(value.data);
} else {
rehydratedBuffer = new global.Buffer(value.data);
}
return {
base64: true,
data: rehydratedBuffer.toString('base64')
};
}
}
return value;
};
// Decode the data which was transmitted over the wire to a JavaScript Object in a format which SC understands.
// See encode function below for more details.
module.exports.decode = function (input) {
if (input == null) {
return null;
}
// Leave ping or pong message as is
if (input == '#1' || input == '#2') {
return input;
}
var message = input.toString();
try {
return JSON.parse(message);
} catch (err) {}
return message;
};
// Encode a raw JavaScript object (which is in the SC protocol format) into a format for
// transfering it over the wire. In this case, we just convert it into a simple JSON string.
// If you want to create your own custom codec, you can encode the object into any format
// (e.g. binary ArrayBuffer or string with any kind of compression) so long as your decode
// function is able to rehydrate that object back into its original JavaScript Object format
// (which adheres to the SC protocol).
// See https://github.com/SocketCluster/socketcluster/blob/master/socketcluster-protocol.md
// for details about the SC protocol.
module.exports.encode = function (object) {
// Leave ping or pong message as is
if (object == '#1' || object == '#2') {
return object;
}
return JSON.stringify(object, binaryToBase64Replacer);
};
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],2:[function(require,module,exports){
var SCSocket = require('./lib/scsocket');
var SCSocketCreator = require('./lib/scsocketcreator');
module.exports.SCSocketCreator = SCSocketCreator;
module.exports.SCSocket = SCSocket;
module.exports.SCEmitter = require('sc-emitter').SCEmitter;
module.exports.connect = function (options) {
return SCSocketCreator.connect(options);
};
module.exports.destroy = function (options) {
return SCSocketCreator.destroy(options);
};
module.exports.connections = SCSocketCreator.connections;
module.exports.version = '5.2.4';
},{"./lib/scsocket":5,"./lib/scsocketcreator":6,"sc-emitter":18}],3:[function(require,module,exports){
(function (global){
var AuthEngine = function () {
this._internalStorage = {};
};
AuthEngine.prototype._isLocalStorageEnabled = function () {
var err;
try {
// Some browsers will throw an error here if localStorage is disabled.
global.localStorage;
// Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem
// throw QuotaExceededError. We're going to detect this and avoid hard to debug edge cases.
global.localStorage.setItem('__scLocalStorageTest', 1);
global.localStorage.removeItem('__scLocalStorageTest');
} catch (e) {
err = e;
}
return !err;
};
AuthEngine.prototype.saveToken = function (name, token, options, callback) {
if (this._isLocalStorageEnabled() && global.localStorage) {
global.localStorage.setItem(name, token);
} else {
this._internalStorage[name] = token;
}
callback && callback(null, token);
};
AuthEngine.prototype.removeToken = function (name, callback) {
var token;
this.loadToken(name, function (err, authToken) {
token = authToken;
});
if (this._isLocalStorageEnabled() && global.localStorage) {
global.localStorage.removeItem(name);
}
delete this._internalStorage[name];
callback && callback(null, token);
};
AuthEngine.prototype.loadToken = function (name, callback) {
var token;
if (this._isLocalStorageEnabled() && global.localStorage) {
token = global.localStorage.getItem(name);
} else {
token = this._internalStorage[name] || null;
}
callback(null, token);
};
module.exports.AuthEngine = AuthEngine;
}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{}],4:[function(require,module,exports){
var scErrors = require('sc-errors');
var InvalidActionError = scErrors.InvalidActionError;
var Response = function (socket, id) {
this.socket = socket;
this.id = id;
this.sent = false;
};
Response.prototype._respond = function (responseData) {
if (this.sent) {
throw new InvalidActionError('Response ' + this.id + ' has already been sent');
} else {
this.sent = true;
this.socket.send(this.socket.encode(responseData));
}
};
Response.prototype.end = function (data) {
if (this.id) {
var responseData = {
rid: this.id
};
if (data !== undefined) {
responseData.data = data;
}
this._respond(responseData);
}
};
Response.prototype.error = function (error, data) {
if (this.id) {
var err = scErrors.dehydrateError(error);
var responseData = {
rid: this.id,
error: err
};
if (data !== undefined) {
responseData.data = data;
}
this._respond(responseData);
}
};
Response.prototype.callback = function (error, data) {
if (error) {
this.error(error, data);
} else {
this.end(data);
}
};
module.exports.Response = Response;
},{"sc-errors":20}],5:[function(require,module,exports){
(function (global,Buffer){
var SCEmitter = require('sc-emitter').SCEmitter;
var SCChannel = require('sc-channel').SCChannel;
var Response = require('./response').Response;
var AuthEngine = require('./auth').AuthEngine;
var formatter = require('sc-formatter');
var SCTransport = require('./sctransport').SCTransport;
var querystring = require('querystring');
var LinkedList = require('linked-list');
var base64 = require('base-64');
var cloneDeep = require('lodash.clonedeep');
var scErrors = require('sc-errors');
var InvalidArgumentsError = scErrors.InvalidArgumentsError;
var InvalidMessageError = scErrors.InvalidMessageError;
var SocketProtocolError = scErrors.SocketProtocolError;
var TimeoutError = scErrors.TimeoutError;
var isBrowser = typeof window != 'undefined';
var SCSocket = function (opts) {
var self = this;
SCEmitter.call(this);
this.id = null;
this.state = this.CLOSED;
this.authState = this.PENDING;
this.signedAuthToken = null;
this.authToken = null;
this.pendingReconnect = false;
this.pendingReconnectTimeout = null;
this.pendingConnectCallback = false;
this.connectTimeout = opts.connectTimeout;
this.ackTimeout = opts.ackTimeout;
this.channelPrefix = opts.channelPrefix || null;
this.disconnectOnUnload = opts.disconnectOnUnload == null ? true : opts.disconnectOnUnload;
// pingTimeout will be ackTimeout at the start, but it will
// be updated with values provided by the 'connect' event
this.pingTimeout = this.ackTimeout;
var maxTimeout = Math.pow(2, 31) - 1;
var verifyDuration = function (propertyName) {
if (self[propertyName] > maxTimeout) {
throw new InvalidArgumentsError('The ' + propertyName +
' value provided exceeded the maximum amount allowed');
}
};
verifyDuration('connectTimeout');
verifyDuration('ackTimeout');
verifyDuration('pingTimeout');
this._localEvents = {
'connect': 1,
'connectAbort': 1,
'disconnect': 1,
'message': 1,
'error': 1,
'raw': 1,
'fail': 1,
'kickOut': 1,
'subscribe': 1,
'unsubscribe': 1,
'subscribeStateChange': 1,
'authStateChange': 1,
'authenticate': 1,
'deauthenticate': 1,
'removeAuthToken': 1,
'subscribeRequest': 1
};
this.connectAttempts = 0;
this._emitBuffer = new LinkedList();
this._channels = {};
this.options = opts;
this._cid = 1;
this.options.callIdGenerator = function () {
return self._callIdGenerator();
};
if (this.options.autoReconnect) {
if (this.options.autoReconnectOptions == null) {
this.options.autoReconnectOptions = {};
}
// Add properties to the this.options.autoReconnectOptions object.
// We assign the reference to a reconnectOptions variable to avoid repetition.
var reconnectOptions = this.options.autoReconnectOptions;
if (reconnectOptions.initialDelay == null) {
reconnectOptions.initialDelay = 10000;
}
if (reconnectOptions.randomness == null) {
reconnectOptions.randomness = 10000;
}
if (reconnectOptions.multiplier == null) {
reconnectOptions.multiplier = 1.5;
}
if (reconnectOptions.maxDelay == null) {
reconnectOptions.maxDelay = 60000;
}
}
if (this.options.subscriptionRetryOptions == null) {
this.options.subscriptionRetryOptions = {};
}
if (this.options.authEngine) {
this.auth = this.options.authEngine;
} else {
this.auth = new AuthEngine();
}
if (this.options.codecEngine) {
this.codec = this.options.codecEngine;
} else {
// Default codec engine
this.codec = formatter;
}
this.options.path = this.options.path.replace(/\/$/, '') + '/';
this.options.query = opts.query || {};
if (typeof this.options.query == 'string') {
this.options.query = querystring.parse(this.options.query);
}
this.connect();
this._channelEmitter = new SCEmitter();
if (isBrowser && this.disconnectOnUnload) {
var unloadHandler = function () {
self.disconnect();
};
if (global.attachEvent) {
global.attachEvent('onunload', unloadHandler);
} else if (global.addEventListener) {
global.addEventListener('beforeunload', unloadHandler, false);
}
}
};
SCSocket.prototype = Object.create(SCEmitter.prototype);
SCSocket.CONNECTING = SCSocket.prototype.CONNECTING = SCTransport.prototype.CONNECTING;
SCSocket.OPEN = SCSocket.prototype.OPEN = SCTransport.prototype.OPEN;
SCSocket.CLOSED = SCSocket.prototype.CLOSED = SCTransport.prototype.CLOSED;
SCSocket.AUTHENTICATED = SCSocket.prototype.AUTHENTICATED = 'authenticated';
SCSocket.UNAUTHENTICATED = SCSocket.prototype.UNAUTHENTICATED = 'unauthenticated';
SCSocket.PENDING = SCSocket.prototype.PENDING = 'pending';
SCSocket.ignoreStatuses = scErrors.socketProtocolIgnoreStatuses;
SCSocket.errorStatuses = scErrors.socketProtocolErrorStatuses;
SCSocket.prototype._privateEventHandlerMap = {
'#publish': function (data) {
var undecoratedChannelName = this._undecorateChannelName(data.channel);
var isSubscribed = this.isSubscribed(undecoratedChannelName, true);
if (isSubscribed) {
this._channelEmitter.emit(undecoratedChannelName, data.data);
}
},
'#kickOut': function (data) {
var undecoratedChannelName = this._undecorateChannelName(data.channel);
var channel = this._channels[undecoratedChannelName];
if (channel) {
SCEmitter.prototype.emit.call(this, 'kickOut', data.message, undecoratedChannelName);
channel.emit('kickOut', data.message, undecoratedChannelName);
this._triggerChannelUnsubscribe(channel);
}
},
'#setAuthToken': function (data, response) {
var self = this;
if (data) {
var triggerAuthenticate = function (err) {
if (err) {
// This is a non-fatal error, we don't want to close the connection
// because of this but we do want to notify the server and throw an error
// on the client.
response.error(err);
self._onSCError(err);
} else {
self._changeToAuthenticatedState(data.token);
response.end();
}
};
this.auth.saveToken(this.options.authTokenName, data.token, {}, triggerAuthenticate);
} else {
response.error(new InvalidMessageError('No token data provided by #setAuthToken event'));
}
},
'#removeAuthToken': function (data, response) {
var self = this;
this.auth.removeToken(this.options.authTokenName, function (err, oldToken) {
if (err) {
// Non-fatal error - Do not close the connection
response.error(err);
self._onSCError(err);
} else {
SCEmitter.prototype.emit.call(self, 'removeAuthToken', oldToken);
self._changeToUnauthenticatedState();
response.end();
}
});
},
'#disconnect': function (data) {
this.transport.close(data.code, data.data);
}
};
SCSocket.prototype._callIdGenerator = function () {
return this._cid++;
};
SCSocket.prototype.getState = function () {
return this.state;
};
SCSocket.prototype.getBytesReceived = function () {
return this.transport.getBytesReceived();
};
SCSocket.prototype.deauthenticate = function (callback) {
var self = this;
this.auth.removeToken(this.options.authTokenName, function (err, oldToken) {
if (err) {
// Non-fatal error - Do not close the connection
self._onSCError(err);
} else {
self.emit('#removeAuthToken');
SCEmitter.prototype.emit.call(self, 'removeAuthToken', oldToken);
self._changeToUnauthenticatedState();
}
callback && callback(err);
});
};
SCSocket.prototype.connect = SCSocket.prototype.open = function () {
var self = this;
if (this.state == this.CLOSED) {
this.pendingReconnect = false;
this.pendingReconnectTimeout = null;
clearTimeout(this._reconnectTimeoutRef);
this.state = this.CONNECTING;
this._changeToPendingAuthState();
if (this.transport) {
this.transport.off();
}
this.transport = new SCTransport(this.auth, this.codec, this.options);
this.transport.on('open', function (status) {
self.state = self.OPEN;
self._onSCOpen(status);
});
this.transport.on('error', function (err) {
self._onSCError(err);
});
this.transport.on('close', function (code, data) {
self.state = self.CLOSED;
self._onSCClose(code, data);
});
this.transport.on('openAbort', function (code, data) {
self.state = self.CLOSED;
self._onSCClose(code, data, true);
});
this.transport.on('event', function (event, data, res) {
self._onSCEvent(event, data, res);
});
}
};
SCSocket.prototype.reconnect = function () {
this.disconnect();
this.connect();
};
SCSocket.prototype.disconnect = function (code, data) {
code = code || 1000;
if (this.state == this.OPEN) {
var packet = {
code: code,
data: data
};
this.transport.emit('#disconnect', packet);
this.transport.close(code, data);
} else if (this.state == this.CONNECTING) {
this.transport.close(code, data);
} else {
this.pendingReconnect = false;
this.pendingReconnectTimeout = null;
clearTimeout(this._reconnectTimeoutRef);
}
};
SCSocket.prototype._changeToPendingAuthState = function () {
if (this.authState != this.PENDING) {
var oldState = this.authState;
this.authState = this.PENDING;
var stateChangeData = {
oldState: oldState,
newState: this.authState
};
SCEmitter.prototype.emit.call(this, 'authStateChange', stateChangeData);
}
};
SCSocket.prototype._changeToUnauthenticatedState = function () {
if (this.authState != this.UNAUTHENTICATED) {
var oldState = this.authState;
this.authState = this.UNAUTHENTICATED;
this.signedAuthToken = null;
this.authToken = null;
var stateChangeData = {
oldState: oldState,
newState: this.authState
};
SCEmitter.prototype.emit.call(this, 'authStateChange', stateChangeData);
if (oldState == this.AUTHENTICATED) {
SCEmitter.prototype.emit.call(this, 'deauthenticate');
}
SCEmitter.prototype.emit.call(this, 'authTokenChange', this.signedAuthToken);
}
};
SCSocket.prototype._changeToAuthenticatedState = function (signedAuthToken) {
this.signedAuthToken = signedAuthToken;
this.authToken = this._extractAuthTokenData(signedAuthToken);
if (this.authState != this.AUTHENTICATED) {
var oldState = this.authState;
this.authState = this.AUTHENTICATED;
var stateChangeData = {
oldState: oldState,
newState: this.authState,
signedAuthToken: signedAuthToken,
authToken: this.authToken
};
this.processPendingSubscriptions();
SCEmitter.prototype.emit.call(this, 'authStateChange', stateChangeData);
SCEmitter.prototype.emit.call(this, 'authenticate', signedAuthToken);
}
SCEmitter.prototype.emit.call(this, 'authTokenChange', signedAuthToken);
};
SCSocket.prototype.decodeBase64 = function (encodedString) {
var decodedString;
if (typeof Buffer == 'undefined') {
if (global.atob) {
decodedString = global.atob(encodedString);
} else {
decodedString = base64.decode(encodedString);
}
} else {
var buffer = new Buffer(encodedString, 'base64');
decodedString = buffer.toString('utf8');
}
return decodedString;
};
SCSocket.prototype.encodeBase64 = function (decodedString) {
var encodedString;
if (typeof Buffer == 'undefined') {
if (global.btoa) {
encodedString = global.btoa(decodedString);
} else {
encodedString = base64.encode(decodedString);
}
} else {
var buffer = new Buffer(decodedString, 'utf8');
encodedString = buffer.toString('base64');
}
return encodedString;
};
SCSocket.prototype._extractAuthTokenData = function (signedAuthToken) {
var tokenParts = (signedAuthToken || '').split('.');
var encodedTokenData = tokenParts[1];
if (encodedTokenData != null) {
var tokenData = encodedTokenData;
try {
tokenData = this.decodeBase64(tokenData);
return JSON.parse(tokenData);
} catch (e) {
return tokenData;
}
}
return null;
};
SCSocket.prototype.getAuthToken = function () {
return this.authToken;
};
SCSocket.prototype.getSignedAuthToken = function () {
return this.signedAuthToken;
};
// Perform client-initiated authentication by providing an encrypted token string
SCSocket.prototype.authenticate = function (signedAuthToken, callback) {
var self = this;
this._changeToPendingAuthState();
this.emit('#authenticate', signedAuthToken, function (err, authStatus) {
if (authStatus && authStatus.authError) {
authStatus.authError = scErrors.hydrateError(authStatus.authError);
}
if (err) {
self._changeToUnauthenticatedState();
callback && callback(err, authStatus);
} else {
self.auth.saveToken(self.options.authTokenName, signedAuthToken, {}, function (err) {
callback && callback(err, authStatus);
if (err) {
self._changeToUnauthenticatedState();
self._onSCError(err);
} else {
if (authStatus.isAuthenticated) {
self._changeToAuthenticatedState(signedAuthToken);
} else {
self._changeToUnauthenticatedState();
}
}
});
}
});
};
SCSocket.prototype._tryReconnect = function (initialDelay) {
var self = this;
var exponent = this.connectAttempts++;
var reconnectOptions = this.options.autoReconnectOptions;
var timeout;
if (initialDelay == null || exponent > 0) {
var initialTimeout = Math.round(reconnectOptions.initialDelay + (reconnectOptions.randomness || 0) * Math.random());
timeout = Math.round(initialTimeout * Math.pow(reconnectOptions.multiplier, exponent));
} else {
timeout = initialDelay;
}
if (timeout > reconnectOptions.maxDelay) {
timeout = reconnectOptions.maxDelay;
}
clearTimeout(this._reconnectTimeoutRef);
this.pendingReconnect = true;
this.pendingReconnectTimeout = timeout;
this._reconnectTimeoutRef = setTimeout(function () {
self.connect();
}, timeout);
};
SCSocket.prototype._onSCOpen = function (status) {
var self = this;
if (status) {
this.id = status.id;
this.pingTimeout = status.pingTimeout;
this.transport.pingTimeout = this.pingTimeout;
if (status.isAuthenticated) {
this._changeToAuthenticatedState(status.authToken);
} else {
this._changeToUnauthenticatedState();
}
} else {
this._changeToUnauthenticatedState();
}
this.connectAttempts = 0;
if (this.options.autoProcessSubscriptions) {
this.processPendingSubscriptions();
} else {
this.pendingConnectCallback = true;
}
// If the user invokes the callback while in autoProcessSubscriptions mode, it
// won't break anything - The processPendingSubscriptions() call will be a no-op.
SCEmitter.prototype.emit.call(this, 'connect', status, function () {
self.processPendingSubscriptions();
});
this._flushEmitBuffer();
};
SCSocket.prototype._onSCError = function (err) {
var self = this;
// Throw error in different stack frame so that error handling
// cannot interfere with a reconnect action.
setTimeout(function () {
if (self.listeners('error').length < 1) {
throw err;
} else {
SCEmitter.prototype.emit.call(self, 'error', err);
}
}, 0);
};
SCSocket.prototype._suspendSubscriptions = function () {
var channel, newState;
for (var channelName in this._channels) {
if (this._channels.hasOwnProperty(channelName)) {
channel = this._channels[channelName];
if (channel.state == channel.SUBSCRIBED ||
channel.state == channel.PENDING) {
newState = channel.PENDING;
} else {
newState = channel.UNSUBSCRIBED;
}
this._triggerChannelUnsubscribe(channel, newState);
}
}
};
SCSocket.prototype._onSCClose = function (code, data, openAbort) {
var self = this;
this.id = null;
if (this.transport) {
this.transport.off();
}
this.pendingReconnect = false;
this.pendingReconnectTimeout = null;
clearTimeout(this._reconnectTimeoutRef);
this._changeToPendingAuthState();
this._suspendSubscriptions();
// Try to reconnect
// on server ping timeout (4000)
// or on client pong timeout (4001)
// or on close without status (1005)
// or on handshake failure (4003)
// or on socket hung up (1006)
if (this.options.autoReconnect) {
if (code == 4000 || code == 4001 || code == 1005) {
// If there is a ping or pong timeout or socket closes without
// status, don't wait before trying to reconnect - These could happen
// if the client wakes up after a period of inactivity and in this case we
// want to re-establish the connection as soon as possible.
this._tryReconnect(0);
// Codes 4500 and above will be treated as permanent disconnects.
// Socket will not try to auto-reconnect.
} else if (code != 1000 && code < 4500) {
this._tryReconnect();
}
}
if (openAbort) {
SCEmitter.prototype.emit.call(self, 'connectAbort', code, data);
} else {
SCEmitter.prototype.emit.call(self, 'disconnect', code, data);
}
if (!SCSocket.ignoreStatuses[code]) {
var failureMessage;
if (data) {
failureMessage = 'Socket connection failed: ' + data;
} else {
failureMessage = 'Socket connection failed for unknown reasons';
}
var err = new SocketProtocolError(SCSocket.errorStatuses[code] || failureMessage, code);
this._onSCError(err);
}
};
SCSocket.prototype._onSCEvent = function (event, data, res) {
var handler = this._privateEventHandlerMap[event];
if (handler) {
handler.call(this, data, res);
} else {
SCEmitter.prototype.emit.call(this, event, data, function () {
res && res.callback.apply(res, arguments);
});
}
};
SCSocket.prototype.decode = function (message) {
return this.transport.decode(message);
};
SCSocket.prototype.encode = function (object) {
return this.transport.encode(object);
};
SCSocket.prototype._flushEmitBuffer = function () {
var currentNode = this._emitBuffer.head;
var nextNode;
while (currentNode) {
nextNode = currentNode.next;
var eventObject = currentNode.data;
currentNode.detach();
this.transport.emitObject(eventObject);
currentNode = nextNode;
}
};
SCSocket.prototype._handleEventAckTimeout = function (eventObject, eventNode) {
if (eventNode) {
eventNode.detach();
}
var callback = eventObject.callback;
if (callback) {
delete eventObject.callback;
var error = new TimeoutError("Event response for '" + eventObject.event + "' timed out");
callback.call(eventObject, error, eventObject);
}
};
SCSocket.prototype._emit = function (event, data, callback) {
var self = this;
if (this.state == this.CLOSED) {
this.connect();
}
var eventObject = {
event: event,
data: data,
callback: callback
};
var eventNode = new LinkedList.Item();
if (this.options.cloneData) {
eventNode.data = cloneDeep(eventObject);
} else {
eventNode.data = eventObject;
}
eventObject.timeout = setTimeout(function () {
self._handleEventAckTimeout(eventObject, eventNode);
}, this.ackTimeout);
this._emitBuffer.append(eventNode);
if (this.state == this.OPEN) {
this._flushEmitBuffer();
}
};
SCSocket.prototype.send = function (data) {
this.transport.send(data);
};
SCSocket.prototype.emit = function (event, data, callback) {
if (this._localEvents[event] == null) {
this._emit(event, data, callback);
} else {
SCEmitter.prototype.emit.call(this, event, data);
}
};
SCSocket.prototype.publish = function (channelName, data, callback) {
var pubData = {
channel: this._decorateChannelName(channelName),
data: data
};
this.emit('#publish', pubData, callback);
};
SCSocket.prototype._triggerChannelSubscribe = function (channel, subscriptionOptions) {
var channelName = channel.name;
if (channel.state != channel.SUBSCRIBED) {
var oldState = channel.state;
channel.state = channel.SUBSCRIBED;
var stateChangeData = {
channel: channelName,
oldState: oldState,
newState: channel.state,
subscriptionOptions: subscriptionOptions
};
channel.emit('subscribeStateChange', stateChangeData);
channel.emit('subscribe', channelName, subscriptionOptions);
SCEmitter.prototype.emit.call(this, 'subscribeStateChange', stateChangeData);
SCEmitter.prototype.emit.call(this, 'subscribe', channelName, subscriptionOptions);
}
};
SCSocket.prototype._triggerChannelSubscribeFail = function (err, channel, subscriptionOptions) {
var channelName = channel.name;
var meetsAuthRequirements = !channel.waitForAuth || this.authState == this.AUTHENTICATED;
if (channel.state != channel.UNSUBSCRIBED && meetsAuthRequirements) {
channel.state = channel.UNSUBSCRIBED;
channel.emit('subscribeFail', err, channelName, subscriptionOptions);
SCEmitter.prototype.emit.call(this, 'subscribeFail', err, channelName, subscriptionOptions);
}
};
// Cancel any pending subscribe callback
SCSocket.prototype._cancelPendingSubscribeCallback = function (channel) {
if (channel._pendingSubscriptionCid != null) {
this.transport.cancelPendingResponse(channel._pendingSubscriptionCid);
delete channel._pendingSubscriptionCid;
}
};
SCSocket.prototype._decorateChannelName = function (channelName) {
if (this.channelPrefix) {
channelName = this.channelPrefix + channelName;
}
return channelName;
};
SCSocket.prototype._undecorateChannelName = function (decoratedChannelName) {
if (this.channelPrefix && decoratedChannelName.indexOf(this.channelPrefix) == 0) {
return decoratedChannelName.replace(this.channelPrefix, '');
}
return decoratedChannelName;
};
SCSocket.prototype._trySubscribe = function (channel) {
var self = this;
var meetsAuthRequirements = !channel.waitForAuth || this.authState == this.AUTHENTICATED;
// We can only ever have one pending subscribe action at any given time on a channel
if (this.state == this.OPEN && !this.pendingConnectCallback &&
channel._pendingSubscriptionCid == null && meetsAuthRequirements) {
var options = {
noTimeout: true
};
var subscriptionOptions = {
channel: this._decorateChannelName(channel.name)
};
if (channel.waitForAuth) {