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", "rest-spread-spacing": "error",
"template-curly-spacing": "error", "template-curly-spacing": "error",
"yield-star-spacing": "error", "yield-star-spacing": "error",
"no-param-reassign": "error",
"no-restricted-globals": [ "no-restricted-globals": [
"error", "error",

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -121,8 +121,8 @@ class GuildMemberRoleManager extends DataManager {
const newRoles = [...new Set(resolvedRoles.concat(...this.cache.keys()))]; const newRoles = [...new Set(resolvedRoles.concat(...this.cache.keys()))];
return this.set(newRoles, reason); return this.set(newRoles, reason);
} else { } else {
roleOrRoles = this.guild.roles.resolveId(roleOrRoles); const resolvedRoleId = this.guild.roles.resolveId(roleOrRoles);
if (roleOrRoles === null) { if (resolvedRoleId === null) {
throw new DiscordjsTypeError( throw new DiscordjsTypeError(
ErrorCodes.InvalidType, ErrorCodes.InvalidType,
'roles', '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(); const clone = this.member._clone();
clone._roles = [...this.cache.keys(), roleOrRoles]; clone._roles = [...this.cache.keys(), resolvedRoleId];
return clone; return clone;
} }
} }
@@ -160,8 +160,8 @@ class GuildMemberRoleManager extends DataManager {
const newRoles = this.cache.filter(role => !resolvedRoles.includes(role.id)); const newRoles = this.cache.filter(role => !resolvedRoles.includes(role.id));
return this.set(newRoles, reason); return this.set(newRoles, reason);
} else { } else {
roleOrRoles = this.guild.roles.resolveId(roleOrRoles); const resolvedRoleId = this.guild.roles.resolveId(roleOrRoles);
if (roleOrRoles === null) { if (resolvedRoleId === null) {
throw new DiscordjsTypeError( throw new DiscordjsTypeError(
ErrorCodes.InvalidType, ErrorCodes.InvalidType,
'roles', '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 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()]; clone._roles = [...newRoles.keys()];
return clone; return clone;
} }

View File

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

View File

@@ -203,10 +203,10 @@ class MessageManager extends CachedManager {
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async pin(message, reason) { async pin(message, reason) {
message = this.resolveId(message); const messageId = this.resolveId(message);
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable'); 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>} * @returns {Promise<void>}
*/ */
async unpin(message, reason) { async unpin(message, reason) {
message = this.resolveId(message); const messageId = this.resolveId(message);
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable'); 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>} * @returns {Promise<void>}
*/ */
async react(message, emoji) { async react(message, emoji) {
message = this.resolveId(message); const messageId = this.resolveId(message);
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable'); if (!messageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable');
emoji = resolvePartialEmoji(emoji); const resolvedEmoji = resolvePartialEmoji(emoji);
if (!emoji) throw new DiscordjsTypeError(ErrorCodes.EmojiType, 'emoji', 'EmojiIdentifierResolvable'); if (!resolvedEmoji) throw new DiscordjsTypeError(ErrorCodes.EmojiType, 'emoji', 'EmojiIdentifierResolvable');
const emojiId = emoji.id const emojiId = resolvedEmoji.id
? `${emoji.animated ? 'a:' : ''}${emoji.name}:${emoji.id}` ? `${resolvedEmoji.animated ? 'a:' : ''}${resolvedEmoji.name}:${resolvedEmoji.id}`
: encodeURIComponent(emoji.name); : 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>} * @returns {Promise<void>}
*/ */
async delete(message) { async delete(message) {
message = this.resolveId(message); const messageId = this.resolveId(message);
if (!message) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable'); 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>} * @returns {Promise<GuildChannel>}
* @private * @private
*/ */
async upsert(userOrRole, options, overwriteOptions = {}, existing) { async upsert(userOrRole, options, { reason, type } = {}, existing) {
let userOrRoleId = this.channel.guild.roles.resolveId(userOrRole) ?? this.client.users.resolveId(userOrRole); const userOrRoleId = this.channel.guild.roles.resolveId(userOrRole) ?? this.client.users.resolveId(userOrRole);
let { type, reason } = overwriteOptions;
if (typeof type !== 'number') { let resolvedType = type;
userOrRole = this.channel.guild.roles.resolve(userOrRole) ?? this.client.users.resolve(userOrRole); if (typeof resolvedType !== 'number') {
if (!userOrRole) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role'); const resolvedUserOrRole = this.channel.guild.roles.resolve(userOrRole) ?? this.client.users.resolve(userOrRole);
type = userOrRole instanceof Role ? OverwriteType.Role : OverwriteType.Member; 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); const { allow, deny } = PermissionOverwrites.resolveOverwriteOptions(options, existing);
await this.client.rest.put(Routes.channelPermission(this.channel.id, userOrRoleId), { 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, reason,
}); });
return this.channel; return this.channel;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -57,8 +57,8 @@ class BitField {
* @returns {boolean} * @returns {boolean}
*/ */
has(bit) { has(bit) {
bit = this.constructor.resolve(bit); const resolvedBit = this.constructor.resolve(bit);
return (this.bitfield & bit) === 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 } = {}) { function createChannel(client, data, guild, { allowUnknownGuild } = {}) {
let channel; 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) { if ((data.recipients && data.type !== ChannelType.GroupDM) || data.type === ChannelType.DM) {
channel = new (getDMChannel())(client, data); channel = new (getDMChannel())(client, data);
} else if (data.type === ChannelType.GroupDM) { } else if (data.type === ChannelType.GroupDM) {
channel = new (getPartialGroupDMChannel())(client, data); channel = new (getPartialGroupDMChannel())(client, data);
} }
} else { } else if (resolvedGuild || allowUnknownGuild) {
guild ??= client.guilds.cache.get(data.guild_id); switch (data.type) {
case ChannelType.GuildText: {
if (guild || allowUnknownGuild) { channel = new (getTextChannel())(resolvedGuild, data, client);
switch (data.type) { break;
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;
} }
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; return channel;
} }

View File

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