avocado-old/packages/net/packet/socket.io-parser.js
2020-06-28 06:39:19 -05:00

145 lines
2.2 KiB
JavaScript

import {compose, deflate, EventEmitter, inflate} from '@avocado/core';
export const types = [
'CONNECT',
'DISCONNECT',
'EVENT',
'ACK',
'ERROR',
'BINARY_EVENT',
'BINARY_ACK'
];
/**
* Packet type `connect`.
*
* @api public
*/
export const CONNECT = 0;
/**
* Packet type `disconnect`.
*
* @api public
*/
export const DISCONNECT = 1;
/**
* Packet type `event`.
*
* @api public
*/
export const EVENT = 2;
/**
* Packet type `ack`.
*
* @api public
*/
export const ACK = 3;
/**
* Packet type `error`.
*
* @api public
*/
export const ERROR = 4;
/**
* Packet type 'binary event'
*
* @api public
*/
export const BINARY_EVENT = 5;
/**
* Packet type `binary ack`. For acks with binary arguments.
*
* @api public
*/
export const BINARY_ACK = 6;
// /**
// * Packet types (see https://github.com/socketio/socket.io-protocol)
// */
// const TYPES = {
// // EVENT: 2,
// BINARY_EVENT: 5,
// };
class Encoder {
encode(packet, callback) {
switch (packet.type) {
case BINARY_ACK:
case BINARY_EVENT:
return callback([this.pack(packet)]);
default:
return callback([JSON.stringify(packet)]);
}
}
pack(packet) {
const {fromId} = require('./packets.scwp');
const packetId = packet.data[0];
const {default: Packet} = fromId(packetId);
return deflate(Packet.pack(packet));
}
}
const decorateDecoder = compose(
EventEmitter,
);
class Decoder extends decorateDecoder(class {}) {
add(obj) {
if (typeof obj === 'string') {
this.parseJSON(obj);
}
else {
this.parseBinary(obj);
}
}
destroy() {}
parseBinary(packet) {
const {fromId} = require('./packets.scwp');
packet = inflate(Buffer.from(packet));
const view = new Uint8Array(packet);
const packetId = view[0];
const {default: Packet} = fromId(packetId);
const unpacked = Packet.unpack(packet);
const {data} = unpacked;
this.emit('decoded', {
type: unpacked.type,
data: [packetId, data],
id: unpacked.id,
nsp: unpacked.nsp,
});
}
parseJSON(obj) {
let decoded;
try {
decoded = JSON.parse(obj);
}
catch (e) {
decoded = errorPacket;
}
this.emit('decoded', decoded);
}
}
export {Decoder, Encoder};