refactor: remove parameter reassignment (#10715)

* refactor: remove parameter reassignment

* refactor: requested changes

Co-authored-by: Almeida <github@almeidx.dev>

* chore: requested changes

Co-authored-by: Qjuh <Qjuh@users.noreply.github.com>

* chore: requested changes

* refactor: destructure in parameters

Co-authored-by: Almeida <github@almeidx.dev>

* refactor: apply suggested changes

---------

Co-authored-by: Almeida <github@almeidx.dev>
Co-authored-by: Qjuh <Qjuh@users.noreply.github.com>
This commit is contained in:
Danial Raza
2025-02-26 16:31:29 +01:00
committed by GitHub
parent bb6767113f
commit b6fda781c8
21 changed files with 196 additions and 185 deletions

View File

@@ -168,6 +168,7 @@
"rest-spread-spacing": "error",
"template-curly-spacing": "error",
"yield-star-spacing": "error",
"no-param-reassign": "error",
"no-restricted-globals": [
"error",

View File

@@ -49,10 +49,10 @@ class ApplicationEmojiManager extends CachedManager {
* .catch(console.error);
*/
async create({ attachment, name }) {
attachment = await resolveImage(attachment);
if (!attachment) throw new DiscordjsTypeError(ErrorCodes.ReqResourceType);
const image = await resolveImage(attachment);
if (!image) throw new DiscordjsTypeError(ErrorCodes.ReqResourceType);
const body = { image: attachment, name };
const body = { image, name };
const emoji = await this.client.rest.post(Routes.applicationEmojis(this.application.id), { body });
return this._add(emoji);

View File

@@ -53,7 +53,7 @@ class GuildChannelManager extends CachedManager {
get channelCountWithoutThreads() {
return this.cache.reduce((acc, channel) => {
if (ThreadChannelTypes.includes(channel.type)) return acc;
return ++acc;
return acc + 1;
}, 0);
}
@@ -184,9 +184,6 @@ class GuildChannelManager extends CachedManager {
defaultForumLayout,
reason,
}) {
parent &&= this.client.channels.resolveId(parent);
permissionOverwrites &&= permissionOverwrites.map(overwrite => PermissionOverwrites.resolve(overwrite, this.guild));
const data = await this.client.rest.post(Routes.guildChannels(this.guild.id), {
body: {
name,
@@ -195,9 +192,11 @@ class GuildChannelManager extends CachedManager {
nsfw,
bitrate,
user_limit: userLimit,
parent_id: parent,
parent_id: parent && this.client.channels.resolveId(parent),
position,
permission_overwrites: permissionOverwrites,
permission_overwrites: permissionOverwrites?.map(overwrite =>
PermissionOverwrites.resolve(overwrite, this.guild),
),
rate_limit_per_user: rateLimitPerUser,
rtc_region: rtcRegion,
video_quality_mode: videoQualityMode,
@@ -235,18 +234,19 @@ class GuildChannelManager extends CachedManager {
* .catch(console.error)
*/
async createWebhook({ channel, name, avatar, reason }) {
const id = this.resolveId(channel);
if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
const channelId = this.resolveId(channel);
if (!channelId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
const resolvedImage = await resolveImage(avatar);
const resolvedAvatar = await resolveImage(avatar);
const data = await this.client.rest.post(Routes.channelWebhooks(id), {
const data = await this.client.rest.post(Routes.channelWebhooks(channelId), {
body: {
name,
avatar: resolvedImage,
avatar: resolvedAvatar,
},
reason,
});
return new Webhook(this.client, data);
}
@@ -361,13 +361,14 @@ class GuildChannelManager extends CachedManager {
* .catch(console.error);
*/
async setPosition(channel, position, { relative, reason } = {}) {
channel = this.resolve(channel);
if (!channel) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
const resolvedChannel = this.resolve(channel);
if (!resolvedChannel) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable');
const updatedChannels = await setPosition(
channel,
resolvedChannel,
position,
relative,
this.guild._sortedChannels(channel),
this.guild._sortedChannels(resolvedChannel),
this.client,
Routes.guildChannels(this.guild.id),
reason,
@@ -377,7 +378,8 @@ class GuildChannelManager extends CachedManager {
guild_id: this.guild.id,
channels: updatedChannels,
});
return channel;
return resolvedChannel;
}
/**
@@ -459,17 +461,18 @@ class GuildChannelManager extends CachedManager {
* .catch(console.error);
*/
async setPositions(channelPositions) {
channelPositions = channelPositions.map(channelPosition => ({
const resolvedChannelPositions = channelPositions.map(channelPosition => ({
id: this.client.channels.resolveId(channelPosition.channel),
position: channelPosition.position,
lock_permissions: channelPosition.lockPermissions,
parent_id: channelPosition.parent !== undefined ? this.resolveId(channelPosition.parent) : undefined,
}));
await this.client.rest.patch(Routes.guildChannels(this.guild.id), { body: channelPositions });
await this.client.rest.patch(Routes.guildChannels(this.guild.id), { body: resolvedChannelPositions });
return this.client.actions.GuildChannelsPositionUpdate.handle({
guild_id: this.guild.id,
channels: channelPositions,
channels: resolvedChannelPositions,
}).guild;
}

View File

@@ -85,11 +85,12 @@ class GuildEmojiManager extends CachedManager {
if (emoji instanceof ApplicationEmoji) return emoji.identifier;
if (typeof emoji === 'string') {
const res = parseEmoji(emoji);
let identifier = emoji;
if (res?.name.length) {
emoji = `${res.animated ? 'a:' : ''}${res.name}${res.id ? `:${res.id}` : ''}`;
identifier = `${res.animated ? 'a:' : ''}${res.name}${res.id ? `:${res.id}` : ''}`;
}
if (!emoji.includes('%')) return encodeURIComponent(emoji);
return emoji;
if (!identifier.includes('%')) return encodeURIComponent(identifier);
return identifier;
}
return null;
}
@@ -119,10 +120,10 @@ class GuildEmojiManager extends CachedManager {
* .catch(console.error);
*/
async create({ attachment, name, roles, reason }) {
attachment = await resolveImage(attachment);
if (!attachment) throw new DiscordjsTypeError(ErrorCodes.ReqResourceType);
const image = await resolveImage(attachment);
if (!image) throw new DiscordjsTypeError(ErrorCodes.ReqResourceType);
const body = { image: attachment, name };
const body = { image, name };
if (roles) {
if (!Array.isArray(roles) && !(roles instanceof Collection)) {
throw new DiscordjsTypeError(
@@ -222,9 +223,9 @@ class GuildEmojiManager extends CachedManager {
* @returns {Promise<User>}
*/
async fetchAuthor(emoji) {
emoji = this.resolve(emoji);
if (!emoji) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true);
if (emoji.managed) {
const resolvedEmoji = this.resolve(emoji);
if (!resolvedEmoji) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true);
if (resolvedEmoji.managed) {
throw new DiscordjsError(ErrorCodes.EmojiManaged);
}
@@ -234,9 +235,9 @@ class GuildEmojiManager extends CachedManager {
throw new DiscordjsError(ErrorCodes.MissingManageGuildExpressionsPermission, this.guild);
}
const data = await this.client.rest.get(Routes.guildEmoji(this.guild.id, emoji.id));
emoji._patch(data);
return emoji.author;
const data = await this.client.rest.get(Routes.guildEmoji(this.guild.id, resolvedEmoji.id));
resolvedEmoji._patch(data);
return resolvedEmoji.author;
}
}

View File

@@ -40,18 +40,18 @@ class GuildEmojiRoleManager extends DataManager {
* @returns {Promise<GuildEmoji>}
*/
async add(roleOrRoles) {
if (!Array.isArray(roleOrRoles) && !(roleOrRoles instanceof Collection)) roleOrRoles = [roleOrRoles];
const roles = Array.isArray(roleOrRoles) || roleOrRoles instanceof Collection ? roleOrRoles : [roleOrRoles];
const resolvedRoles = [];
for (const role of roleOrRoles.values()) {
const resolvedRole = this.guild.roles.resolveId(role);
if (!resolvedRole) {
const resolvedRoleIds = [];
for (const role of roles.values()) {
const roleId = this.guild.roles.resolveId(role);
if (!roleId) {
throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role);
}
resolvedRoles.push(resolvedRole);
resolvedRoleIds.push(roleId);
}
const newRoles = [...new Set(resolvedRoles.concat(...this.cache.keys()))];
const newRoles = [...new Set(resolvedRoleIds.concat(...this.cache.keys()))];
return this.set(newRoles);
}
@@ -61,10 +61,10 @@ class GuildEmojiRoleManager extends DataManager {
* @returns {Promise<GuildEmoji>}
*/
async remove(roleOrRoles) {
if (!Array.isArray(roleOrRoles) && !(roleOrRoles instanceof Collection)) roleOrRoles = [roleOrRoles];
const roles = Array.isArray(roleOrRoles) || roleOrRoles instanceof Collection ? roleOrRoles : [roleOrRoles];
const resolvedRoleIds = [];
for (const role of roleOrRoles.values()) {
for (const role of roles.values()) {
const roleId = this.guild.roles.resolveId(role);
if (!roleId) {
throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array or Collection', 'roles', role);

View File

@@ -220,14 +220,15 @@ class GuildMemberManager extends CachedManager {
limit = 0,
withPresences: presences,
users,
query,
query: initialQuery,
time = 120e3,
nonce = DiscordSnowflake.generate().toString(),
} = {}) {
}) {
if (nonce.length > 32) throw new DiscordjsRangeError(ErrorCodes.MemberFetchNonceLength);
const query = initialQuery || (!users ? '' : undefined);
return new Promise((resolve, reject) => {
if (!query && !users) query = '';
this.guild.client.ws.send(this.guild.shardId, {
op: GatewayOpcodes.RequestGuildMembers,
d: {

View File

@@ -121,8 +121,8 @@ class GuildMemberRoleManager extends DataManager {
const newRoles = [...new Set(resolvedRoles.concat(...this.cache.keys()))];
return this.set(newRoles, reason);
} else {
roleOrRoles = this.guild.roles.resolveId(roleOrRoles);
if (roleOrRoles === null) {
const resolvedRoleId = this.guild.roles.resolveId(roleOrRoles);
if (resolvedRoleId === null) {
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'roles',
@@ -130,10 +130,10 @@ class GuildMemberRoleManager extends DataManager {
);
}
await this.client.rest.put(Routes.guildMemberRole(this.guild.id, this.member.id, roleOrRoles), { reason });
await this.client.rest.put(Routes.guildMemberRole(this.guild.id, this.member.id, resolvedRoleId), { reason });
const clone = this.member._clone();
clone._roles = [...this.cache.keys(), roleOrRoles];
clone._roles = [...this.cache.keys(), resolvedRoleId];
return clone;
}
}
@@ -160,8 +160,8 @@ class GuildMemberRoleManager extends DataManager {
const newRoles = this.cache.filter(role => !resolvedRoles.includes(role.id));
return this.set(newRoles, reason);
} else {
roleOrRoles = this.guild.roles.resolveId(roleOrRoles);
if (roleOrRoles === null) {
const resolvedRoleId = this.guild.roles.resolveId(roleOrRoles);
if (resolvedRoleId === null) {
throw new DiscordjsTypeError(
ErrorCodes.InvalidType,
'roles',
@@ -169,10 +169,10 @@ class GuildMemberRoleManager extends DataManager {
);
}
await this.client.rest.delete(Routes.guildMemberRole(this.guild.id, this.member.id, roleOrRoles), { reason });
await this.client.rest.delete(Routes.guildMemberRole(this.guild.id, this.member.id, resolvedRoleId), { reason });
const clone = this.member._clone();
const newRoles = this.cache.filter(role => role.id !== roleOrRoles);
const newRoles = this.cache.filter(role => role.id !== resolvedRoleId);
clone._roles = [...newRoles.keys()];
return clone;
}

View File

@@ -59,15 +59,14 @@ class GuildStickerManager extends CachedManager {
*/
async create({ file, name, tags, description, reason } = {}) {
const resolvedFile = await MessagePayload.resolveFile(file);
if (!resolvedFile) throw new DiscordjsTypeError(ErrorCodes.ReqResourceType);
file = { ...resolvedFile, key: 'file' };
resolvedFile.key = 'file';
const body = { name, tags, description: description ?? '' };
const sticker = await this.client.rest.post(Routes.guildStickers(this.guild.id), {
appendToFormData: true,
body,
files: [file],
files: [resolvedFile],
reason,
});
return this.client.actions.GuildStickerCreate.handle(this.guild, sticker).sticker;
@@ -129,10 +128,10 @@ class GuildStickerManager extends CachedManager {
* @returns {Promise<void>}
*/
async delete(sticker, reason) {
sticker = this.resolveId(sticker);
if (!sticker) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
const resolvedStickerId = this.resolveId(sticker);
if (!resolvedStickerId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
await this.client.rest.delete(Routes.guildSticker(this.guild.id, sticker), { reason });
await this.client.rest.delete(Routes.guildSticker(this.guild.id, resolvedStickerId), { reason });
}
/**
@@ -171,11 +170,11 @@ class GuildStickerManager extends CachedManager {
* @returns {Promise<?User>}
*/
async fetchUser(sticker) {
sticker = this.resolve(sticker);
if (!sticker) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
const data = await this.client.rest.get(Routes.guildSticker(this.guild.id, sticker.id));
sticker._patch(data);
return sticker.user;
const resolvedSticker = this.resolve(sticker);
if (!resolvedSticker) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable');
const data = await this.client.rest.get(Routes.guildSticker(this.guild.id, resolvedSticker.id));
resolvedSticker._patch(data);
return resolvedSticker.user;
}
}

View File

@@ -203,10 +203,10 @@ class MessageManager extends CachedManager {
* @returns {Promise<void>}
*/
async pin(message, reason) {
message = this.resolveId(message);
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
const messageId = this.resolveId(message);
if (!messageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
await this.client.rest.put(Routes.channelPin(this.channel.id, message), { reason });
await this.client.rest.put(Routes.channelPin(this.channel.id, messageId), { reason });
}
/**
@@ -216,10 +216,10 @@ class MessageManager extends CachedManager {
* @returns {Promise<void>}
*/
async unpin(message, reason) {
message = this.resolveId(message);
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
const messageId = this.resolveId(message);
if (!messageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
await this.client.rest.delete(Routes.channelPin(this.channel.id, message), { reason });
await this.client.rest.delete(Routes.channelPin(this.channel.id, messageId), { reason });
}
/**
@@ -229,17 +229,17 @@ class MessageManager extends CachedManager {
* @returns {Promise<void>}
*/
async react(message, emoji) {
message = this.resolveId(message);
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
const messageId = this.resolveId(message);
if (!messageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
emoji = resolvePartialEmoji(emoji);
if (!emoji) throw new DiscordjsTypeError(ErrorCodes.EmojiType, 'emoji', 'EmojiIdentifierResolvable');
const resolvedEmoji = resolvePartialEmoji(emoji);
if (!resolvedEmoji) throw new DiscordjsTypeError(ErrorCodes.EmojiType, 'emoji', 'EmojiIdentifierResolvable');
const emojiId = emoji.id
? `${emoji.animated ? 'a:' : ''}${emoji.name}:${emoji.id}`
: encodeURIComponent(emoji.name);
const emojiId = resolvedEmoji.id
? `${resolvedEmoji.animated ? 'a:' : ''}${resolvedEmoji.name}:${resolvedEmoji.id}`
: encodeURIComponent(resolvedEmoji.name);
await this.client.rest.put(Routes.channelMessageOwnReaction(this.channel.id, message, emojiId));
await this.client.rest.put(Routes.channelMessageOwnReaction(this.channel.id, messageId, emojiId));
}
/**
@@ -248,10 +248,10 @@ class MessageManager extends CachedManager {
* @returns {Promise<void>}
*/
async delete(message) {
message = this.resolveId(message);
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
const messageId = this.resolveId(message);
if (!messageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
await this.client.rest.delete(Routes.channelMessage(this.channel.id, message));
await this.client.rest.delete(Routes.channelMessage(this.channel.id, messageId));
}
/**

View File

@@ -91,19 +91,20 @@ class PermissionOverwriteManager extends CachedManager {
* @returns {Promise<GuildChannel>}
* @private
*/
async upsert(userOrRole, options, overwriteOptions = {}, existing) {
let userOrRoleId = this.channel.guild.roles.resolveId(userOrRole) ?? this.client.users.resolveId(userOrRole);
let { type, reason } = overwriteOptions;
if (typeof type !== 'number') {
userOrRole = this.channel.guild.roles.resolve(userOrRole) ?? this.client.users.resolve(userOrRole);
if (!userOrRole) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role');
type = userOrRole instanceof Role ? OverwriteType.Role : OverwriteType.Member;
async upsert(userOrRole, options, { reason, type } = {}, existing) {
const userOrRoleId = this.channel.guild.roles.resolveId(userOrRole) ?? this.client.users.resolveId(userOrRole);
let resolvedType = type;
if (typeof resolvedType !== 'number') {
const resolvedUserOrRole = this.channel.guild.roles.resolve(userOrRole) ?? this.client.users.resolve(userOrRole);
if (!resolvedUserOrRole) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role');
resolvedType = resolvedUserOrRole instanceof Role ? OverwriteType.Role : OverwriteType.Member;
}
const { allow, deny } = PermissionOverwrites.resolveOverwriteOptions(options, existing);
await this.client.rest.put(Routes.channelPermission(this.channel.id, userOrRoleId), {
body: { id: userOrRoleId, type, allow, deny },
body: { id: userOrRoleId, type: resolvedType, allow, deny },
reason,
});
return this.channel;

View File

@@ -186,11 +186,11 @@ class RoleManager extends CachedManager {
* .catch(console.error);
*/
async edit(role, options) {
role = this.resolve(role);
if (!role) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable');
const resolvedRole = this.resolve(role);
if (!resolvedRole) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable');
if (typeof options.position === 'number') {
await this.setPosition(role, options.position, { reason: options.reason });
await this.setPosition(resolvedRole, options.position, { reason: options.reason });
}
let icon = options.icon;
@@ -210,9 +210,12 @@ class RoleManager extends CachedManager {
unicode_emoji: options.unicodeEmoji,
};
const d = await this.client.rest.patch(Routes.guildRole(this.guild.id, role.id), { body, reason: options.reason });
const d = await this.client.rest.patch(Routes.guildRole(this.guild.id, resolvedRole.id), {
body,
reason: options.reason,
});
const clone = role._clone();
const clone = resolvedRole._clone();
clone._patch(d);
return clone;
}
@@ -247,10 +250,10 @@ class RoleManager extends CachedManager {
* .catch(console.error);
*/
async setPosition(role, position, { relative, reason } = {}) {
role = this.resolve(role);
if (!role) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable');
const resolvedRole = this.resolve(role);
if (!resolvedRole) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable');
const updatedRoles = await setPosition(
role,
resolvedRole,
position,
relative,
this.guild._sortedRoles(),
@@ -263,7 +266,7 @@ class RoleManager extends CachedManager {
guild_id: this.guild.id,
roles: updatedRoles,
});
return role;
return resolvedRole;
}
/**
@@ -284,16 +287,16 @@ class RoleManager extends CachedManager {
*/
async setPositions(rolePositions) {
// Make sure rolePositions are prepared for API
rolePositions = rolePositions.map(rolePosition => ({
const resolvedRolePositions = rolePositions.map(rolePosition => ({
id: this.resolveId(rolePosition.role),
position: rolePosition.position,
}));
// Call the API to update role positions
await this.client.rest.patch(Routes.guildRoles(this.guild.id), { body: rolePositions });
await this.client.rest.patch(Routes.guildRoles(this.guild.id), { body: resolvedRolePositions });
return this.client.actions.GuildRolesPositionUpdate.handle({
guild_id: this.guild.id,
roles: rolePositions,
roles: resolvedRolePositions,
}).guild;
}

View File

@@ -134,10 +134,10 @@ class ShardClientUtil {
reject(new DiscordjsTypeError(ErrorCodes.ShardingInvalidEvalBroadcast));
return;
}
script = `(${script})(this, ${JSON.stringify(options.context)})`;
const evalScript = `(${script})(this, ${JSON.stringify(options.context)})`;
const listener = message => {
if (message?._sEval !== script || message._sEvalShard !== options.shard) return;
if (message?._sEval !== evalScript || message._sEvalShard !== options.shard) return;
parent.removeListener('message', listener);
this.decrementMaxListeners(parent);
if (!message._error) resolve(message._result);
@@ -145,7 +145,7 @@ class ShardClientUtil {
};
this.incrementMaxListeners(parent);
parent.on('message', listener);
this.send({ _sEval: script, _sEvalShard: options.shard }).catch(err => {
this.send({ _sEval: evalScript, _sEvalShard: options.shard }).catch(err => {
parent.removeListener('message', listener);
this.decrementMaxListeners(parent);
reject(err);

View File

@@ -191,28 +191,31 @@ class ShardingManager extends AsyncEventEmitter {
*/
async spawn({ amount = this.totalShards, delay = 5500, timeout = 30_000 } = {}) {
// Obtain/verify the number of shards to spawn
if (amount === 'auto') {
amount = await fetchRecommendedShardCount(this.token);
let shardAmount = amount;
if (shardAmount === 'auto') {
shardAmount = await fetchRecommendedShardCount(this.token);
} else {
if (typeof amount !== 'number' || isNaN(amount)) {
if (typeof shardAmount !== 'number' || isNaN(shardAmount)) {
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'a number.');
}
if (amount < 1) throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'at least 1.');
if (!Number.isInteger(amount)) {
if (shardAmount < 1) {
throw new DiscordjsRangeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'at least 1.');
}
if (!Number.isInteger(shardAmount)) {
throw new DiscordjsTypeError(ErrorCodes.ClientInvalidOption, 'Amount of shards', 'an integer.');
}
}
// Make sure this many shards haven't already been spawned
if (this.shards.size >= amount) throw new DiscordjsError(ErrorCodes.ShardingAlreadySpawned, this.shards.size);
if (this.shardList === 'auto' || this.totalShards === 'auto' || this.totalShards !== amount) {
this.shardList = [...Array(amount).keys()];
if (this.shards.size >= shardAmount) throw new DiscordjsError(ErrorCodes.ShardingAlreadySpawned, this.shards.size);
if (this.shardList === 'auto' || this.totalShards === 'auto' || this.totalShards !== shardAmount) {
this.shardList = [...Array(shardAmount).keys()];
}
if (this.totalShards === 'auto' || this.totalShards !== amount) {
this.totalShards = amount;
if (this.totalShards === 'auto' || this.totalShards !== shardAmount) {
this.totalShards = shardAmount;
}
if (this.shardList.some(shardId => shardId >= amount)) {
if (this.shardList.some(shardId => shardId >= shardAmount)) {
throw new DiscordjsRangeError(
ErrorCodes.ClientInvalidOption,
'Amount of shards',

View File

@@ -180,10 +180,10 @@ class GuildChannel extends BaseChannel {
}
overwritesFor(member, verified = false, roles = null) {
if (!verified) member = this.guild.members.resolve(member);
if (!member) return [];
const resolvedMember = verified ? member : this.guild.members.resolve(member);
if (!resolvedMember) return [];
roles ??= member.roles.cache;
const resolvedRoles = roles ?? resolvedMember.roles.cache;
const roleOverwrites = [];
let memberOverwrites;
let everyoneOverwrites;
@@ -191,9 +191,9 @@ class GuildChannel extends BaseChannel {
for (const overwrite of this.permissionOverwrites.cache.values()) {
if (overwrite.id === this.guild.id) {
everyoneOverwrites = overwrite;
} else if (roles.has(overwrite.id)) {
} else if (resolvedRoles.has(overwrite.id)) {
roleOverwrites.push(overwrite);
} else if (overwrite.id === member.id) {
} else if (overwrite.id === resolvedMember.id) {
memberOverwrites = overwrite;
}
}

View File

@@ -346,9 +346,9 @@ class GuildMember extends Base {
* @returns {Readonly<PermissionsBitField>}
*/
permissionsIn(channel) {
channel = this.guild.channels.resolve(channel);
if (!channel) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
return channel.permissionsFor(this);
const resolvedChannel = this.guild.channels.resolve(channel);
if (!resolvedChannel) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
return resolvedChannel.permissionsFor(this);
}
/**

View File

@@ -118,9 +118,9 @@ class PermissionOverwrites extends Base {
* @param {ResolvedOverwriteOptions} initialPermissions The initial permissions
* @returns {ResolvedOverwriteOptions}
*/
static resolveOverwriteOptions(options, { allow, deny } = {}) {
allow = new PermissionsBitField(allow);
deny = new PermissionsBitField(deny);
static resolveOverwriteOptions(options, initialPermissions = {}) {
const allow = new PermissionsBitField(initialPermissions.allow);
const deny = new PermissionsBitField(initialPermissions.deny);
for (const [perm, value] of Object.entries(options)) {
if (value === true) {

View File

@@ -264,9 +264,9 @@ class Role extends Base {
* @returns {Readonly<PermissionsBitField>}
*/
permissionsIn(channel, checkAdmin = true) {
channel = this.guild.channels.resolve(channel);
if (!channel) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
return channel.rolePermissions(this, checkAdmin);
const resolvedChannel = this.guild.channels.resolve(channel);
if (!resolvedChannel) throw new DiscordjsError(ErrorCodes.GuildChannelResolve);
return resolvedChannel.rolePermissions(this, checkAdmin);
}
/**

View File

@@ -275,11 +275,12 @@ class Webhook {
* @param {WebhookEditOptions} options Options for editing the webhook
* @returns {Promise<Webhook>}
*/
async edit({ name = this.name, avatar, channel, reason }) {
async edit({ name = this.name, avatar: newAvatar, channel: newChannel, reason }) {
let avatar = newAvatar;
if (avatar && !(typeof avatar === 'string' && avatar.startsWith('data:'))) {
avatar = await resolveImage(avatar);
}
channel &&= channel.id ?? channel;
const channel = newChannel?.id ?? newChannel;
const data = await this.client.rest.patch(Routes.webhook(this.id, channel ? undefined : this.token), {
body: { name, avatar, channel_id: channel },
reason,

View File

@@ -57,8 +57,8 @@ class BitField {
* @returns {boolean}
*/
has(bit) {
bit = this.constructor.resolve(bit);
return (this.bitfield & bit) === bit;
const resolvedBit = this.constructor.resolve(bit);
return (this.bitfield & resolvedBit) === resolvedBit;
}
/**

View File

@@ -33,56 +33,54 @@ const getMediaChannel = lazy(() => require('../structures/MediaChannel.js').Medi
*/
function createChannel(client, data, guild, { allowUnknownGuild } = {}) {
let channel;
if (!data.guild_id && !guild) {
let resolvedGuild = guild || client.guilds.cache.get(data.guild_id);
if (!data.guild_id && !resolvedGuild) {
if ((data.recipients && data.type !== ChannelType.GroupDM) || data.type === ChannelType.DM) {
channel = new (getDMChannel())(client, data);
} else if (data.type === ChannelType.GroupDM) {
channel = new (getPartialGroupDMChannel())(client, data);
}
} else {
guild ??= client.guilds.cache.get(data.guild_id);
if (guild || allowUnknownGuild) {
switch (data.type) {
case ChannelType.GuildText: {
channel = new (getTextChannel())(guild, data, client);
break;
}
case ChannelType.GuildVoice: {
channel = new (getVoiceChannel())(guild, data, client);
break;
}
case ChannelType.GuildCategory: {
channel = new (getCategoryChannel())(guild, data, client);
break;
}
case ChannelType.GuildAnnouncement: {
channel = new (getAnnouncementChannel())(guild, data, client);
break;
}
case ChannelType.GuildStageVoice: {
channel = new (getStageChannel())(guild, data, client);
break;
}
case ChannelType.AnnouncementThread:
case ChannelType.PublicThread:
case ChannelType.PrivateThread: {
channel = new (getThreadChannel())(guild, data, client);
if (!allowUnknownGuild) channel.parent?.threads.cache.set(channel.id, channel);
break;
}
case ChannelType.GuildDirectory:
channel = new (getDirectoryChannel())(guild, data, client);
break;
case ChannelType.GuildForum:
channel = new (getForumChannel())(guild, data, client);
break;
case ChannelType.GuildMedia:
channel = new (getMediaChannel())(guild, data, client);
break;
} else if (resolvedGuild || allowUnknownGuild) {
switch (data.type) {
case ChannelType.GuildText: {
channel = new (getTextChannel())(resolvedGuild, data, client);
break;
}
if (channel && !allowUnknownGuild) guild.channels?.cache.set(channel.id, channel);
case ChannelType.GuildVoice: {
channel = new (getVoiceChannel())(resolvedGuild, data, client);
break;
}
case ChannelType.GuildCategory: {
channel = new (getCategoryChannel())(resolvedGuild, data, client);
break;
}
case ChannelType.GuildAnnouncement: {
channel = new (getAnnouncementChannel())(resolvedGuild, data, client);
break;
}
case ChannelType.GuildStageVoice: {
channel = new (getStageChannel())(resolvedGuild, data, client);
break;
}
case ChannelType.AnnouncementThread:
case ChannelType.PublicThread:
case ChannelType.PrivateThread: {
channel = new (getThreadChannel())(resolvedGuild, data, client);
if (!allowUnknownGuild) channel.parent?.threads.cache.set(channel.id, channel);
break;
}
case ChannelType.GuildDirectory:
channel = new (getDirectoryChannel())(resolvedGuild, data, client);
break;
case ChannelType.GuildForum:
channel = new (getForumChannel())(resolvedGuild, data, client);
break;
case ChannelType.GuildMedia:
channel = new (getMediaChannel())(resolvedGuild, data, client);
break;
}
if (channel && !allowUnknownGuild) resolvedGuild.channels?.cache.set(channel.id, channel);
}
return channel;
}

View File

@@ -21,11 +21,11 @@ function flatten(obj, ...props) {
.filter(key => !key.startsWith('_'))
.map(key => ({ [key]: true }));
props = objProps.length ? Object.assign(...objProps, ...props) : Object.assign({}, ...props);
const mergedProps = objProps.length ? Object.assign(...objProps, ...props) : Object.assign({}, ...props);
const out = {};
for (let [prop, newProp] of Object.entries(props)) {
for (let [prop, newProp] of Object.entries(mergedProps)) {
if (!newProp) continue;
newProp = newProp === true ? prop : newProp;
@@ -96,9 +96,9 @@ async function fetchRecommendedShardCount(token, { guildsPerShard = 1_000, multi
* @returns {?PartialEmoji}
*/
function parseEmoji(text) {
if (text.includes('%')) text = decodeURIComponent(text);
if (!text.includes(':')) return { animated: false, name: text, id: undefined };
const match = text.match(/<?(?:(a):)?(\w{2,32}):(\d{17,19})?>?/);
const decodedText = text.includes('%') ? decodeURIComponent(text) : text;
if (!decodedText.includes(':')) return { animated: false, name: decodedText, id: undefined };
const match = decodedText.match(/<?(?:(a):)?(\w{2,32}):(\d{17,19})?>?/);
return match && { animated: Boolean(match[1]), name: match[2], id: match[3] };
}
@@ -228,10 +228,10 @@ function getSortableGroupTypes(type) {
*/
function moveElementInArray(array, element, newIndex, offset = false) {
const index = array.indexOf(element);
newIndex = (offset ? index : 0) + newIndex;
if (newIndex > -1 && newIndex < array.length) {
const targetIndex = (offset ? index : 0) + newIndex;
if (targetIndex > -1 && targetIndex < array.length) {
const removedElement = array.splice(index, 1)[0];
array.splice(newIndex, 0, removedElement);
array.splice(targetIndex, 0, removedElement);
}
return array.indexOf(element);
}