-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathindex.js
More file actions
80 lines (60 loc) · 1.78 KB
/
index.js
File metadata and controls
80 lines (60 loc) · 1.78 KB
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
var Emitter = require('component-emitter');
exports.protocol = 5;
/**
* Packet types (see https://github.com/socketio/socket.io-protocol)
*/
var PacketType = (exports.PacketType = {
CONNECT: 0,
DISCONNECT: 1,
EVENT: 2,
ACK: 3,
CONNECT_ERROR: 4
});
var isInteger = Number.isInteger || function (value) {
return typeof value === 'number' &&
isFinite(value) &&
Math.floor(value) === value;
};
var isString = function (value) { return typeof value === 'string'; };
var isObject = function (value) {
return Object.prototype.toString.call(value) === '[object Object]';
};
function Encoder () {}
Encoder.prototype.encode = function (packet) {
return [ JSON.stringify(packet) ];
};
function Decoder () {}
Emitter(Decoder.prototype);
function isDataValid (decoded) {
switch (decoded.type) {
case PacketType.CONNECT:
return decoded.data === undefined || isObject(decoded.data);
case PacketType.DISCONNECT:
return decoded.data === undefined;
case PacketType.CONNECT_ERROR:
return isObject(decoded.data);
default:
return Array.isArray(decoded.data);
}
}
Decoder.prototype.add = function (obj) {
var decoded = JSON.parse(obj);
var isTypeValid = isInteger(decoded.type) && decoded.type >= PacketType.CONNECT && decoded.type <= PacketType.CONNECT_ERROR;
if (!isTypeValid) {
throw new Error('invalid packet type');
}
if (!isString(decoded.nsp)) {
throw new Error('invalid namespace');
}
if (!isDataValid(decoded)) {
throw new Error('invalid payload');
}
var isAckValid = decoded.id === undefined || isInteger(decoded.id);
if (!isAckValid) {
throw new Error('invalid packet id');
}
this.emit('decoded', decoded);
};
Decoder.prototype.destroy = function () {};
exports.Encoder = Encoder;
exports.Decoder = Decoder;