Code coverage report for sockjs-client/lib/sockjs.js

Statements: 81.16% (112 / 138)      Branches: 65.12% (56 / 86)      Functions: 93.75% (15 / 16)      Lines: 81.02% (111 / 137)      Ignored: none     

All files » sockjs-client/lib/ » sockjs.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                  1   1 1   1 1 1 1 1 1   1   1   1 30 15       15 15   15 15 15     15 12   3     15 15 15   15 15 13   13   13 13   2         1   1 4     1 11 11       1 11 11       11 11               1 69     69         1             1 28   28 2     2     26 11 11     26 11 11                 15           15   15     1 81     81   11 11   69 69 69   69           1 1 1             1 11           11 11               11       11         11 11   11       11     11 11 11   11 11 11 11 11         1 12           12     12 12 12     1 69           69 69   69     1 13   13 13       13     13 13     1 15    
'use strict';
/*
 * ***** BEGIN LICENSE BLOCK *****
 * Copyright (c) 2011-2012 VMware, Inc.
 *
 * For the license see COPYING.
 * ***** END LICENSE BLOCK *****
 */
 
var inherits = require('util').inherits;
 
var assign = require('lodash.assign');
var contains = require('lodash.contains');
 
var helpers = require('./helpers.js');
var REventTarget = require('./reventtarget.js');
var SimpleEvent = require('./simpleevent.js');
var InfoReceiver = require('./info-receiver.js');
var jsonParse = require('./safe-json-parse.js');
var protocols = require('./protocols.js');
 
module.exports = SockJS;
 
inherits(SockJS, REventTarget);
 
function SockJS(url, _reserved, options) {
    if (!(this instanceof SockJS)) {
        return new SockJS(url, _reserved, options);
    }
 
    // options should default to empty
    this._options = options = options || {};
    this._base_url = helpers.amendUrl(url);
 
    this._server = 'server' in options ? options.server : helpers.random_number_string(1000);
    this._devel = 'devel' in options ? options.devel : false;
    this._debug = 'debug' in options ? options.debug : false;
 
    // only allow whitelist if it is valid
    if (options.protocols_whitelist && options.protocols_whitelist.length) {
        this._protocols_whitelist = Array.isArray(options.protocols_whitelist) ? options.protocols_whitelist : [options.protocols_whitelist];
    } else {
        this._protocols_whitelist = [];
    }
 
    this._protocols = [];
    this.protocol = null;
    this.readyState = SockJS.CONNECTING;
 
    createInfoReceiver(this._base_url).on('finish', function (info, rtt) {
        if (info) {
            Eif (this._options.info) {
                // Override if user supplies the option
                info = assign(info, this._options.info);
            }
            this._applyInfo(info, rtt, this._protocols_whitelist);
            this._didClose();
        } else {
            this._didClose(1002, 'Can\'t connect to server', true);
        }
    }.bind(this));
}
 
SockJS.version = require('../package.json').version;
 
'CONNECTING OPEN CLOSING CLOSED'.split(' ').forEach(function (name, i) {
    SockJS.prototype[name] = SockJS[name] = i;
});
 
SockJS.prototype._log = function () {
    Eif (this._debug) {
        helpers.log.apply(helpers, arguments);
    }
};
 
SockJS.prototype._dispatchOpen = function () {
    Eif (this.readyState === SockJS.CONNECTING) {
        Iif (this._transport_tref) {
            clearTimeout(this._transport_tref);
            this._transport_tref = null;
        }
        this.readyState = SockJS.OPEN;
        this.dispatchEvent(new SimpleEvent('open'));
    } else {
        // The server might have been restarted, and lost track of our
        // connection.
        this._didClose(1006, 'Server lost session');
    }
};
 
SockJS.prototype._dispatchMessage = function (data) {
    Iif (this.readyState !== SockJS.OPEN) {
        return;
    }
    this.dispatchEvent(new SimpleEvent('message', {
        data: data
    }));
};
 
SockJS.prototype._dispatchHeartbeat = function () {
    if (this.readyState !== SockJS.OPEN){
        return;
    }
    this.dispatchEvent(new SimpleEvent('heartbeat'));
};
 
