Add stricter/better ESLint config (#589)

* Add stricter/better ESLint config

* Remove more unnecessary @returns
This commit is contained in:
Schuyler Cebulskie
2016-09-03 15:45:23 -04:00
committed by Amish Shah
parent 2682c07bd8
commit 68acf37fd4
33 changed files with 266 additions and 174 deletions

View File

@@ -1,20 +1,133 @@
{ {
"extends": "airbnb", "extends": "eslint:recommended",
"plugins": [ "parserOptions": {
"import", "ecmaVersion": 6
"react", },
"jsx-a11y" "env": {
], "es6": true,
"node": true
},
"rules": { "rules": {
"max-len": [2, 120, 2], "no-extra-parens": ["warn", "all", {
"no-underscore-dangle": 0, "nestedBinaryExpressions": false
"global-require": 0, }],
"guard-for-in": 0, "valid-jsdoc": ["error", {
"no-restricted-syntax": 0, "requireReturn": false,
"no-param-reassign": 0, "requireReturnDescription": false,
"consistent-return": 0, "preferType": {
"import/no-extraneous-dependencies": 0, "String": "string",
"no-continue": 0, "Number": "number",
"no-confusing-arrow" : 0 "Boolean": "boolean",
"Function": "function",
"object": "Object",
"date": "Date",
"error": "Error"
},
"prefer": {
"return": "returns"
}
}],
"accessor-pairs": "warn",
"array-callback-return": "error",
"complexity": "warn",
"consistent-return": "error",
"curly": ["error", "multi-line", "consistent"],
"dot-location": ["error", "property"],
"dot-notation": "error",
"eqeqeq": "error",
"no-empty-function": "error",
"no-floating-decimal": "error",
"no-implied-eval": "error",
"no-invalid-this": "error",
"no-lone-blocks": "error",
"no-multi-spaces": "error",
"no-new-func": "error",
"no-new-wrappers": "error",
"no-new": "error",
"no-octal-escape": "error",
"no-return-assign": "error",
"no-self-compare": "error",
"no-sequences": "error",
"no-throw-literal": "error",
"no-unmodified-loop-condition": "error",
"no-unused-expressions": "error",
"no-useless-call": "error",
"no-useless-concat": "error",
"no-useless-escape": "error",
"no-void": "error",
"no-warning-comments": "warn",
"wrap-iife": "error",
"yoda": "error",
"no-label-var": "error",
"no-shadow": "error",
"no-undef-init": "error",
"callback-return": "error",
"handle-callback-err": "error",
"no-mixed-requires": "error",
"no-new-require": "error",
"no-path-concat": "error",
"no-process-env": "error",
"array-bracket-spacing": "error",
"block-spacing": "error",
"brace-style": ["error", "1tbs", { "allowSingleLine": true }],
"comma-dangle": ["error", "always-multiline"],
"comma-spacing": "error",
"comma-style": "error",
"computed-property-spacing": "error",
"consistent-this": ["error", "$this"],
"eol-last": "error",
"func-names": "error",
"func-style": ["error", "declaration", { "allowArrowFunctions": true }],
"indent": ["error", 2, { "SwitchCase": 1 }],
"key-spacing": "error",
"keyword-spacing": "error",
"max-depth": "error",
"max-len": ["error", 120, 2],
"max-nested-callbacks": ["error", { "max": 4 }],
"max-statements-per-line": ["error", { "max": 2 }],
"new-cap": "error",
"newline-per-chained-call": ["error", { "ignoreChainWithDepth": 3 }],
"no-array-constructor": "error",
"no-inline-comments": "error",
"no-lonely-if": "error",
"no-mixed-operators": "error",
"no-multiple-empty-lines": ["error", { "max": 2, "maxEOF": 1, "maxBOF": 0 }],
"no-new-object": "error",
"no-spaced-func": "error",
"no-trailing-spaces": "error",
"no-unneeded-ternary": "error",
"no-whitespace-before-property": "error",
"object-curly-spacing": ["error", "always"],
"operator-assignment": "error",
"operator-linebreak": ["error", "after"],
"padded-blocks": ["error", "never"],
"quote-props": ["error", "as-needed"],
"quotes": ["error", "single", { "avoidEscape": true, "allowTemplateLiterals": true }],
"semi-spacing": "error",
"semi": "error",
"space-before-blocks": "error",
"space-before-function-paren": ["error", "never"],
"space-in-parens": "error",
"space-infix-ops": "error",
"space-unary-ops": "error",
"spaced-comment": "error",
"unicode-bom": "error",
"arrow-body-style": "error",
"arrow-spacing": "error",
"no-duplicate-imports": "error",
"no-useless-computed-key": "error",
"no-useless-constructor": "error",
"prefer-arrow-callback": "error",
"prefer-rest-params": "error",
"prefer-spread": "error",
"prefer-template": "error",
"rest-spread-spacing": "error",
"template-curly-spacing": "error",
"yield-star-spacing": "error"
} }
} }

View File

@@ -4,5 +4,4 @@ node_js:
cache: cache:
directories: directories:
- node_modules - node_modules
before_install: npm install -g eslint eslint-config-airbnb eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-react install: npm install
install: npm install

View File

@@ -34,11 +34,7 @@
"devDependencies": { "devDependencies": {
"fs-extra": "^0.30.0", "fs-extra": "^0.30.0",
"jsdoc-parse": "^1.2.0", "jsdoc-parse": "^1.2.0",
"eslint": "^3.4.0", "eslint": "^3.4.0"
"eslint-config-airbnb": "^10.0.0",
"eslint-plugin-import": "^1.14.0",
"eslint-plugin-react": "^6.2.0",
"eslint-plugin-jsx-a11y": "^2.2.0"
}, },
"optionalDependencies": { "optionalDependencies": {
"node-opus": "^0.1.13" "node-opus": "^0.1.13"

View File

@@ -117,7 +117,7 @@ class Client extends EventEmitter {
* @param {string} emailOrToken The email or token used for the account. If it is an email, a password _must_ be * @param {string} emailOrToken The email or token used for the account. If it is an email, a password _must_ be
* provided. * provided.
* @param {string} [password] The password for the account, only needed if an email was provided. * @param {string} [password] The password for the account, only needed if an email was provided.
* @return {Promise<string>} * @returns {Promise<string>}
* @example * @example
* // log the client in using a token * // log the client in using a token
* const token = 'my token'; * const token = 'my token';
@@ -128,13 +128,13 @@ class Client extends EventEmitter {
* const password = 'supersecret123'; * const password = 'supersecret123';
* client.login(email, password); * client.login(email, password);
*/ */
login(email, password) { login(emailOrToken, password) {
if (password) { if (password) {
// login with email and password // login with email and password
return this.rest.methods.loginEmailPassword(email, password); return this.rest.methods.loginEmailPassword(emailOrToken, password);
} }
// login with token // login with token
return this.rest.methods.loginToken(email); return this.rest.methods.loginToken(emailOrToken);
} }
/** /**
@@ -174,7 +174,7 @@ class Client extends EventEmitter {
} }
syncGuilds(guilds = this.guilds.array()) { syncGuilds(guilds = this.guilds.array()) {
return this.ws.send({ this.ws.send({
op: 12, op: 12,
d: guilds.map(g => g.id), d: guilds.map(g => g.id),
}); });
@@ -184,7 +184,7 @@ class Client extends EventEmitter {
* Caches a user, or obtains it from the cache if it's already cached. * Caches a user, or obtains it from the cache if it's already cached.
* If the user isn't already cached, it will only be obtainable by OAuth bot accounts. * If the user isn't already cached, it will only be obtainable by OAuth bot accounts.
* @param {string} id The ID of the user to obtain * @param {string} id The ID of the user to obtain
* @return {Promise<User>} * @returns {Promise<User>}
*/ */
fetchUser(id) { fetchUser(id) {
if (this.users.has(id)) return Promise.resolve(this.users.get(id)); if (this.users.has(id)) return Promise.resolve(this.users.get(id));

View File

@@ -20,6 +20,7 @@ class ClientDataResolver {
constructor(client) { constructor(client) {
this.client = client; this.client = client;
} }
/** /**
* Data that resolves to give a User object. This can be: * Data that resolves to give a User object. This can be:
* * A User object * * A User object
@@ -80,15 +81,14 @@ class ClientDataResolver {
* * A User object * * A User object
* @typedef {Guild} GuildMemberResolvable * @typedef {Guild} GuildMemberResolvable
*/ */
/** /**
* Resolves a GuildMemberResolvable to a GuildMember object * Resolves a GuildMemberResolvable to a GuildMember object
* @param {GuildResolvable} guild the guild that the member is part of * @param {GuildResolvable} guild the guild that the member is part of
* @param {UserResolvable} user the user that is part of the guild * @param {UserResolvable} user the user that is part of the guild
* @returns {?GuildMember} * @returns {?GuildMember}
*/ */
resolveGuildMember($guild, $user) { resolveGuildMember(guild, user) {
let guild = $guild;
let user = $user;
if (user instanceof GuildMember) { if (user instanceof GuildMember) {
return user; return user;
} }
@@ -112,7 +112,7 @@ class ClientDataResolver {
/** /**
* Resolves a Base64Resolvable to a Base 64 image * Resolves a Base64Resolvable to a Base 64 image
* @param {Base64Resolvable} dataResolvable the base 64 resolvable you want to resolve * @param {Base64Resolvable} data the base 64 resolvable you want to resolve
* @returns {?string} * @returns {?string}
*/ */
resolveBase64(data) { resolveBase64(data) {
@@ -132,7 +132,7 @@ class ClientDataResolver {
/** /**
* Resolves a ChannelResolvable to a Channel object * Resolves a ChannelResolvable to a Channel object
* @param {ChannelResolvable} channelResolvable the channel resolvable to resolve * @param {ChannelResolvable} channel the channel resolvable to resolve
* @returns {?Channel} * @returns {?Channel}
*/ */
resolveChannel(channel) { resolveChannel(channel) {
@@ -157,7 +157,7 @@ class ClientDataResolver {
/** /**
* Resolves a StringResolvable to a string * Resolves a StringResolvable to a string
* @param {StringResolvable} StringResolvable the string resolvable to resolve * @param {StringResolvable} data the string resolvable to resolve
* @returns {string} * @returns {string}
*/ */
resolveString(data) { resolveString(data) {
@@ -176,13 +176,13 @@ class ClientDataResolver {
* Data that can be resolved to give a Buffer. This can be: * Data that can be resolved to give a Buffer. This can be:
* * A Buffer * * A Buffer
* * The path to a local file * * The path to a local file
* * An URL * * A URL
* @typedef {string|Buffer} FileResolvable * @typedef {string|Buffer} FileResolvable
*/ */
/** /**
* Resolves a FileResolvable to a Buffer * Resolves a FileResolvable to a Buffer
* @param {FileResolvable} fileResolvable the file resolvable to resolve * @param {FileResolvable} resource the file resolvable to resolve
* @returns {string|Buffer} * @returns {string|Buffer}
*/ */
resolveFile(resource) { resolveFile(resource) {
@@ -190,20 +190,18 @@ class ClientDataResolver {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (/^https?:\/\//.test(resource)) { if (/^https?:\/\//.test(resource)) {
request.get(resource) request.get(resource)
.set('Content-Type', 'blob') .set('Content-Type', 'blob')
.end((err, res) => err ? reject(err) : resolve(res.body)); .end((err, res) => err ? reject(err) : resolve(res.body));
} else { } else {
const file = path.resolve(resource); const file = path.resolve(resource);
const stat = fs.statSync(file); const stat = fs.statSync(file);
if (!stat.isFile()) { if (!stat.isFile()) {
return reject(new Error(`The file could not be found: ${file}`)); reject(new Error(`The file could not be found: ${file}`));
return;
} }
fs.readFile(file, (err, data) => { fs.readFile(file, (err, data) => {
if (err) { if (err) reject(err); else resolve(data);
return reject(err);
}
resolve(data);
}); });
} }
}); });

View File

@@ -24,7 +24,6 @@ class ClientManager {
* @param {string} token the authorization token * @param {string} token the authorization token
* @param {function} resolve function to run when connection is successful * @param {function} resolve function to run when connection is successful
* @param {function} reject function to run when connection fails * @param {function} reject function to run when connection fails
* @returns {void}
*/ */
connectToWebSocket(token, resolve, reject) { connectToWebSocket(token, resolve, reject) {
this.client.token = token; this.client.token = token;
@@ -41,7 +40,6 @@ class ClientManager {
/** /**
* Sets up a keep-alive interval to keep the Client's connection valid * Sets up a keep-alive interval to keep the Client's connection valid
* @param {number} time the interval in milliseconds at which heartbeat packets should be sent * @param {number} time the interval in milliseconds at which heartbeat packets should be sent
* @returns {void}
*/ */
setupKeepAlive(time) { setupKeepAlive(time) {
this.heartbeatInterval = this.client.setInterval(() => { this.heartbeatInterval = this.client.setInterval(() => {

View File

@@ -417,9 +417,7 @@ class RESTMethods {
} }
}; };
this.rest.client.on(Constants.Events.GUILD_BAN_REMOVE, listener); this.rest.client.on(Constants.Events.GUILD_BAN_REMOVE, listener);
this.rest.makeRequest('del', `${Constants.Endpoints.guildBans(guild.id)}/${member.id}`, true) this.rest.makeRequest('del', `${Constants.Endpoints.guildBans(guild.id)}/${member.id}`, true).catch(reject);
.then(() => {})
.catch(reject);
}); });
} }

View File

@@ -41,7 +41,7 @@ class RequestHandler {
* Attempts to get this RequestHandler to process its current queue * Attempts to get this RequestHandler to process its current queue
*/ */
handle() { handle() {
return;
} }
} }

View File

@@ -99,12 +99,13 @@ class ClientVoiceManager {
/** /**
* Sets up a request to join a voice channel * Sets up a request to join a voice channel
* @param {VoiceChannel} channel the voice channel to join * @param {VoiceChannel} channel the voice channel to join
* @returns {void} * @returns {Promise<VoiceConnection>}
*/ */
joinChannel(channel) { joinChannel(channel) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
if (this.pending.get(channel.guild.id)) { if (this.pending.get(channel.guild.id)) {
return reject(new Error('already connecting to a channel in this guild')); reject(new Error('already connecting to a channel in this guild'));
return;
} }
const existingConn = this.connections.get(channel.guild.id); const existingConn = this.connections.get(channel.guild.id);
if (existingConn) { if (existingConn) {
@@ -112,7 +113,8 @@ class ClientVoiceManager {
this._sendWSJoin(channel); this._sendWSJoin(channel);
this.connections.get(channel.guild.id).channel = channel; this.connections.get(channel.guild.id).channel = channel;
} }
return resolve(existingConn); resolve(existingConn);
return;
} }
this.pending.set(channel.guild.id, { this.pending.set(channel.guild.id, {
channel, channel,

View File

@@ -65,24 +65,22 @@ class VoiceConnection extends EventEmitter {
/** /**
* Executed whenever an error occurs with the UDP/WebSocket sub-client * Executed whenever an error occurs with the UDP/WebSocket sub-client
* @private * @private
* @param {Error} error * @param {Error} err The error that occurred
* @returns {void}
*/ */
_onError(e) { _onError(err) {
this._reject(e); this._reject(err);
/** /**
* Emitted whenever the connection encounters a fatal error. * Emitted whenever the connection encounters a fatal error.
* @event VoiceConnection#error * @event VoiceConnection#error
* @param {Error} error the encountered error * @param {Error} error the encountered error
*/ */
this.emit('error', e); this.emit('error', err);
this._shutdown(e); this._shutdown(err);
} }
/** /**
* Disconnects the Client from the Voice Channel * Disconnects the Client from the Voice Channel
* @param {string} [reason='user requested'] the reason of the disconnection * @param {string} [reason='user requested'] the reason of the disconnection
* @returns {void}
*/ */
disconnect(reason = 'user requested') { disconnect(reason = 'user requested') {
this.manager.client.ws.send({ this.manager.client.ws.send({
@@ -94,7 +92,7 @@ class VoiceConnection extends EventEmitter {
self_deaf: false, self_deaf: false,
}, },
}); });
return this._shutdown(reason); this._shutdown(reason);
} }
_onClose(e) { _onClose(e) {
@@ -122,7 +120,6 @@ class VoiceConnection extends EventEmitter {
/** /**
* Binds listeners to the WebSocket and UDP sub-clients * Binds listeners to the WebSocket and UDP sub-clients
* @returns {void}
* @private * @private
*/ */
bindListeners() { bindListeners() {
@@ -208,7 +205,7 @@ class VoiceConnection extends EventEmitter {
/** /**
* Play the given file in the voice connection * Play the given file in the voice connection
* @param {string} filepath the path to the file * @param {string} file the path to the file
* @returns {StreamDispatcher} * @returns {StreamDispatcher}
* @example * @example
* // play files natively * // play files natively

View File

@@ -16,7 +16,8 @@ class VoiceConnectionUDPClient extends EventEmitter {
dnsLookup() { dnsLookup() {
dns.lookup(this.voiceConnection.endpoint, (err, address) => { dns.lookup(this.voiceConnection.endpoint, (err, address) => {
if (err) { if (err) {
return this.emit('error', err); this.emit('error', err);
return;
} }
this.connectUDP(address); this.connectUDP(address);
}); });
@@ -27,7 +28,7 @@ class VoiceConnectionUDPClient extends EventEmitter {
try { try {
this.udpSocket.send(packet, 0, packet.length, this.data.port, this.udpIP); this.udpSocket.send(packet, 0, packet.length, this.data.port, this.udpIP);
} catch (err) { } catch (err) {
return this.emit('error', err); this.emit('error', err);
} }
} }
} }

View File

@@ -51,16 +51,18 @@ class VoiceConnectionWebSocket extends EventEmitter {
}); });
} }
_onClose(e) { _onClose(err) {
if (!this.opened && this.attempts >= 0) { if (!this.opened && this.attempts >= 0) {
return this.setupWS(); this.setupWS();
return;
} }
this.emit('close', e); this.emit('close', err);
} }
_onError(e) { _onError(e) {
if (!this.opened && this.attempts >= 0) { if (!this.opened && this.attempts >= 0) {
return this.setupWS(); this.setupWS();
return;
} }
this.emit('error', e); this.emit('error', e);
} }
@@ -83,7 +85,8 @@ class VoiceConnectionWebSocket extends EventEmitter {
try { try {
packet = JSON.parse(event.data); packet = JSON.parse(event.data);
} catch (error) { } catch (error) {
return this._onError(error); this._onError(error);
return;
} }
switch (packet.op) { switch (packet.op) {

View File

@@ -62,15 +62,18 @@ class StreamDispatcher extends EventEmitter {
_send() { _send() {
try { try {
if (this._triggered) { if (this._triggered) {
return this._setSpeaking(false); this._setSpeaking(false);
return;
} }
const data = this.streamingData; const data = this.streamingData;
if (data.missed >= 5) { if (data.missed >= 5) {
return this._triggerTerminalState('error', new Error('stream is not generating fast enough')); this._triggerTerminalState('error', new Error('stream is not generating fast enough'));
return;
} }
if (this.paused) { if (this.paused) {
data.timestamp = (data.timestamp + 4294967295) ? data.timestamp + 960 : 0; data.timestamp = data.timestamp + 4294967295 ? data.timestamp + 960 : 0;
return this.player.connection.manager.client.setTimeout(() => this._send(), data.length * 10); this.player.connection.manager.client.setTimeout(() => this._send(), data.length * 10);
return;
} }
const bufferLength = 1920 * data.channels; const bufferLength = 1920 * data.channels;
this._setSpeaking(true); this._setSpeaking(true);
@@ -78,7 +81,8 @@ class StreamDispatcher extends EventEmitter {
if (!buffer) { if (!buffer) {
data.missed++; data.missed++;
return this.player.connection.manager.client.setTimeout(() => this._send(), data.length * 10); this.player.connection.manager.client.setTimeout(() => this._send(), data.length * 10);
return;
} }
data.missed = 0; data.missed = 0;
@@ -91,7 +95,7 @@ class StreamDispatcher extends EventEmitter {
data.count++; data.count++;
data.sequence = (data.sequence + 1) < (65536) ? data.sequence + 1 : 0; data.sequence = (data.sequence + 1) < (65536) ? data.sequence + 1 : 0;
data.timestamp = (data.timestamp + 4294967295) ? data.timestamp + 960 : 0; data.timestamp = data.timestamp + 4294967295 ? data.timestamp + 960 : 0;
this._sendBuffer(buffer, data.sequence, data.timestamp); this._sendBuffer(buffer, data.sequence, data.timestamp);
@@ -114,14 +118,14 @@ class StreamDispatcher extends EventEmitter {
/** /**
* Emitted once the stream has encountered an error. Attach a `once` listener to this. Also emits `end`. * Emitted once the stream has encountered an error. Attach a `once` listener to this. Also emits `end`.
* @event StreamDispatcher#error * @event StreamDispatcher#error
* @param {Error} error the error encountered * @param {Error} err the error encountered
*/ */
_triggerError(e) { _triggerError(err) {
this.emit('end'); this.emit('end');
this.emit('error', e); this.emit('error', err);
} }
_triggerTerminalState(state, e) { _triggerTerminalState(state, err) {
if (this._triggered) { if (this._triggered) {
return; return;
} }
@@ -136,10 +140,10 @@ class StreamDispatcher extends EventEmitter {
this._setSpeaking(false); this._setSpeaking(false);
switch (state) { switch (state) {
case 'end': case 'end':
this._triggerEnd(e); this._triggerEnd(err);
break; break;
case 'error': case 'error':
this._triggerError(e); this._triggerError(err);
break; break;
default: default:
this.emit('error', 'unknown trigger state'); this.emit('error', 'unknown trigger state');
@@ -149,10 +153,11 @@ class StreamDispatcher extends EventEmitter {
_startStreaming() { _startStreaming() {
if (!this.stream) { if (!this.stream) {
return this.emit('error', 'no stream'); this.emit('error', 'no stream');
return;
} }
this.stream.on('end', e => this._triggerTerminalState('end', e)); this.stream.on('end', err => this._triggerTerminalState('end', err));
this.stream.on('error', e => this._triggerTerminalState('error', e)); this.stream.on('error', err => this._triggerTerminalState('error', err));
const data = this.streamingData; const data = this.streamingData;
data.length = 20; data.length = 20;
data.missed = 0; data.missed = 0;
@@ -172,7 +177,6 @@ class StreamDispatcher extends EventEmitter {
/** /**
* Stops the current stream permanently and emits an `end` event. * Stops the current stream permanently and emits an `end` event.
* @returns {void}
*/ */
end() { end() {
this._triggerTerminalState('end', 'user requested'); this._triggerTerminalState('end', 'user requested');
@@ -180,7 +184,6 @@ class StreamDispatcher extends EventEmitter {
/** /**
* Stops sending voice packets to the voice connection (stream may still progress however) * Stops sending voice packets to the voice connection (stream may still progress however)
* @returns {void}
*/ */
pause() { pause() {
this._pause(true); this._pause(true);
@@ -188,7 +191,6 @@ class StreamDispatcher extends EventEmitter {
/** /**
* Resumes sending voice packets to the voice connection (may be further on in the stream than when paused) * Resumes sending voice packets to the voice connection (may be further on in the stream than when paused)
* @returns {void}
*/ */
resume() { resume() {
this._pause(false); this._pause(false);

View File

@@ -11,7 +11,7 @@ function fetch(Encoder) {
try { try {
return new Encoder(); return new Encoder();
} catch (err) { } catch (err) {
return; return null;
} }
} }

View File

@@ -7,6 +7,7 @@ function chooseCommand() {
return cmd; return cmd;
} }
} }
return null;
} }
class FfmpegConverterEngine extends ConverterEngine { class FfmpegConverterEngine extends ConverterEngine {

View File

@@ -70,11 +70,12 @@ class VoiceConnectionPlayer extends EventEmitter {
streams.inputStream.destroy(); streams.inputStream.destroy();
this.emit('debug', 'stream kill part 5/5 pass'); this.emit('debug', 'stream kill part 5/5 pass');
} }
} catch (e) { } catch (err) {
return e; return err;
} }
} }
} }
return null;
} }
setSpeaking(value) { setSpeaking(value) {

View File

@@ -8,6 +8,7 @@ class VoiceReadable extends Readable {
} }
_read() { _read() {
return;
} }
$push(d) { $push(d) {

View File

@@ -91,7 +91,8 @@ class VoiceReceiver extends EventEmitter {
* @event VoiceReceiver#warn * @event VoiceReceiver#warn
* @param {string} message the warning message * @param {string} message the warning message
*/ */
return this.emit('warn', 'failed to decrypt voice packet'); this.emit('warn', 'failed to decrypt voice packet');
return;
} }
data = new Buffer(data); data = new Buffer(data);
/** /**

View File

@@ -49,7 +49,6 @@ class WebSocketManager {
/** /**
* Connects the client to a given gateway * Connects the client to a given gateway
* @param {string} gateway the gateway to connect to * @param {string} gateway the gateway to connect to
* @returns {void}
*/ */
connect(gateway) { connect(gateway) {
this.status = Constants.Status.CONNECTING; this.status = Constants.Status.CONNECTING;
@@ -68,12 +67,13 @@ class WebSocketManager {
/** /**
* Sends a packet to the gateway * Sends a packet to the gateway
* @param {Object} packet An object that can be JSON stringified * @param {Object} data An object that can be JSON stringified
* @returns {void} * @param {boolean} force Whether or not to send the packet immediately
*/ */
send(data, force = false) { send(data, force = false) {
if (force) { if (force) {
return this.ws.send(JSON.stringify(data)); this.ws.send(JSON.stringify(data));
return;
} }
this._queue.push(JSON.stringify(data)); this._queue.push(JSON.stringify(data));
this.doQueue(); this.doQueue();
@@ -89,9 +89,10 @@ class WebSocketManager {
const item = this._queue[0]; const item = this._queue[0];
if (this.ws.readyState === WebSocket.OPEN && item) { if (this.ws.readyState === WebSocket.OPEN && item) {
if (this._remaining === 0) { if (this._remaining === 0) {
return this.client.setTimeout(() => { this.client.setTimeout(() => {
this.doQueue(); this.doQueue();
}, 1000); }, 1000);
return;
} }
this._remaining--; this._remaining--;
this.ws.send(item); this.ws.send(item);
@@ -103,7 +104,6 @@ class WebSocketManager {
/** /**
* Run whenever the gateway connections opens up * Run whenever the gateway connections opens up
* @returns {void}
*/ */
eventOpen() { eventOpen() {
if (this.reconnecting) { if (this.reconnecting) {
@@ -115,7 +115,6 @@ class WebSocketManager {
/** /**
* Sends a gatway resume packet, in cases of unexpected disconnections. * Sends a gatway resume packet, in cases of unexpected disconnections.
* @returns {void}
*/ */
_sendResume() { _sendResume() {
const payload = { const payload = {
@@ -132,7 +131,6 @@ class WebSocketManager {
/** /**
* Sends a new identification packet, in cases of new connections or failed reconnections. * Sends a new identification packet, in cases of new connections or failed reconnections.
* @returns {void}
*/ */
_sendNewIdentify() { _sendNewIdentify() {
this.reconnecting = false; this.reconnecting = false;
@@ -150,7 +148,7 @@ class WebSocketManager {
/** /**
* Run whenever the connection to the gateway is closed, it will try to reconnect the client. * Run whenever the connection to the gateway is closed, it will try to reconnect the client.
* @returns {void} * @param {Object} event the event
*/ */
eventClose(event) { eventClose(event) {
if (event.code === 4004) { if (event.code === 4004) {
@@ -164,12 +162,11 @@ class WebSocketManager {
/** /**
* Run whenever a message is received from the WebSocket. Returns `true` if the message * Run whenever a message is received from the WebSocket. Returns `true` if the message
* was handled properly. * was handled properly.
* @param {Object} data the received websocket data * @param {Object} event the received websocket data
* @returns {boolean} * @returns {boolean}
*/ */
eventMessage($event) { eventMessage(event) {
let packet; let packet;
const event = $event;
try { try {
if (event.binary) { if (event.binary) {
event.data = zlib.inflateSync(event.data).toString(); event.data = zlib.inflateSync(event.data).toString();
@@ -191,15 +188,15 @@ class WebSocketManager {
/** /**
* Run whenever an error occurs with the WebSocket connection. Tries to reconnect * Run whenever an error occurs with the WebSocket connection. Tries to reconnect
* @returns {void} * @param {Error} err the error that occurred
*/ */
eventError(e) { eventError(err) {
/** /**
* Emitted whenever the Client encounters a serious connection error * Emitted whenever the Client encounters a serious connection error
* @event Client#error * @event Client#error
* @param {Error} error the encountered error * @param {Error} error the encountered error
*/ */
this.client.emit('error', e); this.client.emit('error', err);
this.tryReconnect(); this.tryReconnect();
} }
@@ -217,7 +214,6 @@ class WebSocketManager {
/** /**
* Runs on new packets before `READY` to see if the Client is ready yet, if it is prepares * Runs on new packets before `READY` to see if the Client is ready yet, if it is prepares
* the `READY` event. * the `READY` event.
* @returns {void}
*/ */
checkIfReady() { checkIfReady() {
if (this.status !== Constants.Status.READY && this.status !== Constants.Status.NEARLY) { if (this.status !== Constants.Status.READY && this.status !== Constants.Status.NEARLY) {
@@ -229,10 +225,11 @@ class WebSocketManager {
this.status = Constants.Status.NEARLY; this.status = Constants.Status.NEARLY;
if (this.client.options.fetch_all_members) { if (this.client.options.fetch_all_members) {
const promises = this.client.guilds.array().map(g => g.fetchMembers()); const promises = this.client.guilds.array().map(g => g.fetchMembers());
return Promise.all(promises).then(() => this._emitReady()).catch(e => { Promise.all(promises).then(() => this._emitReady()).catch(e => {
this.client.emit('warn', `error on pre-ready guild member fetching - ${e}`); this.client.emit('warn', `error on pre-ready guild member fetching - ${e}`);
this._emitReady(); this._emitReady();
}); });
return;
} }
this._emitReady(); this._emitReady();
} }
@@ -241,7 +238,6 @@ class WebSocketManager {
/** /**
* Tries to reconnect the client, changing the status to Constants.Status.RECONNECTING. * Tries to reconnect the client, changing the status to Constants.Status.RECONNECTING.
* @returns {void}
*/ */
tryReconnect() { tryReconnect() {
this.status = Constants.Status.RECONNECTING; this.status = Constants.Status.RECONNECTING;

View File

@@ -20,7 +20,7 @@ class ChannelPinsUpdate extends AbstractHandler {
const time = new Date(data.last_pin_timestamp); const time = new Date(data.last_pin_timestamp);
if (channel && time) { if (channel && time) {
return client.emit(Constants.Events.CHANNEL_PINS_UPDATE, channel, time); client.emit(Constants.Events.CHANNEL_PINS_UPDATE, channel, time);
} }
} }

View File

@@ -45,14 +45,12 @@ class PresenceUpdateHandler extends AbstractHandler {
data.user.status = data.status || user.status; data.user.status = data.status || user.status;
data.user.game = data.game; data.user.game = data.game;
const same = ( const same = data.user.username === user.username &&
data.user.username === user.username &&
data.user.id === user.id && data.user.id === user.id &&
data.user.discriminator === user.discriminator && data.user.discriminator === user.discriminator &&
data.user.avatar === user.avatar && data.user.avatar === user.avatar &&
data.user.status === user.status && data.user.status === user.status &&
JSON.stringify(data.user.game) === JSON.stringify(user.game) JSON.stringify(data.user.game) === JSON.stringify(user.game);
);
if (!same) { if (!same) {
const oldUser = cloneObject(user); const oldUser = cloneObject(user);

View File

@@ -29,7 +29,7 @@ class ReadyHandler extends AbstractHandler {
this.packetManager.ws.sessionID = data.session_id; this.packetManager.ws.sessionID = data.session_id;
this.packetManager.ws.checkIfReady('abc'); this.packetManager.ws.checkIfReady();
} }
} }

View File

@@ -37,7 +37,7 @@ class Channel {
/** /**
* Deletes the channel * Deletes the channel
* @return {Promise<Channel>} * @returns {Promise<Channel>}
* @example * @example
* // delete the channel * // delete the channel
* channel.delete() * channel.delete()

View File

@@ -53,7 +53,7 @@ class EvaluatedPermissions {
} }
} }
return ((this.permissions & permission) > 0); return (this.permissions & permission) > 0;
} }
} }

View File

@@ -54,13 +54,11 @@ class GroupDMChannel extends Channel {
} }
equals(other) { equals(other) {
const base = ( const base = other &&
other &&
this.id === other.id && this.id === other.id &&
this.name === other.name && this.name === other.name &&
this.icon === other.icon && this.icon === other.icon &&
this.owner.id === other.owner_id this.owner.id === other.owner_id;
);
if (base) { if (base) {
const thisIDs = this.recipients.array().map(r => r.id); const thisIDs = this.recipients.array().map(r => r.id);

View File

@@ -123,10 +123,7 @@ class Guild {
member.nickname = data.nick; member.nickname = data.nick;
} }
const notSame = ( const notSame = member.nickname !== oldMember.nickname && !arraysEqual(member._roles, oldMember._roles);
member.nickname !== oldMember.nickname &&
!arraysEqual(member._roles, oldMember._roles)
);
if (this.client.ws.status === Constants.Status.READY && notSame) { if (this.client.ws.status === Constants.Status.READY && notSame) {
/** /**
@@ -183,28 +180,28 @@ class Guild {
* @param {Guild} guild the guild to compare * @param {Guild} guild the guild to compare
* @returns {boolean} * @returns {boolean}
*/ */
equals(data) { equals(guild) {
let base = let base =
data && guild &&
this.id === data.id && this.id === guild.id &&
this.available === !data.unavailable && this.available === !guild.unavailable &&
this.splash === data.splash && this.splash === guild.splash &&
this.region === data.region && this.region === guild.region &&
this.name === data.name && this.name === guild.name &&
this.memberCount === data.member_count && this.memberCount === guild.member_count &&
this.large === data.large && this.large === guild.large &&
this.icon === data.icon && this.icon === guild.icon &&
arraysEqual(this.features, data.features) && arraysEqual(this.features, guild.features) &&
this.ownerID === data.owner_id && this.ownerID === guild.owner_id &&
this.verificationLevel === data.verification_level && this.verificationLevel === guild.verification_level &&
this.embedEnabled === data.embed_enabled; this.embedEnabled === guild.embed_enabled;
if (base) { if (base) {
if (this.embedChannel) { if (this.embedChannel) {
if (this.embedChannel.id !== data.embed_channel_id) { if (this.embedChannel.id !== guild.embed_channel_id) {
base = false; base = false;
} }
} else if (data.embed_channel_id) { } else if (guild.embed_channel_id) {
base = false; base = false;
} }
} }
@@ -228,8 +225,7 @@ class Guild {
/** /**
* Sets up the Guild * Sets up the Guild
* @param {*} data * @param {*} data the raw data of the guild
* @returns {void}
* @private * @private
*/ */
setup(data) { setup(data) {
@@ -588,7 +584,8 @@ class Guild {
throw new Error('already fetching guild members'); throw new Error('already fetching guild members');
} }
if (this.memberCount === this.members.size) { if (this.memberCount === this.members.size) {
return resolve(this); resolve(this);
return;
} }
this._fetchWaiter = resolve; this._fetchWaiter = resolve;
this.client.ws.send({ this.client.ws.send({
@@ -627,7 +624,6 @@ class Guild {
/** /**
* Syncs this guild (already done automatically every 30 seconds) * Syncs this guild (already done automatically every 30 seconds)
* @returns {void}
*/ */
sync() { sync() {
this.client.syncGuilds([this]); this.client.syncGuilds([this]);

View File

@@ -65,20 +65,18 @@ class GuildChannel extends Channel {
* @param {GuildChannel} channel the channel to compare this channel to * @param {GuildChannel} channel the channel to compare this channel to
* @returns {boolean} * @returns {boolean}
*/ */
equals(other) { equals(channel) {
let base = ( let base = channel &&
other && this.type === channel.type &&
this.type === other.type && this.topic === channel.topic &&
this.topic === other.topic && this.position === channel.position &&
this.position === other.position && this.name === channel.name &&
this.name === other.name && this.id === channel.id;
this.id === other.id
);
if (base) { if (base) {
if (other.permission_overwrites) { if (channel.permission_overwrites) {
const thisIDSet = Array.from(this.permissionOverwrites.keys()); const thisIDSet = Array.from(this.permissionOverwrites.keys());
const otherIDSet = other.permission_overwrites.map(overwrite => overwrite.id); const otherIDSet = channel.permission_overwrites.map(overwrite => overwrite.id);
if (arraysEqual(thisIDSet, otherIDSet)) { if (arraysEqual(thisIDSet, otherIDSet)) {
base = true; base = true;
} else { } else {
@@ -168,7 +166,7 @@ class GuildChannel extends Channel {
/** /**
* Overwrites the permissions for a user or role in this channel. * Overwrites the permissions for a user or role in this channel.
* @param {Role|UserResolvable} userOrRole the user or role to update * @param {Role|UserResolvable} userOrRole the user or role to update
* @param {PermissionOverwriteOptions} config the configuration for the update * @param {PermissionOverwriteOptions} options the configuration for the update
* @returns {Promise<null, Error>} * @returns {Promise<null, Error>}
* @example * @example
* // overwrite permissions for a message author * // overwrite permissions for a message author
@@ -205,11 +203,11 @@ class GuildChannel extends Channel {
for (const perm in options) { for (const perm in options) {
if (options[perm] === true) { if (options[perm] === true) {
payload.allow |= (Constants.PermissionFlags[perm] || 0); payload.allow |= Constants.PermissionFlags[perm] || 0;
payload.deny &= ~(Constants.PermissionFlags[perm] || 0); payload.deny &= ~(Constants.PermissionFlags[perm] || 0);
} else if (options[perm] === false) { } else if (options[perm] === false) {
payload.allow &= ~(Constants.PermissionFlags[perm] || 0); payload.allow &= ~(Constants.PermissionFlags[perm] || 0);
payload.deny |= (Constants.PermissionFlags[perm] || 0); payload.deny |= Constants.PermissionFlags[perm] || 0;
} }
} }

View File

@@ -155,7 +155,7 @@ class Message {
return new Date(this._editedTimestamp); return new Date(this._editedTimestamp);
} }
patch(data) { patch(data) { // eslint-disable-line complexity
if (data.author) { if (data.author) {
this.author = this.client.users.get(data.author.id); this.author = this.client.users.get(data.author.id);
if (this.guild) { if (this.guild) {

View File

@@ -212,7 +212,7 @@ class Role {
} }
} }
return ((this.permissions & permission) > 0); return (this.permissions & permission) > 0;
} }
/** /**
@@ -229,7 +229,7 @@ class Role {
* @readonly * @readonly
*/ */
get hexColor() { get hexColor() {
let col = (this.color).toString(16); let col = this.color.toString(16);
while (col.length < 6) { while (col.length < 6) {
col = `0${col}`; col = `0${col}`;
} }

View File

@@ -80,7 +80,7 @@ class User {
/** /**
* Deletes a DM Channel (if one exists) between the Client and the User. Resolves with the Channel if successful. * Deletes a DM Channel (if one exists) between the Client and the User. Resolves with the Channel if successful.
* @return {Promise<DMChannel>} * @returns {Promise<DMChannel>}
*/ */
deleteDM() { deleteDM() {
return this.client.rest.methods.deleteChannel(this); return this.client.rest.methods.deleteChannel(this);
@@ -93,14 +93,12 @@ class User {
* @returns {boolean} * @returns {boolean}
*/ */
equals(user) { equals(user) {
let base = ( let base = user &&
user &&
this.username === user.username && this.username === user.username &&
this.id === user.id && this.id === user.id &&
this.discriminator === user.discriminator && this.discriminator === user.discriminator &&
this.avatar === user.avatar && this.avatar === user.avatar &&
this.bot === Boolean(user.bot) this.bot === Boolean(user.bot);
);
if (base) { if (base) {
if (user.status) { if (user.status) {

View File

@@ -59,7 +59,6 @@ class VoiceChannel extends GuildChannel {
/** /**
* Leaves this voice channel * Leaves this voice channel
* @returns {void}
* @example * @example
* // leave a voice channel * // leave a voice channel
* voiceChannel.leave(); * voiceChannel.leave();

View File

@@ -55,7 +55,7 @@ class MessageCollector extends EventEmitter {
* @type {boolean} * @type {boolean}
*/ */
this.ended = false; this.ended = false;
this.listener = (message => this.verify(message)); this.listener = message => this.verify(message);
this.channel.client.on('message', this.listener); this.channel.client.on('message', this.listener);
/** /**
* A collection of collected messages, mapped by message ID. * A collection of collected messages, mapped by message ID.
@@ -70,7 +70,7 @@ class MessageCollector extends EventEmitter {
/** /**
* Verifies a message against the filter and options * Verifies a message against the filter and options
* @private * @private
* @param {Message} message * @param {Message} message the message
* @returns {boolean} * @returns {boolean}
*/ */
verify(message) { verify(message) {
@@ -258,7 +258,6 @@ class TextBasedChannel {
/** /**
* Starts a typing indicator in the channel. * Starts a typing indicator in the channel.
* @param {number} [count] The number of times startTyping should be considered to have been called * @param {number} [count] The number of times startTyping should be considered to have been called
* @returns {void}
* @example * @example
* // start typing in a channel * // start typing in a channel
* channel.startTyping(); * channel.startTyping();
@@ -284,7 +283,6 @@ class TextBasedChannel {
* The indicator will only stop if this is called as many times as startTyping(). * The indicator will only stop if this is called as many times as startTyping().
* <info>It can take a few seconds for the Client User to stop typing.</info> * <info>It can take a few seconds for the Client User to stop typing.</info>
* @param {boolean} [force=false] whether or not to force the indicator to stop regardless of call count * @param {boolean} [force=false] whether or not to force the indicator to stop regardless of call count
* @returns {void}
* @example * @example
* // stop typing in a channel * // stop typing in a channel
* channel.stopTyping(); * channel.stopTyping();

View File

@@ -47,7 +47,7 @@ class Collection extends Map {
/** /**
* If the items in this collection have a delete method (e.g. messages), invoke * If the items in this collection have a delete method (e.g. messages), invoke
* the delete method. Returns an array of promises * the delete method. Returns an array of promises
* @return {Array<Promise>} * @returns {Array<Promise>}
*/ */
deleteAll() { deleteAll() {
const returns = []; const returns = [];