fix websocket unpacking (#3301)

This commit is contained in:
Gus Caplan
2019-05-27 12:13:25 -05:00
committed by Amish Shah
parent db56e0cbae
commit 065908956b
2 changed files with 13 additions and 7 deletions

View File

@@ -6,9 +6,13 @@ try {
if (!erlpack.pack) erlpack = null;
} catch (err) {} // eslint-disable-line no-empty
let TextDecoder;
if (browser) {
TextDecoder = window.TextDecoder; // eslint-disable-line no-undef
exports.WebSocket = window.WebSocket; // eslint-disable-line no-undef
} else {
TextDecoder = require('util').TextDecoder;
try {
exports.WebSocket = require('@discordjs/uws');
} catch (err) {
@@ -16,12 +20,19 @@ if (browser) {
}
}
const ab = new TextDecoder();
exports.encoding = erlpack ? 'etf' : 'json';
exports.pack = erlpack ? erlpack.pack : JSON.stringify;
exports.unpack = data => {
if (!erlpack || data[0] === '{') return JSON.parse(data);
if (exports.encoding === 'json') {
if (typeof data !== 'string') {
data = ab.decode(data);
}
return JSON.parse(data);
}
if (!Buffer.isBuffer(data)) data = Buffer.from(new Uint8Array(data));
return erlpack.unpack(data);
};