SockJS.prototype._didClose = function (code, reason, force) {
    var close_event;
 
    if (!contains([ SockJS.CONNECTING, SockJS.OPEN, SockJS.CLOSING ], this.readyState)) {
        this.dispatchEvent(new SimpleEvent('error', {
            name: 'INVALID_STATE_ERR'
        }));
        return;
    }
 
    if (this._transport) {
        this._transport.doCleanup();
        this._transport = null;
    }
 
    if (!helpers.userSetCode(code) && this.readyState === SockJS.CONNECTING && !force) {
        Eif (this._try_next_protocol(close_event)) {
            return;
        }
        close_event = new SimpleEvent('close', {
            code: 2000,
            reason: 'All transports failed',
            wasClean: false,
            last_event: close_event
        });
    } else {
        close_event = new SimpleEvent('close', {
            code: code,
            reason: reason,
            wasClean: helpers.userSetCode(code)
        });
    }
    this.readyState = SockJS.CLOSED;
 
    helpers.delay(function () { this.dispatchEvent(close_event); }.bind(this));
};
 
SockJS.prototype._didMessage = function (data) {
    var type = data.slice(0, 1),
        payload;
 
    switch (type) {
    case 'o':
        this._dispatchOpen();
        break;
    case 'a':
        payload = jsonParse(data.slice(1) || '[]');
        for (var i = 0; i < payload.length; i++) {
            this._dispatchMessage(payload[i]);
        }
        break;
    case 'm':
        payload = jsonParse(data.slice(1) || 'null');
        this._dispatchMessage(payload);
        break;
    case 'c':
        payload = jsonParse(data.slice(1) || '[]');
        this._didClose(payload[0], payload[1]);
        break;
    case 'h':
        this._dispatchHeartbeat();
        break;
    }
};
 
SockJS.prototype._try_next_protocol = function (close_event) {
    var protocol,
        roundTrips,
        connid,
        trans_url,
        to;
 
    var timeoutFunction = function () {
        Iif (this.readyState === SockJS.CONNECTING) {
            // I can't understand how it is possible to run
            // this timer, when the state is CLOSED, but
            // apparently in IE everythin is possible.
            this._didClose(2007, 'Transport timed out');
        }
    }.bind(this);
 
    Iif (this.protocol) {
        this._log('Closed transport:', this.protocol, ''+close_event);
        this.protocol = null;
    }
    Iif (this._transport_tref) {
        clearTimeout(this._transport_tref);
        this._transport_tref = null;
    }
 
    while (true) {
        protocol = this.protocol = this._protocols.shift();
 
        Iif (!protocol) {
            return false;
        }
 
        Iif (!protocols[protocol] || !protocols[protocol].enabled(this._base_url)) {
            this._log('Skipping transport:', protocol);
        } else {
            roundTrips = protocols[protocol].roundTrips || 1;
            to = ((this._rto || 0) * roundTrips) || 5000;
            this._transport_tref = helpers.delay(to, timeoutFunction);
 
            connid = helpers.random_string(8);
            trans_url = this._base_url + '/' + this._server + '/' + connid;
            this._log('Opening transport:', protocol, ' url:' + trans_url, ' RTO:' + this._rto);
            this._transport = new protocols[protocol](this, trans_url, this._base_url);
            return true;
        }
    }
};
 
SockJS.prototype.close = function (code, reason) {
    Iif (code && !helpers.userSetCode(code)) {
        this.dispatchEvent(new SimpleEvent('error', {
            name: 'INVALID_ACCESS_ERR'
        }));
        return false;
    }
    Iif (!contains([ SockJS.CONNECTING, SockJS.OPEN ], this.readyState)) {
        return false;
    }
    this.readyState = SockJS.CLOSING;
    this._didClose(code || 1000, reason || 'Normal closure');
    return true;
};
 
SockJS.prototype.send = function (data) {
    Iif (this.readyState === SockJS.CONNECTING) {
        this.dispatchEvent(new SimpleEvent('error', {
            name: 'INVALID_STATE_ERR'
        }));
        return false;
    }
    Eif (this.readyState === SockJS.OPEN) {
        this._transport.doSend(helpers.quote('' + data));
    }
    return true;
};
 
SockJS.prototype._applyInfo = function (info, rtt, protocols_whitelist) {
    var probed;
 
    this._rtt = rtt;
    this._rto = helpers.countRTO(rtt);
 
    // Servers can override base_url, eg to provide a randomized domain name and
    // avoid browser per-domain connection limits.
    Iif (info.base_url) {
        this._base_url = helpers.amendUrl(info.base_url);
    }
    probed = helpers.probeProtocols(this._base_url);
    this._protocols = helpers.detectProtocols(probed, protocols_whitelist, info);
};
 
function createInfoReceiver(base_url) {
    return new InfoReceiver(base_url);
}