faye 1.0.4 → 1.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/node/faye-node.js CHANGED
@@ -2,7 +2,7 @@
2
2
  'use strict';
3
3
 
4
4
  var Faye = {
5
- VERSION: '1.0.4',
5
+ VERSION: '1.1.3',
6
6
 
7
7
  BAYEUX_VERSION: '1.0',
8
8
  ID_LENGTH: 160,
@@ -26,7 +26,17 @@ var Faye = {
26
26
 
27
27
  random: function(bitlength) {
28
28
  bitlength = bitlength || this.ID_LENGTH;
29
- return csprng(bitlength, 36);
29
+ var maxLength = Math.ceil(bitlength * Math.log(2) / Math.log(36));
30
+ var string = csprng(bitlength, 36);
31
+ while (string.length < maxLength) string = '0' + string;
32
+ return string;
33
+ },
34
+
35
+ validateOptions: function(options, validKeys) {
36
+ for (var key in options) {
37
+ if (this.indexOf(validKeys, key) < 0)
38
+ throw new Error('Unrecognized option: ' + key);
39
+ }
30
40
  },
31
41
 
32
42
  clientIdFromMessages: function(messages) {
@@ -357,9 +367,8 @@ Faye.Namespace = Faye.Class({
357
367
  (function() {
358
368
  'use strict';
359
369
 
360
- var timeout = setTimeout;
370
+ var timeout = setTimeout, defer;
361
371
 
362
- var defer;
363
372
  if (typeof setImmediate === 'function')
364
373
  defer = function(fn) { setImmediate(fn) };
365
374
  else if (typeof process === 'object' && process.nextTick)
@@ -372,12 +381,12 @@ var PENDING = 0,
372
381
  REJECTED = 2;
373
382
 
374
383
  var RETURN = function(x) { return x },
375
- THROW = function(x) { throw x };
384
+ THROW = function(x) { throw x };
376
385
 
377
386
  var Promise = function(task) {
378
- this._state = PENDING;
379
- this._callbacks = [];
380
- this._errbacks = [];
387
+ this._state = PENDING;
388
+ this._onFulfilled = [];
389
+ this._onRejected = [];
381
390
 
382
391
  if (typeof task !== 'function') return;
383
392
  var self = this;
@@ -386,34 +395,30 @@ var Promise = function(task) {
386
395
  function(reason) { reject(self, reason) });
387
396
  };
388
397
 
389
- Promise.prototype.then = function(callback, errback) {
390
- var next = {}, self = this;
391
-
392
- next.promise = new Promise(function(fulfill, reject) {
393
- next.fulfill = fulfill;
394
- next.reject = reject;
395
-
396
- registerCallback(self, callback, next);
397
- registerErrback(self, errback, next);
398
- });
399
- return next.promise;
398
+ Promise.prototype.then = function(onFulfilled, onRejected) {
399
+ var next = new Promise();
400
+ registerOnFulfilled(this, onFulfilled, next);
401
+ registerOnRejected(this, onRejected, next);
402
+ return next;
400
403
  };
401
404
 
402
- var registerCallback = function(promise, callback, next) {
403
- if (typeof callback !== 'function') callback = RETURN;
404
- var handler = function(value) { invoke(callback, value, next) };
405
+ var registerOnFulfilled = function(promise, onFulfilled, next) {
406
+ if (typeof onFulfilled !== 'function') onFulfilled = RETURN;
407
+ var handler = function(value) { invoke(onFulfilled, value, next) };
408
+
405
409
  if (promise._state === PENDING) {
406
- promise._callbacks.push(handler);
410
+ promise._onFulfilled.push(handler);
407
411
  } else if (promise._state === FULFILLED) {
408
412
  handler(promise._value);
409
413
  }
410
414
  };
411
415
 
412
- var registerErrback = function(promise, errback, next) {
413
- if (typeof errback !== 'function') errback = THROW;
414
- var handler = function(reason) { invoke(errback, reason, next) };
416
+ var registerOnRejected = function(promise, onRejected, next) {
417
+ if (typeof onRejected !== 'function') onRejected = THROW;
418
+ var handler = function(reason) { invoke(onRejected, reason, next) };
419
+
415
420
  if (promise._state === PENDING) {
416
- promise._errbacks.push(handler);
421
+ promise._onRejected.push(handler);
417
422
  } else if (promise._state === REJECTED) {
418
423
  handler(promise._reason);
419
424
  }
@@ -424,55 +429,80 @@ var invoke = function(fn, value, next) {
424
429
  };
425
430
 
426
431
  var _invoke = function(fn, value, next) {
427
- var called = false, outcome, type, then;
432
+ var outcome;
428
433
 
429
434
  try {
430
435
  outcome = fn(value);
431
- type = typeof outcome;
432
- then = outcome !== null && (type === 'function' || type === 'object') && outcome.then;
436
+ } catch (error) {
437
+ return reject(next, error);
438
+ }
433
439
 
434
- if (outcome === next.promise)
435
- return next.reject(new TypeError('Recursive promise chain detected'));
440
+ if (outcome === next) {
441
+ reject(next, new TypeError('Recursive promise chain detected'));
442
+ } else {
443
+ fulfill(next, outcome);
444
+ }
445
+ };
436
446
 
437
- if (typeof then !== 'function') return next.fulfill(outcome);
447
+ var fulfill = Promise.fulfill = Promise.resolve = function(promise, value) {
448
+ var called = false, type, then;
438
449
 
439
- then.call(outcome, function(v) {
440
- if (called) return;
441
- called = true;
442
- _invoke(RETURN, v, next);
450
+ try {
451
+ type = typeof value;
452
+ then = value !== null && (type === 'function' || type === 'object') && value.then;
453
+
454
+ if (typeof then !== 'function') return _fulfill(promise, value);
455
+
456
+ then.call(value, function(v) {
457
+ if (!(called ^ (called = true))) return;
458
+ fulfill(promise, v);
443
459
  }, function(r) {
444
- if (called) return;
445
- called = true;
446
- next.reject(r);
460
+ if (!(called ^ (called = true))) return;
461
+ reject(promise, r);
447
462
  });
448
-
449
463
  } catch (error) {
450
- if (called) return;
451
- called = true;
452
- next.reject(error);
464
+ if (!(called ^ (called = true))) return;
465
+ reject(promise, error);
453
466
  }
454
467
  };
455
468
 
456
- var fulfill = Promise.fulfill = Promise.resolve = function(promise, value) {
469
+ var _fulfill = function(promise, value) {
457
470
  if (promise._state !== PENDING) return;
458
471
 
459
- promise._state = FULFILLED;
460
- promise._value = value;
461
- promise._errbacks = [];
472
+ promise._state = FULFILLED;
473
+ promise._value = value;
474
+ promise._onRejected = [];
462
475
 
463
- var callbacks = promise._callbacks, cb;
464
- while (cb = callbacks.shift()) cb(value);
476
+ var onFulfilled = promise._onFulfilled, fn;
477
+ while (fn = onFulfilled.shift()) fn(value);
465
478
  };
466
479
 
467
480
  var reject = Promise.reject = function(promise, reason) {
468
481
  if (promise._state !== PENDING) return;
469
482
 
470
- promise._state = REJECTED;
471
- promise._reason = reason;
472
- promise._callbacks = [];
483
+ promise._state = REJECTED;
484
+ promise._reason = reason;
485
+ promise._onFulfilled = [];
473
486
 
474
- var errbacks = promise._errbacks, eb;
475
- while (eb = errbacks.shift()) eb(reason);
487
+ var onRejected = promise._onRejected, fn;
488
+ while (fn = onRejected.shift()) fn(reason);
489
+ };
490
+
491
+ Promise.all = function(promises) {
492
+ return new Promise(function(fulfill, reject) {
493
+ var list = [],
494
+ n = promises.length,
495
+ i;
496
+
497
+ if (n === 0) return fulfill(list);
498
+
499
+ for (i = 0; i < n; i++) (function(promise, i) {
500
+ Promise.fulfilled(promise).then(function(value) {
501
+ list[i] = value;
502
+ if (--n === 0) fulfill(list);
503
+ }, reject);
504
+ })(promises[i], i);
505
+ });
476
506
  };
477
507
 
478
508
  Promise.defer = defer;
@@ -744,7 +774,7 @@ Faye.Deferrable = {
744
774
  setDeferredStatus: function(status, value) {
745
775
  if (this._timer) Faye.ENV.clearTimeout(this._timer);
746
776
 
747
- var promise = this.then();
777
+ this.then();
748
778
 
749
779
  if (status === 'succeeded')
750
780
  this._fulfill(value);
@@ -801,7 +831,7 @@ Faye.Timeouts = {
801
831
  this._timeouts = this._timeouts || {};
802
832
  var timeout = this._timeouts[name];
803
833
  if (!timeout) return;
804
- clearTimeout(timeout);
834
+ Faye.ENV.clearTimeout(timeout);
805
835
  delete this._timeouts[name];
806
836
  },
807
837
 
@@ -823,13 +853,13 @@ Faye.Logging = {
823
853
  writeLog: function(messageArgs, level) {
824
854
  if (!Faye.logger) return;
825
855
 
826
- var messageArgs = Array.prototype.slice.apply(messageArgs),
827
- banner = '[Faye',
828
- klass = this.className,
856
+ var args = Array.prototype.slice.apply(messageArgs),
857
+ banner = '[Faye',
858
+ klass = this.className,
829
859
 
830
- message = messageArgs.shift().replace(/\?/g, function() {
860
+ message = args.shift().replace(/\?/g, function() {
831
861
  try {
832
- return Faye.toJSON(messageArgs.shift());
862
+ return Faye.toJSON(args.shift());
833
863
  } catch (e) {
834
864
  return '[Object]';
835
865
  }
@@ -852,11 +882,11 @@ Faye.Logging = {
852
882
 
853
883
  (function() {
854
884
  for (var key in Faye.Logging.LOG_LEVELS)
855
- (function(level, value) {
885
+ (function(level) {
856
886
  Faye.Logging[level] = function() {
857
887
  this.writeLog(arguments, level);
858
888
  };
859
- })(key, Faye.Logging.LOG_LEVELS[key]);
889
+ })(key);
860
890
  })();
861
891
 
862
892
  Faye.Grammar = {
@@ -999,12 +1029,11 @@ Faye.extend(Faye.Channel, {
999
1029
  },
1000
1030
 
1001
1031
  subscribe: function(names, callback, context) {
1002
- if (!callback) return;
1003
1032
  var name;
1004
1033
  for (var i = 0, n = names.length; i < n; i++) {
1005
1034
  name = names[i];
1006
1035
  var channel = this._channels[name] = this._channels[name] || new Faye.Channel(name);
1007
- channel.bind('message', callback, context);
1036
+ if (callback) channel.bind('message', callback, context);
1008
1037
  }
1009
1038
  },
1010
1039
 
@@ -1032,17 +1061,6 @@ Faye.extend(Faye.Channel, {
1032
1061
  })
1033
1062
  });
1034
1063
 
1035
- Faye.Envelope = Faye.Class({
1036
- initialize: function(message, timeout) {
1037
- this.id = message.id;
1038
- this.message = message;
1039
-
1040
- if (timeout !== undefined) this.timeout(timeout / 1000, false);
1041
- }
1042
- });
1043
-
1044
- Faye.extend(Faye.Envelope.prototype, Faye.Deferrable);
1045
-
1046
1064
  Faye.Publication = Faye.Class(Faye.Deferrable);
1047
1065
 
1048
1066
  Faye.Subscription = Faye.Class({
@@ -1068,65 +1086,61 @@ Faye.Subscription = Faye.Class({
1068
1086
  Faye.extend(Faye.Subscription.prototype, Faye.Deferrable);
1069
1087
 
1070
1088
  Faye.Client = Faye.Class({
1071
- UNCONNECTED: 1,
1072
- CONNECTING: 2,
1073
- CONNECTED: 3,
1074
- DISCONNECTED: 4,
1089
+ UNCONNECTED: 1,
1090
+ CONNECTING: 2,
1091
+ CONNECTED: 3,
1092
+ DISCONNECTED: 4,
1075
1093
 
1076
- HANDSHAKE: 'handshake',
1077
- RETRY: 'retry',
1078
- NONE: 'none',
1094
+ HANDSHAKE: 'handshake',
1095
+ RETRY: 'retry',
1096
+ NONE: 'none',
1079
1097
 
1080
- CONNECTION_TIMEOUT: 60,
1081
- DEFAULT_RETRY: 5,
1082
- MAX_REQUEST_SIZE: 2048,
1098
+ CONNECTION_TIMEOUT: 60,
1083
1099
 
1084
- DEFAULT_ENDPOINT: '/bayeux',
1085
- INTERVAL: 0,
1100
+ DEFAULT_ENDPOINT: '/bayeux',
1101
+ INTERVAL: 0,
1086
1102
 
1087
1103
  initialize: function(endpoint, options) {
1088
1104
  this.info('New client created for ?', endpoint);
1105
+ options = options || {};
1089
1106
 
1090
- this._options = options || {};
1091
- this.endpoint = Faye.URI.parse(endpoint || this.DEFAULT_ENDPOINT);
1092
- this.endpoints = this._options.endpoints || {};
1093
- this.transports = {};
1094
- this.cookies = Faye.CookieJar && new Faye.CookieJar();
1095
- this.headers = {};
1096
- this.ca = this._options.ca;
1097
- this._disabled = [];
1098
- this._retry = this._options.retry || this.DEFAULT_RETRY;
1099
-
1100
- for (var key in this.endpoints)
1101
- this.endpoints[key] = Faye.URI.parse(this.endpoints[key]);
1107
+ Faye.validateOptions(options, ['interval', 'timeout', 'endpoints', 'proxy', 'retry', 'scheduler', 'websocketExtensions', 'tls', 'ca']);
1102
1108
 
1103
- this.maxRequestSize = this.MAX_REQUEST_SIZE;
1109
+ this._endpoint = endpoint || this.DEFAULT_ENDPOINT;
1110
+ this._channels = new Faye.Channel.Set();
1111
+ this._dispatcher = new Faye.Dispatcher(this, this._endpoint, options);
1104
1112
 
1105
- this._state = this.UNCONNECTED;
1106
- this._channels = new Faye.Channel.Set();
1107
1113
  this._messageId = 0;
1114
+ this._state = this.UNCONNECTED;
1108
1115
 
1109
1116
  this._responseCallbacks = {};
1110
1117
 
1111
1118
  this._advice = {
1112
1119
  reconnect: this.RETRY,
1113
- interval: 1000 * (this._options.interval || this.INTERVAL),
1114
- timeout: 1000 * (this._options.timeout || this.CONNECTION_TIMEOUT)
1120
+ interval: 1000 * (options.interval || this.INTERVAL),
1121
+ timeout: 1000 * (options.timeout || this.CONNECTION_TIMEOUT)
1115
1122
  };
1123
+ this._dispatcher.timeout = this._advice.timeout / 1000;
1124
+
1125
+ this._dispatcher.bind('message', this._receiveMessage, this);
1116
1126
 
1117
1127
  if (Faye.Event && Faye.ENV.onbeforeunload !== undefined)
1118
1128
  Faye.Event.on(Faye.ENV, 'beforeunload', function() {
1119
- if (Faye.indexOf(this._disabled, 'autodisconnect') < 0)
1129
+ if (Faye.indexOf(this._dispatcher._disabled, 'autodisconnect') < 0)
1120
1130
  this.disconnect();
1121
1131
  }, this);
1122
1132
  },
1123
1133
 
1134
+ addWebsocketExtension: function(extension) {
1135
+ return this._dispatcher.addWebsocketExtension(extension);
1136
+ },
1137
+
1124
1138
  disable: function(feature) {
1125
- this._disabled.push(feature);
1139
+ return this._dispatcher.disable(feature);
1126
1140
  },
1127
1141
 
1128
1142
  setHeader: function(name, value) {
1129
- this.headers[name] = value;
1143
+ return this._dispatcher.setHeader(name, value);
1130
1144
  },
1131
1145
 
1132
1146
  // Request
@@ -1155,30 +1169,30 @@ Faye.Client = Faye.Class({
1155
1169
  this._state = this.CONNECTING;
1156
1170
  var self = this;
1157
1171
 
1158
- this.info('Initiating handshake with ?', Faye.URI.stringify(this.endpoint));
1159
- this._selectTransport(Faye.MANDATORY_CONNECTION_TYPES);
1172
+ this.info('Initiating handshake with ?', Faye.URI.stringify(this._endpoint));
1173
+ this._dispatcher.selectTransport(Faye.MANDATORY_CONNECTION_TYPES);
1160
1174
 
1161
- this._send({
1175
+ this._sendMessage({
1162
1176
  channel: Faye.Channel.HANDSHAKE,
1163
1177
  version: Faye.BAYEUX_VERSION,
1164
- supportedConnectionTypes: [this._transport.connectionType]
1178
+ supportedConnectionTypes: this._dispatcher.getConnectionTypes()
1165
1179
 
1166
- }, function(response) {
1180
+ }, {}, function(response) {
1167
1181
 
1168
1182
  if (response.successful) {
1169
- this._state = this.CONNECTED;
1170
- this._clientId = response.clientId;
1183
+ this._state = this.CONNECTED;
1184
+ this._dispatcher.clientId = response.clientId;
1171
1185
 
1172
- this._selectTransport(response.supportedConnectionTypes);
1186
+ this._dispatcher.selectTransport(response.supportedConnectionTypes);
1173
1187
 
1174
- this.info('Handshake successful: ?', this._clientId);
1188
+ this.info('Handshake successful: ?', this._dispatcher.clientId);
1175
1189
 
1176
1190
  this.subscribe(this._channels.getKeys(), true);
1177
1191
  if (callback) Faye.Promise.defer(function() { callback.call(context) });
1178
1192
 
1179
1193
  } else {
1180
1194
  this.info('Handshake unsuccessful');
1181
- Faye.ENV.setTimeout(function() { self.handshake(callback, context) }, this._advice.interval);
1195
+ Faye.ENV.setTimeout(function() { self.handshake(callback, context) }, this._dispatcher.retry * 1000);
1182
1196
  this._state = this.UNCONNECTED;
1183
1197
  }
1184
1198
  }, this);
@@ -1203,21 +1217,21 @@ Faye.Client = Faye.Class({
1203
1217
  this.callback(callback, context);
1204
1218
  if (this._state !== this.CONNECTED) return;
1205
1219
 
1206
- this.info('Calling deferred actions for ?', this._clientId);
1220
+ this.info('Calling deferred actions for ?', this._dispatcher.clientId);
1207
1221
  this.setDeferredStatus('succeeded');
1208
1222
  this.setDeferredStatus('unknown');
1209
1223
 
1210
1224
  if (this._connectRequest) return;
1211
1225
  this._connectRequest = true;
1212
1226
 
1213
- this.info('Initiating connection for ?', this._clientId);
1227
+ this.info('Initiating connection for ?', this._dispatcher.clientId);
1214
1228
 
1215
- this._send({
1229
+ this._sendMessage({
1216
1230
  channel: Faye.Channel.CONNECT,
1217
- clientId: this._clientId,
1218
- connectionType: this._transport.connectionType
1231
+ clientId: this._dispatcher.clientId,
1232
+ connectionType: this._dispatcher.connectionType
1219
1233
 
1220
- }, this._cycleConnection, this);
1234
+ }, {}, this._cycleConnection, this);
1221
1235
  },
1222
1236
 
1223
1237
  // Request Response
@@ -1231,20 +1245,26 @@ Faye.Client = Faye.Class({
1231
1245
  if (this._state !== this.CONNECTED) return;
1232
1246
  this._state = this.DISCONNECTED;
1233
1247
 
1234
- this.info('Disconnecting ?', this._clientId);
1248
+ this.info('Disconnecting ?', this._dispatcher.clientId);
1249
+ var promise = new Faye.Publication();
1235
1250
 
1236
- this._send({
1251
+ this._sendMessage({
1237
1252
  channel: Faye.Channel.DISCONNECT,
1238
- clientId: this._clientId
1253
+ clientId: this._dispatcher.clientId
1239
1254
 
1240
- }, function(response) {
1241
- if (!response.successful) return;
1242
- this._transport.close();
1243
- delete this._transport;
1255
+ }, {}, function(response) {
1256
+ if (response.successful) {
1257
+ this._dispatcher.close();
1258
+ promise.setDeferredStatus('succeeded');
1259
+ } else {
1260
+ promise.setDeferredStatus('failed', Faye.Error.parse(response.error));
1261
+ }
1244
1262
  }, this);
1245
1263
 
1246
- this.info('Clearing channel listeners for ?', this._clientId);
1264
+ this.info('Clearing channel listeners for ?', this._dispatcher.clientId);
1247
1265
  this._channels = new Faye.Channel.Set();
1266
+
1267
+ return promise;
1248
1268
  },
1249
1269
 
1250
1270
  // Request Response
@@ -1274,22 +1294,22 @@ Faye.Client = Faye.Class({
1274
1294
  }
1275
1295
 
1276
1296
  this.connect(function() {
1277
- this.info('Client ? attempting to subscribe to ?', this._clientId, channel);
1297
+ this.info('Client ? attempting to subscribe to ?', this._dispatcher.clientId, channel);
1278
1298
  if (!force) this._channels.subscribe([channel], callback, context);
1279
1299
 
1280
- this._send({
1300
+ this._sendMessage({
1281
1301
  channel: Faye.Channel.SUBSCRIBE,
1282
- clientId: this._clientId,
1302
+ clientId: this._dispatcher.clientId,
1283
1303
  subscription: channel
1284
1304
 
1285
- }, function(response) {
1305
+ }, {}, function(response) {
1286
1306
  if (!response.successful) {
1287
1307
  subscription.setDeferredStatus('failed', Faye.Error.parse(response.error));
1288
1308
  return this._channels.unsubscribe(channel, callback, context);
1289
1309
  }
1290
1310
 
1291
1311
  var channels = [].concat(response.subscription);
1292
- this.info('Subscription acknowledged for ? to ?', this._clientId, channels);
1312
+ this.info('Subscription acknowledged for ? to ?', this._dispatcher.clientId, channels);
1293
1313
  subscription.setDeferredStatus('succeeded');
1294
1314
  }, this);
1295
1315
  }, this);
@@ -1317,18 +1337,18 @@ Faye.Client = Faye.Class({
1317
1337
  if (!dead) return;
1318
1338
 
1319
1339
  this.connect(function() {
1320
- this.info('Client ? attempting to unsubscribe from ?', this._clientId, channel);
1340
+ this.info('Client ? attempting to unsubscribe from ?', this._dispatcher.clientId, channel);
1321
1341
 
1322
- this._send({
1342
+ this._sendMessage({
1323
1343
  channel: Faye.Channel.UNSUBSCRIBE,
1324
- clientId: this._clientId,
1344
+ clientId: this._dispatcher.clientId,
1325
1345
  subscription: channel
1326
1346
 
1327
- }, function(response) {
1347
+ }, {}, function(response) {
1328
1348
  if (!response.successful) return;
1329
1349
 
1330
1350
  var channels = [].concat(response.subscription);
1331
- this.info('Unsubscription acknowledged for ? from ?', this._clientId, channels);
1351
+ this.info('Unsubscription acknowledged for ? from ?', this._dispatcher.clientId, channels);
1332
1352
  }, this);
1333
1353
  }, this);
1334
1354
  },
@@ -1339,18 +1359,19 @@ Faye.Client = Faye.Class({
1339
1359
  // MAY include: * clientId MAY include: * id
1340
1360
  // * id * error
1341
1361
  // * ext * ext
1342
- publish: function(channel, data) {
1362
+ publish: function(channel, data, options) {
1363
+ Faye.validateOptions(options || {}, ['attempts', 'deadline']);
1343
1364
  var publication = new Faye.Publication();
1344
1365
 
1345
1366
  this.connect(function() {
1346
- this.info('Client ? queueing published message to ?: ?', this._clientId, channel, data);
1367
+ this.info('Client ? queueing published message to ?: ?', this._dispatcher.clientId, channel, data);
1347
1368
 
1348
- this._send({
1369
+ this._sendMessage({
1349
1370
  channel: channel,
1350
1371
  data: data,
1351
- clientId: this._clientId
1372
+ clientId: this._dispatcher.clientId
1352
1373
 
1353
- }, function(response) {
1374
+ }, options, function(response) {
1354
1375
  if (response.successful)
1355
1376
  publication.setDeferredStatus('succeeded');
1356
1377
  else
@@ -1361,8 +1382,28 @@ Faye.Client = Faye.Class({
1361
1382
  return publication;
1362
1383
  },
1363
1384
 
1364
- receiveMessage: function(message) {
1365
- var id = message.id, timeout, callback;
1385
+ _sendMessage: function(message, options, callback, context) {
1386
+ message.id = this._generateMessageId();
1387
+
1388
+ var timeout = this._advice.timeout
1389
+ ? 1.2 * this._advice.timeout / 1000
1390
+ : 1.2 * this._dispatcher.retry;
1391
+
1392
+ this.pipeThroughExtensions('outgoing', message, null, function(message) {
1393
+ if (!message) return;
1394
+ if (callback) this._responseCallbacks[message.id] = [callback, context];
1395
+ this._dispatcher.sendMessage(message, timeout, options || {});
1396
+ }, this);
1397
+ },
1398
+
1399
+ _generateMessageId: function() {
1400
+ this._messageId += 1;
1401
+ if (this._messageId >= Math.pow(2,32)) this._messageId = 0;
1402
+ return this._messageId.toString(36);
1403
+ },
1404
+
1405
+ _receiveMessage: function(message) {
1406
+ var id = message.id, callback;
1366
1407
 
1367
1408
  if (message.successful !== undefined) {
1368
1409
  callback = this._responseCallbacks[id];
@@ -1371,39 +1412,112 @@ Faye.Client = Faye.Class({
1371
1412
 
1372
1413
  this.pipeThroughExtensions('incoming', message, null, function(message) {
1373
1414
  if (!message) return;
1374
-
1375
1415
  if (message.advice) this._handleAdvice(message.advice);
1376
1416
  this._deliverMessage(message);
1377
-
1378
1417
  if (callback) callback[0].call(callback[1], message);
1379
1418
  }, this);
1419
+ },
1420
+
1421
+ _handleAdvice: function(advice) {
1422
+ Faye.extend(this._advice, advice);
1423
+ this._dispatcher.timeout = this._advice.timeout / 1000;
1380
1424
 
1381
- if (this._transportUp === true) return;
1382
- this._transportUp = true;
1383
- this.trigger('transport:up');
1425
+ if (this._advice.reconnect === this.HANDSHAKE && this._state !== this.DISCONNECTED) {
1426
+ this._state = this.UNCONNECTED;
1427
+ this._dispatcher.clientId = null;
1428
+ this._cycleConnection();
1429
+ }
1384
1430
  },
1385
1431
 
1386
- messageError: function(messages, immediate) {
1387
- var retry = this._retry,
1388
- self = this,
1389
- id, message, timeout;
1432
+ _deliverMessage: function(message) {
1433
+ if (!message.channel || message.data === undefined) return;
1434
+ this.info('Client ? calling listeners for ? with ?', this._dispatcher.clientId, message.channel, message.data);
1435
+ this._channels.distributeMessage(message);
1436
+ },
1390
1437
 
1391
- for (var i = 0, n = messages.length; i < n; i++) {
1392
- message = messages[i];
1393
- id = message.id;
1438
+ _cycleConnection: function() {
1439
+ if (this._connectRequest) {
1440
+ this._connectRequest = null;
1441
+ this.info('Closed connection for ?', this._dispatcher.clientId);
1442
+ }
1443
+ var self = this;
1444
+ Faye.ENV.setTimeout(function() { self.connect() }, this._advice.interval);
1445
+ }
1446
+ });
1394
1447
 
1395
- if (immediate)
1396
- this._transportSend(message);
1397
- else
1398
- Faye.ENV.setTimeout(function() { self._transportSend(message) }, retry * 1000);
1448
+ Faye.extend(Faye.Client.prototype, Faye.Deferrable);
1449
+ Faye.extend(Faye.Client.prototype, Faye.Publisher);
1450
+ Faye.extend(Faye.Client.prototype, Faye.Logging);
1451
+ Faye.extend(Faye.Client.prototype, Faye.Extensible);
1452
+
1453
+ Faye.Dispatcher = Faye.Class({
1454
+ MAX_REQUEST_SIZE: 2048,
1455
+ DEFAULT_RETRY: 5,
1456
+
1457
+ UP: 1,
1458
+ DOWN: 2,
1459
+
1460
+ initialize: function(client, endpoint, options) {
1461
+ this._client = client;
1462
+ this.endpoint = Faye.URI.parse(endpoint);
1463
+ this._alternates = options.endpoints || {};
1464
+
1465
+ this.cookies = Faye.Cookies && new Faye.Cookies.CookieJar();
1466
+ this._disabled = [];
1467
+ this._envelopes = {};
1468
+ this.headers = {};
1469
+ this.retry = options.retry || this.DEFAULT_RETRY;
1470
+ this._scheduler = options.scheduler || Faye.Scheduler;
1471
+ this._state = 0;
1472
+ this.transports = {};
1473
+ this.wsExtensions = [];
1474
+
1475
+ this.proxy = options.proxy || {};
1476
+ if (typeof this._proxy === 'string') this._proxy = {origin: this._proxy};
1477
+
1478
+ var exts = options.websocketExtensions;
1479
+ if (exts) {
1480
+ exts = [].concat(exts);
1481
+ for (var i = 0, n = exts.length; i < n; i++)
1482
+ this.addWebsocketExtension(exts[i]);
1399
1483
  }
1400
1484
 
1401
- if (immediate || this._transportUp === false) return;
1402
- this._transportUp = false;
1403
- this.trigger('transport:down');
1485
+ this.tls = options.tls || {};
1486
+ this.tls.ca = this.tls.ca || options.ca;
1487
+
1488
+ for (var type in this._alternates)
1489
+ this._alternates[type] = Faye.URI.parse(this._alternates[type]);
1490
+
1491
+ this.maxRequestSize = this.MAX_REQUEST_SIZE;
1492
+ },
1493
+
1494
+ endpointFor: function(connectionType) {
1495
+ return this._alternates[connectionType] || this.endpoint;
1496
+ },
1497
+
1498
+ addWebsocketExtension: function(extension) {
1499
+ this.wsExtensions.push(extension);
1500
+ },
1501
+
1502
+ disable: function(feature) {
1503
+ this._disabled.push(feature);
1504
+ },
1505
+
1506
+ setHeader: function(name, value) {
1507
+ this.headers[name] = value;
1508
+ },
1509
+
1510
+ close: function() {
1511
+ var transport = this._transport;
1512
+ delete this._transport;
1513
+ if (transport) transport.close();
1514
+ },
1515
+
1516
+ getConnectionTypes: function() {
1517
+ return Faye.Transport.getConnectionTypes();
1404
1518
  },
1405
1519
 
1406
- _selectTransport: function(transportTypes) {
1520
+ selectTransport: function(transportTypes) {
1407
1521
  Faye.Transport.get(this, transportTypes, this._disabled, function(transport) {
1408
1522
  this.debug('Selected ? transport for ?', transport.connectionType, Faye.URI.stringify(transport.endpoint));
1409
1523
 
@@ -1411,186 +1525,275 @@ Faye.Client = Faye.Class({
1411
1525
  if (this._transport) this._transport.close();
1412
1526
 
1413
1527
  this._transport = transport;
1528
+ this.connectionType = transport.connectionType;
1414
1529
  }, this);
1415
1530
  },
1416
1531
 
1417
- _send: function(message, callback, context) {
1418
- if (!this._transport) return;
1419
- message.id = message.id || this._generateMessageId();
1532
+ sendMessage: function(message, timeout, options) {
1533
+ options = options || {};
1420
1534
 
1421
- this.pipeThroughExtensions('outgoing', message, null, function(message) {
1422
- if (!message) return;
1423
- if (callback) this._responseCallbacks[message.id] = [callback, context];
1424
- this._transportSend(message);
1425
- }, this);
1535
+ var id = message.id,
1536
+ attempts = options.attempts,
1537
+ deadline = options.deadline && new Date().getTime() + (options.deadline * 1000),
1538
+ envelope = this._envelopes[id],
1539
+ scheduler;
1540
+
1541
+ if (!envelope) {
1542
+ scheduler = new this._scheduler(message, {timeout: timeout, interval: this.retry, attempts: attempts, deadline: deadline});
1543
+ envelope = this._envelopes[id] = {message: message, scheduler: scheduler};
1544
+ }
1545
+
1546
+ this._sendEnvelope(envelope);
1426
1547
  },
1427
1548
 
1428
- _transportSend: function(message) {
1549
+ _sendEnvelope: function(envelope) {
1429
1550
  if (!this._transport) return;
1551
+ if (envelope.request || envelope.timer) return;
1430
1552
 
1431
- var timeout = 1.2 * (this._advice.timeout || this._retry * 1000),
1432
- envelope = new Faye.Envelope(message, timeout);
1553
+ var message = envelope.message,
1554
+ scheduler = envelope.scheduler,
1555
+ self = this;
1433
1556
 
1434
- envelope.errback(function(immediate) {
1435
- this.messageError([message], immediate);
1436
- }, this);
1557
+ if (!scheduler.isDeliverable()) {
1558
+ scheduler.abort();
1559
+ delete this._envelopes[message.id];
1560
+ return;
1561
+ }
1437
1562
 
1438
- this._transport.send(envelope);
1439
- },
1563
+ envelope.timer = Faye.ENV.setTimeout(function() {
1564
+ self.handleError(message);
1565
+ }, scheduler.getTimeout() * 1000);
1440
1566
 
1441
- _generateMessageId: function() {
1442
- this._messageId += 1;
1443
- if (this._messageId >= Math.pow(2,32)) this._messageId = 0;
1444
- return this._messageId.toString(36);
1567
+ scheduler.send();
1568
+ envelope.request = this._transport.sendMessage(message);
1445
1569
  },
1446
1570
 
1447
- _handleAdvice: function(advice) {
1448
- Faye.extend(this._advice, advice);
1571
+ handleResponse: function(reply) {
1572
+ var envelope = this._envelopes[reply.id];
1449
1573
 
1450
- if (this._advice.reconnect === this.HANDSHAKE && this._state !== this.DISCONNECTED) {
1451
- this._state = this.UNCONNECTED;
1452
- this._clientId = null;
1453
- this._cycleConnection();
1574
+ if (reply.successful !== undefined && envelope) {
1575
+ envelope.scheduler.succeed();
1576
+ delete this._envelopes[reply.id];
1577
+ Faye.ENV.clearTimeout(envelope.timer);
1454
1578
  }
1455
- },
1456
1579
 
1457
- _deliverMessage: function(message) {
1458
- if (!message.channel || message.data === undefined) return;
1459
- this.info('Client ? calling listeners for ? with ?', this._clientId, message.channel, message.data);
1460
- this._channels.distributeMessage(message);
1580
+ this.trigger('message', reply);
1581
+
1582
+ if (this._state === this.UP) return;
1583
+ this._state = this.UP;
1584
+ this._client.trigger('transport:up');
1461
1585
  },
1462
1586
 
1463
- _cycleConnection: function() {
1464
- if (this._connectRequest) {
1465
- this._connectRequest = null;
1466
- this.info('Closed connection for ?', this._clientId);
1587
+ handleError: function(message, immediate) {
1588
+ var envelope = this._envelopes[message.id],
1589
+ request = envelope && envelope.request,
1590
+ self = this;
1591
+
1592
+ if (!request) return;
1593
+
1594
+ request.then(function(req) {
1595
+ if (req && req.abort) req.abort();
1596
+ });
1597
+
1598
+ var scheduler = envelope.scheduler;
1599
+ scheduler.fail();
1600
+
1601
+ Faye.ENV.clearTimeout(envelope.timer);
1602
+ envelope.request = envelope.timer = null;
1603
+
1604
+ if (immediate) {
1605
+ this._sendEnvelope(envelope);
1606
+ } else {
1607
+ envelope.timer = Faye.ENV.setTimeout(function() {
1608
+ envelope.timer = null;
1609
+ self._sendEnvelope(envelope);
1610
+ }, scheduler.getInterval() * 1000);
1467
1611
  }
1468
- var self = this;
1469
- Faye.ENV.setTimeout(function() { self.connect() }, this._advice.interval);
1612
+
1613
+ if (this._state === this.DOWN) return;
1614
+ this._state = this.DOWN;
1615
+ this._client.trigger('transport:down');
1470
1616
  }
1471
1617
  });
1472
1618
 
1473
- Faye.extend(Faye.Client.prototype, Faye.Deferrable);
1474
- Faye.extend(Faye.Client.prototype, Faye.Publisher);
1475
- Faye.extend(Faye.Client.prototype, Faye.Logging);
1476
- Faye.extend(Faye.Client.prototype, Faye.Extensible);
1619
+ Faye.extend(Faye.Dispatcher.prototype, Faye.Publisher);
1620
+ Faye.extend(Faye.Dispatcher.prototype, Faye.Logging);
1621
+
1622
+ Faye.Scheduler = function(message, options) {
1623
+ this.message = message;
1624
+ this.options = options;
1625
+ this.attempts = 0;
1626
+ };
1627
+
1628
+ Faye.extend(Faye.Scheduler.prototype, {
1629
+ getTimeout: function() {
1630
+ return this.options.timeout;
1631
+ },
1632
+
1633
+ getInterval: function() {
1634
+ return this.options.interval;
1635
+ },
1636
+
1637
+ isDeliverable: function() {
1638
+ var attempts = this.options.attempts,
1639
+ made = this.attempts,
1640
+ deadline = this.options.deadline,
1641
+ now = new Date().getTime();
1642
+
1643
+ if (attempts !== undefined && made >= attempts)
1644
+ return false;
1645
+
1646
+ if (deadline !== undefined && now > deadline)
1647
+ return false;
1648
+
1649
+ return true;
1650
+ },
1651
+
1652
+ send: function() {
1653
+ this.attempts += 1;
1654
+ },
1655
+
1656
+ succeed: function() {},
1657
+
1658
+ fail: function() {},
1659
+
1660
+ abort: function() {}
1661
+ });
1477
1662
 
1478
1663
  Faye.Transport = Faye.extend(Faye.Class({
1479
- MAX_DELAY: 0,
1664
+ DEFAULT_PORTS: {'http:': 80, 'https:': 443, 'ws:': 80, 'wss:': 443},
1665
+ SECURE_PROTOCOLS: ['https:', 'wss:'],
1666
+ MAX_DELAY: 0,
1667
+
1480
1668
  batching: true,
1481
1669
 
1482
- initialize: function(client, endpoint) {
1483
- this._client = client;
1484
- this.endpoint = endpoint;
1485
- this._outbox = [];
1670
+ initialize: function(dispatcher, endpoint) {
1671
+ this._dispatcher = dispatcher;
1672
+ this.endpoint = endpoint;
1673
+ this._outbox = [];
1674
+ this._proxy = Faye.extend({}, this._dispatcher.proxy);
1675
+
1676
+ if (!this._proxy.origin && Faye.NodeAdapter) {
1677
+ this._proxy.origin = Faye.indexOf(this.SECURE_PROTOCOLS, this.endpoint.protocol) >= 0
1678
+ ? (process.env.HTTPS_PROXY || process.env.https_proxy)
1679
+ : (process.env.HTTP_PROXY || process.env.http_proxy);
1680
+ }
1486
1681
  },
1487
1682
 
1488
1683
  close: function() {},
1489
1684
 
1490
- encode: function(envelopes) {
1685
+ encode: function(messages) {
1491
1686
  return '';
1492
1687
  },
1493
1688
 
1494
- send: function(envelope) {
1495
- var message = envelope.message;
1496
-
1689
+ sendMessage: function(message) {
1497
1690
  this.debug('Client ? sending message to ?: ?',
1498
- this._client._clientId, Faye.URI.stringify(this.endpoint), message);
1691
+ this._dispatcher.clientId, Faye.URI.stringify(this.endpoint), message);
1499
1692
 
1500
- if (!this.batching) return this.request([envelope]);
1693
+ if (!this.batching) return Faye.Promise.fulfilled(this.request([message]));
1501
1694
 
1502
- this._outbox.push(envelope);
1695
+ this._outbox.push(message);
1696
+ this._promise = this._promise || new Faye.Promise();
1697
+ this._flushLargeBatch();
1503
1698
 
1504
- if (message.channel === Faye.Channel.HANDSHAKE)
1505
- return this.addTimeout('publish', 0.01, this.flush, this);
1699
+ if (message.channel === Faye.Channel.HANDSHAKE) {
1700
+ this.addTimeout('publish', 0.01, this._flush, this);
1701
+ return this._promise;
1702
+ }
1506
1703
 
1507
1704
  if (message.channel === Faye.Channel.CONNECT)
1508
1705
  this._connectMessage = message;
1509
1706
 
1510
- this.flushLargeBatch();
1511
- this.addTimeout('publish', this.MAX_DELAY, this.flush, this);
1707
+ this.addTimeout('publish', this.MAX_DELAY, this._flush, this);
1708
+ return this._promise;
1512
1709
  },
1513
1710
 
1514
- flush: function() {
1711
+ _flush: function() {
1515
1712
  this.removeTimeout('publish');
1516
1713
 
1517
1714
  if (this._outbox.length > 1 && this._connectMessage)
1518
1715
  this._connectMessage.advice = {timeout: 0};
1519
1716
 
1520
- this.request(this._outbox);
1717
+ Faye.Promise.fulfill(this._promise, this.request(this._outbox));
1718
+ delete this._promise;
1521
1719
 
1522
1720
  this._connectMessage = null;
1523
1721
  this._outbox = [];
1524
1722
  },
1525
1723
 
1526
- flushLargeBatch: function() {
1724
+ _flushLargeBatch: function() {
1527
1725
  var string = this.encode(this._outbox);
1528
- if (string.length < this._client.maxRequestSize) return;
1726
+ if (string.length < this._dispatcher.maxRequestSize) return;
1529
1727
  var last = this._outbox.pop();
1530
- this.flush();
1728
+ this._flush();
1531
1729
  if (last) this._outbox.push(last);
1532
1730
  },
1533
1731
 
1534
- receive: function(envelopes, responses) {
1535
- var n = envelopes.length;
1536
- while (n--) envelopes[n].setDeferredStatus('succeeded');
1537
-
1538
- responses = [].concat(responses);
1732
+ _receive: function(replies) {
1733
+ if (!replies) return;
1734
+ replies = [].concat(replies);
1539
1735
 
1540
- this.debug('Client ? received from ?: ?',
1541
- this._client._clientId, Faye.URI.stringify(this.endpoint), responses);
1736
+ this.debug('Client ? received from ? via ?: ?',
1737
+ this._dispatcher.clientId, Faye.URI.stringify(this.endpoint), this.connectionType, replies);
1542
1738
 
1543
- for (var i = 0, n = responses.length; i < n; i++)
1544
- this._client.receiveMessage(responses[i]);
1739
+ for (var i = 0, n = replies.length; i < n; i++)
1740
+ this._dispatcher.handleResponse(replies[i]);
1545
1741
  },
1546
1742
 
1547
- handleError: function(envelopes, immediate) {
1548
- var n = envelopes.length;
1549
- while (n--) envelopes[n].setDeferredStatus('failed', immediate);
1743
+ _handleError: function(messages, immediate) {
1744
+ messages = [].concat(messages);
1745
+
1746
+ this.debug('Client ? failed to send to ? via ?: ?',
1747
+ this._dispatcher.clientId, Faye.URI.stringify(this.endpoint), this.connectionType, messages);
1748
+
1749
+ for (var i = 0, n = messages.length; i < n; i++)
1750
+ this._dispatcher.handleError(messages[i]);
1550
1751
  },
1551
1752
 
1552
1753
  _getCookies: function() {
1553
- var cookies = this._client.cookies;
1754
+ var cookies = this._dispatcher.cookies,
1755
+ url = Faye.URI.stringify(this.endpoint);
1756
+
1554
1757
  if (!cookies) return '';
1555
1758
 
1556
- return cookies.getCookies({
1557
- domain: this.endpoint.hostname,
1558
- path: this.endpoint.path,
1559
- secure: this.endpoint.protocol === 'https:'
1560
- }).toValueString();
1759
+ return Faye.map(cookies.getCookiesSync(url), function(cookie) {
1760
+ return cookie.cookieString();
1761
+ }).join('; ');
1561
1762
  },
1562
1763
 
1563
1764
  _storeCookies: function(setCookie) {
1564
- if (!setCookie || !this._client.cookies) return;
1765
+ var cookies = this._dispatcher.cookies,
1766
+ url = Faye.URI.stringify(this.endpoint),
1767
+ cookie;
1768
+
1769
+ if (!setCookie || !cookies) return;
1565
1770
  setCookie = [].concat(setCookie);
1566
- var cookie;
1567
1771
 
1568
1772
  for (var i = 0, n = setCookie.length; i < n; i++) {
1569
- cookie = this._client.cookies.setCookie(setCookie[i]);
1570
- cookie = cookie[0] || cookie;
1571
- cookie.domain = cookie.domain || this.endpoint.hostname;
1773
+ cookie = Faye.Cookies.Cookie.parse(setCookie[i]);
1774
+ cookies.setCookieSync(cookie, url);
1572
1775
  }
1573
1776
  }
1574
1777
 
1575
1778
  }), {
1576
- get: function(client, allowed, disabled, callback, context) {
1577
- var endpoint = client.endpoint;
1779
+ get: function(dispatcher, allowed, disabled, callback, context) {
1780
+ var endpoint = dispatcher.endpoint;
1578
1781
 
1579
1782
  Faye.asyncEach(this._transports, function(pair, resume) {
1580
1783
  var connType = pair[0], klass = pair[1],
1581
- connEndpoint = client.endpoints[connType] || endpoint;
1784
+ connEndpoint = dispatcher.endpointFor(connType);
1582
1785
 
1583
1786
  if (Faye.indexOf(disabled, connType) >= 0)
1584
1787
  return resume();
1585
1788
 
1586
1789
  if (Faye.indexOf(allowed, connType) < 0) {
1587
- klass.isUsable(client, connEndpoint, function() {});
1790
+ klass.isUsable(dispatcher, connEndpoint, function() {});
1588
1791
  return resume();
1589
1792
  }
1590
1793
 
1591
- klass.isUsable(client, connEndpoint, function(isUsable) {
1794
+ klass.isUsable(dispatcher, connEndpoint, function(isUsable) {
1592
1795
  if (!isUsable) return resume();
1593
- var transport = klass.hasOwnProperty('create') ? klass.create(client, connEndpoint) : new klass(client, connEndpoint);
1796
+ var transport = klass.hasOwnProperty('create') ? klass.create(dispatcher, connEndpoint) : new klass(dispatcher, connEndpoint);
1594
1797
  callback.call(context, transport);
1595
1798
  });
1596
1799
  }, function() {
@@ -1603,6 +1806,10 @@ Faye.Transport = Faye.extend(Faye.Class({
1603
1806
  klass.prototype.connectionType = type;
1604
1807
  },
1605
1808
 
1809
+ getConnectionTypes: function() {
1810
+ return Faye.map(this._transports, function(t) { return t[0] });
1811
+ },
1812
+
1606
1813
  _transports: []
1607
1814
  });
1608
1815
 
@@ -1635,7 +1842,7 @@ Faye.Engine.Proxy = Faye.Class({
1635
1842
 
1636
1843
  this.bind('close', function(clientId) {
1637
1844
  var self = this;
1638
- Faye.Promise.defer(function() { self.flush(clientId) });
1845
+ Faye.Promise.defer(function() { self.flushConnection(clientId) });
1639
1846
  }, this);
1640
1847
 
1641
1848
  this.debug('Created new engine: ?', this._options);
@@ -1691,15 +1898,18 @@ Faye.Engine.Proxy = Faye.Class({
1691
1898
  return Faye.random();
1692
1899
  },
1693
1900
 
1694
- flush: function(clientId) {
1901
+ flushConnection: function(clientId, close) {
1695
1902
  if (!clientId) return;
1696
1903
  this.debug('Flushing connection for ?', clientId);
1697
1904
  var conn = this.connection(clientId, false);
1698
- if (conn) conn.flush(true);
1905
+ if (!conn) return;
1906
+ if (close === false) conn.socket = null;
1907
+ conn.flush();
1908
+ this.closeConnection(clientId);
1699
1909
  },
1700
1910
 
1701
1911
  close: function() {
1702
- for (var clientId in this._connections) this.flush(clientId);
1912
+ for (var clientId in this._connections) this.flushConnection(clientId);
1703
1913
  this._engine.disconnect();
1704
1914
  },
1705
1915
 
@@ -1717,7 +1927,7 @@ Faye.Engine.METHODS.forEach(function(method) {
1717
1927
  Faye.Engine.Proxy.prototype[method] = function() {
1718
1928
  return this._engine[method].apply(this._engine, arguments);
1719
1929
  };
1720
- })
1930
+ });
1721
1931
 
1722
1932
  Faye.extend(Faye.Engine.Proxy.prototype, Faye.Publisher);
1723
1933
  Faye.extend(Faye.Engine.Proxy.prototype, Faye.Logging);
@@ -1731,6 +1941,7 @@ Faye.Engine.Connection = Faye.Class({
1731
1941
  },
1732
1942
 
1733
1943
  deliver: function(message) {
1944
+ delete message.clientId;
1734
1945
  if (this.socket) return this.socket.send(message);
1735
1946
  this._inbox.push(message);
1736
1947
  this._beginDeliveryTimeout();
@@ -1747,14 +1958,14 @@ Faye.Engine.Connection = Faye.Class({
1747
1958
  this._beginConnectionTimeout(timeout);
1748
1959
  },
1749
1960
 
1750
- flush: function(force) {
1751
- if (force || !this.socket) this._engine.closeConnection(this._id);
1752
-
1961
+ flush: function() {
1753
1962
  this.removeTimeout('connection');
1754
1963
  this.removeTimeout('delivery');
1755
1964
 
1756
1965
  this.setDeferredStatus('succeeded', this._inbox);
1757
1966
  this._inbox = [];
1967
+
1968
+ if (!this.socket) this._engine.closeConnection(this._id);
1758
1969
  },
1759
1970
 
1760
1971
  _beginDeliveryTimeout: function() {
@@ -1916,8 +2127,8 @@ Faye.Server = Faye.Class({
1916
2127
  this._engine.openSocket(clientId, new Faye.Server.Socket(this, socket, request));
1917
2128
  },
1918
2129
 
1919
- closeSocket: function(clientId) {
1920
- this._engine.flush(clientId);
2130
+ closeSocket: function(clientId, close) {
2131
+ this._engine.flushConnection(clientId, close);
1921
2132
  },
1922
2133
 
1923
2134
  process: function(messages, request, callback, context) {
@@ -1991,7 +2202,6 @@ Faye.Server = Faye.Class({
1991
2202
  if (!Faye.Grammar.CHANNEL_NAME.test(channelName))
1992
2203
  error = Faye.Error.channelInvalid(channelName);
1993
2204
 
1994
- delete message.clientId;
1995
2205
  if (!error) this._engine.publish(message);
1996
2206
 
1997
2207
  response = this._makeResponse(message);
@@ -2001,8 +2211,7 @@ Faye.Server = Faye.Class({
2001
2211
  },
2002
2212
 
2003
2213
  _handleMeta: function(message, local, callback, context) {
2004
- var method = this._methodFor(message),
2005
- clientId = message.clientId,
2214
+ var method = this._methodFor(message),
2006
2215
  response;
2007
2216
 
2008
2217
  if (method === null) {
@@ -2243,11 +2452,10 @@ Faye.Server.Socket = Faye.Class({
2243
2452
  Faye.Transport.NodeLocal = Faye.extend(Faye.Class(Faye.Transport, {
2244
2453
  batching: false,
2245
2454
 
2246
- request: function(envelopes) {
2247
- var messages = Faye.map(envelopes, function(e) { return e.message });
2455
+ request: function(messages) {
2248
2456
  messages = Faye.copyObject(messages);
2249
- this.endpoint.process(messages, null, function(responses) {
2250
- this.receive(envelopes, Faye.copyObject(responses));
2457
+ this.endpoint.process(messages, null, function(replies) {
2458
+ this._receive(Faye.copyObject(replies));
2251
2459
  }, this);
2252
2460
  }
2253
2461
  }), {
@@ -2271,16 +2479,23 @@ Faye.Transport.WebSocket = Faye.extend(Faye.Class(Faye.Transport, {
2271
2479
  this.connect();
2272
2480
  },
2273
2481
 
2274
- request: function(envelopes) {
2482
+ request: function(messages) {
2275
2483
  this._pending = this._pending || new Faye.Set();
2276
- for (var i = 0, n = envelopes.length; i < n; i++) this._pending.add(envelopes[i]);
2484
+ for (var i = 0, n = messages.length; i < n; i++) this._pending.add(messages[i]);
2485
+
2486
+ var promise = new Faye.Promise();
2277
2487
 
2278
2488
  this.callback(function(socket) {
2279
- if (!socket) return;
2280
- var messages = Faye.map(envelopes, function(e) { return e.message });
2489
+ if (!socket || socket.readyState !== 1) return;
2281
2490
  socket.send(Faye.toJSON(messages));
2491
+ Faye.Promise.fulfill(promise, socket);
2282
2492
  }, this);
2493
+
2283
2494
  this.connect();
2495
+
2496
+ return {
2497
+ abort: function() { promise.then(function(ws) { ws.close() }) }
2498
+ };
2284
2499
  },
2285
2500
 
2286
2501
  connect: function() {
@@ -2321,28 +2536,25 @@ Faye.Transport.WebSocket = Faye.extend(Faye.Class(Faye.Transport, {
2321
2536
  delete self._pending;
2322
2537
 
2323
2538
  if (wasConnected) {
2324
- self.handleError(pending, true);
2539
+ self._handleError(pending, true);
2325
2540
  } else if (self._everConnected) {
2326
- self.handleError(pending);
2541
+ self._handleError(pending);
2327
2542
  } else {
2328
2543
  self.setDeferredStatus('failed');
2329
2544
  }
2330
2545
  };
2331
2546
 
2332
2547
  socket.onmessage = function(event) {
2333
- var messages = JSON.parse(event.data),
2334
- envelopes = [],
2335
- envelope;
2548
+ var replies = JSON.parse(event.data);
2549
+ if (!replies) return;
2336
2550
 
2337
- if (!messages) return;
2338
- messages = [].concat(messages);
2551
+ replies = [].concat(replies);
2339
2552
 
2340
- for (var i = 0, n = messages.length; i < n; i++) {
2341
- if (messages[i].successful === undefined) continue;
2342
- envelope = self._pending.remove(messages[i]);
2343
- if (envelope) envelopes.push(envelope);
2553
+ for (var i = 0, n = replies.length; i < n; i++) {
2554
+ if (replies[i].successful === undefined) continue;
2555
+ self._pending.remove(replies[i]);
2344
2556
  }
2345
- self.receive(envelopes, messages);
2557
+ self._receive(replies);
2346
2558
  };
2347
2559
  },
2348
2560
 
@@ -2352,10 +2564,14 @@ Faye.Transport.WebSocket = Faye.extend(Faye.Class(Faye.Transport, {
2352
2564
  },
2353
2565
 
2354
2566
  _createSocket: function() {
2355
- var url = Faye.Transport.WebSocket.getSocketUrl(this.endpoint),
2356
- options = {headers: Faye.copyObject(this._client.headers), ca: this._client.ca};
2567
+ var url = Faye.Transport.WebSocket.getSocketUrl(this.endpoint),
2568
+ headers = this._dispatcher.headers,
2569
+ extensions = this._dispatcher.wsExtensions,
2570
+ cookie = this._getCookies(),
2571
+ tls = this._dispatcher.tls,
2572
+ options = {extensions: extensions, headers: headers, proxy: this._proxy, tls: tls};
2357
2573
 
2358
- options.headers['Cookie'] = this._getCookies();
2574
+ if (cookie !== '') options.headers['Cookie'] = cookie;
2359
2575
 
2360
2576
  if (Faye.WebSocket) return new Faye.WebSocket.Client(url, [], options);
2361
2577
  if (Faye.ENV.MozWebSocket) return new MozWebSocket(url);
@@ -2365,7 +2581,7 @@ Faye.Transport.WebSocket = Faye.extend(Faye.Class(Faye.Transport, {
2365
2581
  _ping: function() {
2366
2582
  if (!this._socket) return;
2367
2583
  this._socket.send('[]');
2368
- this.addTimeout('ping', this._client._advice.timeout/2000, this._ping, this);
2584
+ this.addTimeout('ping', this._dispatcher.timeout / 2, this._ping, this);
2369
2585
  }
2370
2586
 
2371
2587
  }), {
@@ -2374,9 +2590,9 @@ Faye.Transport.WebSocket = Faye.extend(Faye.Class(Faye.Transport, {
2374
2590
  'https:': 'wss:'
2375
2591
  },
2376
2592
 
2377
- create: function(client, endpoint) {
2378
- var sockets = client.transports.websocket = client.transports.websocket || {};
2379
- sockets[endpoint.href] = sockets[endpoint.href] || new this(client, endpoint);
2593
+ create: function(dispatcher, endpoint) {
2594
+ var sockets = dispatcher.transports.websocket = dispatcher.transports.websocket || {};
2595
+ sockets[endpoint.href] = sockets[endpoint.href] || new this(dispatcher, endpoint);
2380
2596
  return sockets[endpoint.href];
2381
2597
  },
2382
2598
 
@@ -2386,92 +2602,140 @@ Faye.Transport.WebSocket = Faye.extend(Faye.Class(Faye.Transport, {
2386
2602
  return Faye.URI.stringify(endpoint);
2387
2603
  },
2388
2604
 
2389
- isUsable: function(client, endpoint, callback, context) {
2390
- this.create(client, endpoint).isUsable(callback, context);
2605
+ isUsable: function(dispatcher, endpoint, callback, context) {
2606
+ this.create(dispatcher, endpoint).isUsable(callback, context);
2391
2607
  }
2392
2608
  });
2393
2609
 
2394
2610
  Faye.extend(Faye.Transport.WebSocket.prototype, Faye.Deferrable);
2395
2611
  Faye.Transport.register('websocket', Faye.Transport.WebSocket);
2396
2612
 
2397
- if (Faye.Event)
2613
+ if (Faye.Event && Faye.ENV.onbeforeunload !== undefined)
2398
2614
  Faye.Event.on(Faye.ENV, 'beforeunload', function() {
2399
2615
  Faye.Transport.WebSocket._unloaded = true;
2400
2616
  });
2401
2617
 
2402
2618
  Faye.Transport.NodeHttp = Faye.extend(Faye.Class(Faye.Transport, {
2403
- encode: function(envelopes) {
2404
- var messages = Faye.map(envelopes, function(e) { return e.message });
2619
+ initialize: function() {
2620
+ Faye.Transport.prototype.initialize.apply(this, arguments);
2621
+
2622
+ this._endpointSecure = (this.SECURE_PROTOCOLS.indexOf(this.endpoint.protocol) >= 0);
2623
+ this._httpClient = this._endpointSecure ? https : http;
2624
+
2625
+ var proxy = this._proxy;
2626
+ if (!proxy.origin) return;
2627
+
2628
+ this._proxyUri = url.parse(proxy.origin);
2629
+ this._proxySecure = (this.SECURE_PROTOCOLS.indexOf(this._proxyUri.protocol) >= 0);
2630
+
2631
+ if (!this._endpointSecure) {
2632
+ this._httpClient = this._proxySecure ? https : http;
2633
+ return;
2634
+ }
2635
+
2636
+ var options = Faye.extend({
2637
+ proxy: {
2638
+ host: this._proxyUri.hostname,
2639
+ port: this._proxyUri.port || this.DEFAULT_PORTS[this._proxyUri.protocol],
2640
+ proxyAuth: this._proxyUri.auth,
2641
+ headers: Faye.extend({host: this.endpoint.host}, proxy.headers)
2642
+ }
2643
+ }, this._dispatcher.tls);
2644
+
2645
+ if (this._proxySecure) {
2646
+ Faye.extend(options.proxy, proxy.tls);
2647
+ this._tunnel = tunnel.httpsOverHttps(options);
2648
+ } else {
2649
+ this._tunnel = tunnel.httpsOverHttp(options);
2650
+ }
2651
+ },
2652
+
2653
+ encode: function(messages) {
2405
2654
  return Faye.toJSON(messages);
2406
2655
  },
2407
2656
 
2408
- request: function(envelopes) {
2409
- var uri = this.endpoint,
2410
- secure = (uri.protocol === 'https:'),
2411
- client = secure ? https : http,
2412
- content = new Buffer(this.encode(envelopes), 'utf8'),
2657
+ request: function(messages) {
2658
+ var content = new Buffer(this.encode(messages), 'utf8'),
2659
+ params = this._buildParams(content),
2660
+ request = this._httpClient.request(params),
2413
2661
  self = this;
2414
2662
 
2415
- var params = this._buildParams(uri, content, secure),
2416
- request = client.request(params);
2417
-
2418
2663
  request.on('response', function(response) {
2419
- self._handleResponse(response, envelopes);
2664
+ self._handleResponse(messages, response);
2420
2665
  self._storeCookies(response.headers['set-cookie']);
2421
2666
  });
2422
2667
 
2423
- request.on('error', function() {
2424
- self.handleError(envelopes);
2668
+ request.on('error', function(error) {
2669
+ self._handleError(messages);
2425
2670
  });
2671
+
2426
2672
  request.end(content);
2673
+ return request;
2427
2674
  },
2428
2675
 
2429
- _buildParams: function(uri, content, secure) {
2676
+ _buildParams: function(content) {
2677
+ var uri = this.endpoint,
2678
+ proxy = this._proxyUri,
2679
+ target = this._tunnel ? uri : (proxy || uri);
2680
+
2430
2681
  var params = {
2431
2682
  method: 'POST',
2432
- host: uri.hostname,
2433
- port: uri.port || (secure ? 443 : 80),
2683
+ host: target.hostname,
2684
+ port: target.port || this.DEFAULT_PORTS[target.protocol],
2434
2685
  path: uri.path,
2435
2686
  headers: Faye.extend({
2436
2687
  'Content-Length': content.length,
2437
2688
  'Content-Type': 'application/json',
2438
- 'Cookie': this._getCookies(),
2439
2689
  'Host': uri.host
2440
- }, this._client.headers)
2690
+ }, this._dispatcher.headers)
2441
2691
  };
2442
- if (this._client.ca) params.ca = this._client.ca;
2692
+
2693
+ var cookie = this._getCookies();
2694
+ if (cookie !== '') params.headers['Cookie'] = cookie;
2695
+
2696
+ if (this._tunnel) {
2697
+ params.agent = this._tunnel;
2698
+ } else if (this._endpointSecure) {
2699
+ Faye.extend(params, this._dispatcher.tls);
2700
+ } else if (proxy) {
2701
+ params.path = this.endpoint.href;
2702
+ Faye.extend(params, this._proxy.tls);
2703
+ if (proxy.auth)
2704
+ params.headers['Proxy-Authorization'] = new Buffer(proxy.auth, 'utf8').toString('base64');
2705
+ }
2706
+
2443
2707
  return params;
2444
2708
  },
2445
2709
 
2446
- _handleResponse: function(response, envelopes) {
2447
- var message = null,
2710
+ _handleResponse: function(messages, response) {
2711
+ var replies = null,
2448
2712
  body = '',
2449
2713
  self = this;
2450
2714
 
2451
2715
  response.setEncoding('utf8');
2452
2716
  response.on('data', function(chunk) { body += chunk });
2717
+
2453
2718
  response.on('end', function() {
2454
2719
  try {
2455
- message = JSON.parse(body);
2720
+ replies = JSON.parse(body);
2456
2721
  } catch (e) {}
2457
2722
 
2458
- if (message)
2459
- self.receive(envelopes, message);
2723
+ if (replies)
2724
+ self._receive(replies);
2460
2725
  else
2461
- self.handleError(envelopes);
2726
+ self._handleError(messages);
2462
2727
  });
2463
2728
  }
2464
2729
 
2465
2730
  }), {
2466
- isUsable: function(client, endpoint, callback, context) {
2731
+ isUsable: function(dispatcher, endpoint, callback, context) {
2467
2732
  callback.call(context, Faye.URI.isURI(endpoint));
2468
2733
  }
2469
2734
  });
2470
2735
 
2471
2736
  Faye.Transport.register('long-polling', Faye.Transport.NodeHttp);
2472
2737
 
2473
- var concat = require('concat-stream'),
2474
- crypto = require('crypto'),
2738
+ var crypto = require('crypto'),
2475
2739
  fs = require('fs'),
2476
2740
  http = require('http'),
2477
2741
  https = require('https'),
@@ -2481,11 +2745,12 @@ var concat = require('concat-stream'),
2481
2745
  url = require('url'),
2482
2746
  querystring = require('querystring'),
2483
2747
 
2484
- csprng = require('csprng');
2748
+ csprng = require('csprng'),
2749
+ tunnel = require('tunnel-agent');
2485
2750
 
2486
2751
  Faye.WebSocket = require('faye-websocket');
2487
2752
  Faye.EventSource = Faye.WebSocket.EventSource;
2488
- Faye.CookieJar = require('cookiejar').CookieJar;
2753
+ Faye.Cookies = require('tough-cookie');
2489
2754
 
2490
2755
  Faye.NodeAdapter = Faye.Class({
2491
2756
  DEFAULT_ENDPOINT: '/bayeux',
@@ -2498,7 +2763,10 @@ Faye.NodeAdapter = Faye.Class({
2498
2763
  VALID_JSONP_CALLBACK: /^[a-z_\$][a-z0-9_\$]*(\.[a-z_\$][a-z0-9_\$]*)*$/i,
2499
2764
 
2500
2765
  initialize: function(options) {
2501
- this._options = options || {};
2766
+ this._options = options || {};
2767
+ Faye.WebSocket.validateOptions(this._options, ['engine', 'mount', 'ping', 'timeout', 'extensions', 'websocketExtensions']);
2768
+
2769
+ this._extensions = [];
2502
2770
  this._endpoint = this._options.mount || this.DEFAULT_ENDPOINT;
2503
2771
  this._endpointRe = new RegExp('^' + this._endpoint.replace(/\/$/, '') + '(/[^/]*)*(\\.[^\\.]+)?$');
2504
2772
  this._server = new Faye.Server(this._options);
@@ -2507,12 +2775,21 @@ Faye.NodeAdapter = Faye.Class({
2507
2775
  this._static.map(path.basename(this._endpoint) + '.js', this.SCRIPT_PATH);
2508
2776
  this._static.map('client.js', this.SCRIPT_PATH);
2509
2777
 
2510
- var extensions = this._options.extensions;
2511
- if (!extensions) return;
2778
+ var extensions = this._options.extensions,
2779
+ websocketExtensions = this._options.websocketExtensions,
2780
+ i, n;
2781
+
2782
+ if (extensions) {
2783
+ extensions = [].concat(extensions);
2784
+ for (i = 0, n = extensions.length; i < n; i++)
2785
+ this.addExtension(extensions[i]);
2786
+ }
2512
2787
 
2513
- extensions = [].concat(extensions);
2514
- for (var i = 0, n = extensions.length; i < n; i++)
2515
- this.addExtension(extensions[i]);
2788
+ if (websocketExtensions) {
2789
+ websocketExtensions = [].concat(websocketExtensions);
2790
+ for (i = 0, n = websocketExtensions.length; i < n; i++)
2791
+ this.addWebsocketExtension(websocketExtensions[i]);
2792
+ }
2516
2793
  },
2517
2794
 
2518
2795
  listen: function() {
@@ -2527,6 +2804,10 @@ Faye.NodeAdapter = Faye.Class({
2527
2804
  return this._server.removeExtension(extension);
2528
2805
  },
2529
2806
 
2807
+ addWebsocketExtension: function(extension) {
2808
+ this._extensions.push(extension);
2809
+ },
2810
+
2530
2811
  close: function() {
2531
2812
  return this._server.close();
2532
2813
  },
@@ -2562,7 +2843,6 @@ Faye.NodeAdapter = Faye.Class({
2562
2843
  handle: function(request, response) {
2563
2844
  var requestUrl = url.parse(request.url, true),
2564
2845
  requestMethod = request.method,
2565
- origin = request.headers.origin,
2566
2846
  self = this;
2567
2847
 
2568
2848
  request.originalUrl = request.url;
@@ -2584,17 +2864,15 @@ Faye.NodeAdapter = Faye.Class({
2584
2864
  return this._callWithParams(request, response, requestUrl.query);
2585
2865
 
2586
2866
  if (requestMethod === 'POST')
2587
- return request.pipe(concat(function(data) {
2588
- data = data.toString('utf8');
2589
-
2867
+ return this._concatStream(request, function(data) {
2590
2868
  var type = (request.headers['content-type'] || '').split(';')[0],
2591
2869
  params = (type === 'application/json')
2592
2870
  ? {message: data}
2593
2871
  : querystring.parse(data);
2594
2872
 
2595
2873
  request.body = data;
2596
- self._callWithParams(request, response, params);
2597
- }));
2874
+ this._callWithParams(request, response, params);
2875
+ }, this);
2598
2876
 
2599
2877
  this._returnError(response, {message: 'Unrecognized request type'});
2600
2878
  },
@@ -2645,7 +2923,8 @@ Faye.NodeAdapter = Faye.Class({
2645
2923
  },
2646
2924
 
2647
2925
  handleUpgrade: function(request, socket, head) {
2648
- var ws = new Faye.WebSocket(request, socket, head, null, {ping: this._options.ping}),
2926
+ var options = {extensions: this._extensions, ping: this._options.ping},
2927
+ ws = new Faye.WebSocket(request, socket, head, [], options),
2649
2928
  clientId = null,
2650
2929
  self = this;
2651
2930
 
@@ -2658,9 +2937,9 @@ Faye.NodeAdapter = Faye.Class({
2658
2937
  var message = JSON.parse(event.data),
2659
2938
  cid = Faye.clientIdFromMessages(message);
2660
2939
 
2661
- if (clientId && cid && cid !== clientId) self._server.closeSocket(clientId);
2940
+ if (clientId && cid && cid !== clientId) self._server.closeSocket(clientId, false);
2662
2941
  self._server.openSocket(cid, ws, request);
2663
- clientId = cid;
2942
+ if (cid) clientId = cid;
2664
2943
 
2665
2944
  self._server.process(message, request, function(replies) {
2666
2945
  if (ws) ws.send(Faye.toJSON(replies));
@@ -2693,15 +2972,37 @@ Faye.NodeAdapter = Faye.Class({
2693
2972
  _handleOptions: function(response) {
2694
2973
  var headers = {
2695
2974
  'Access-Control-Allow-Credentials': 'false',
2696
- 'Access-Control-Allow-Headers': 'Accept, Content-Type, Pragma, X-Requested-With',
2697
- 'Access-Control-Allow-Methods': 'POST, GET, PUT, DELETE, OPTIONS',
2975
+ 'Access-Control-Allow-Headers': 'Accept, Authorization, Content-Type, Pragma, X-Requested-With',
2976
+ 'Access-Control-Allow-Methods': 'POST, GET',
2698
2977
  'Access-Control-Allow-Origin': '*',
2699
2978
  'Access-Control-Max-Age': '86400'
2700
2979
  };
2980
+
2701
2981
  response.writeHead(200, headers);
2702
2982
  response.end('');
2703
2983
  },
2704
2984
 
2985
+ _concatStream: function(stream, callback, context) {
2986
+ var chunks = [],
2987
+ length = 0;
2988
+
2989
+ stream.on('data', function(chunk) {
2990
+ chunks.push(chunk);
2991
+ length += chunk.length;
2992
+ });
2993
+
2994
+ stream.on('end', function() {
2995
+ var buffer = new Buffer(length),
2996
+ offset = 0;
2997
+
2998
+ for (var i = 0, n = chunks.length; i < n; i++) {
2999
+ chunks[i].copy(buffer, offset);
3000
+ offset += chunks[i].length;
3001
+ }
3002
+ callback.call(context, buffer.toString('utf8'));
3003
+ });
3004
+ },
3005
+
2705
3006
  _formatRequest: function(request) {
2706
3007
  var method = request.method.toUpperCase(),
2707
3008
  string = 'curl -X ' + method;