From 8dc1692d87624781fe99faba2e1415f0d4bf68d4 Mon Sep 17 00:00:00 2001 From: Vlad Frangu Date: Sun, 5 Oct 2025 16:13:56 +0300 Subject: [PATCH] chore: run format --- apps/guide/src/app/guide/layout.tsx | 4 +- apps/guide/src/components/mdx/mermaid.tsx | 5 +- .../releasePackages/generateReleaseTree.ts | 27 +- .../src/releasePackages/releasePackage.ts | 8 +- .../src/mixins/ApiItemContainerMixin.ts | 9 +- .../src/model/ApiPackage.ts | 21 +- .../src/model/Deserializer.ts | 9 +- .../api-extractor/src/collector/Collector.ts | 9 +- .../src/collector/CollectorEntity.ts | 8 +- .../src/collector/SourceMapper.ts | 12 +- .../brokers/src/brokers/redis/BaseRedis.ts | 8 +- packages/builders/src/util/normalizeArray.ts | 5 +- .../collection/__tests__/collection.test.ts | 4 +- packages/collection/src/collection.ts | 361 ++++++++++++++---- packages/core/src/client.ts | 25 +- .../discord.js/scripts/generateRequires.mjs | 8 +- packages/discord.js/src/client/Client.js | 42 +- .../discord.js/src/client/actions/Action.js | 12 +- .../src/client/actions/ChannelUpdate.js | 4 +- .../actions/GuildChannelsPositionUpdate.js | 4 +- .../src/client/actions/GuildEmojiCreate.js | 5 +- .../src/client/actions/GuildEmojisUpdate.js | 4 +- .../src/client/actions/GuildMemberUpdate.js | 4 +- .../src/client/actions/GuildRoleCreate.js | 4 +- .../actions/GuildRolesPositionUpdate.js | 4 +- .../actions/GuildSoundboardSoundDelete.js | 4 +- .../src/client/actions/GuildStickerCreate.js | 5 +- .../src/client/actions/GuildStickersUpdate.js | 4 +- .../src/client/actions/InteractionCreate.js | 9 +- .../src/client/actions/MessageCreate.js | 9 +- .../src/client/actions/MessageDelete.js | 8 +- .../src/client/actions/MessageDeleteBulk.js | 13 +- .../src/client/actions/MessagePollVoteAdd.js | 16 +- .../client/actions/MessagePollVoteRemove.js | 16 +- .../src/client/actions/MessageReactionAdd.js | 31 +- .../client/actions/MessageReactionRemove.js | 21 +- .../actions/MessageReactionRemoveAll.js | 8 +- .../actions/MessageReactionRemoveEmoji.js | 17 +- .../src/client/actions/MessageUpdate.js | 4 +- .../src/client/actions/ThreadMembersUpdate.js | 5 +- .../src/client/actions/TypingStart.js | 4 +- .../AUTO_MODERATION_ACTION_EXECUTION.js | 4 +- .../handlers/AUTO_MODERATION_RULE_CREATE.js | 4 +- .../handlers/AUTO_MODERATION_RULE_DELETE.js | 8 +- .../handlers/AUTO_MODERATION_RULE_UPDATE.js | 4 +- .../handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js | 4 +- .../websocket/handlers/GUILD_BAN_ADD.js | 4 +- .../websocket/handlers/GUILD_BAN_REMOVE.js | 4 +- .../client/websocket/handlers/GUILD_DELETE.js | 9 +- .../handlers/GUILD_INTEGRATIONS_UPDATE.js | 4 +- .../websocket/handlers/GUILD_MEMBERS_CHUNK.js | 14 +- .../websocket/handlers/GUILD_ROLE_UPDATE.js | 8 +- .../handlers/GUILD_SCHEDULED_EVENT_CREATE.js | 4 +- .../handlers/GUILD_SCHEDULED_EVENT_UPDATE.js | 4 +- .../GUILD_SOUNDBOARD_SOUNDS_UPDATE.js | 4 +- .../handlers/GUILD_SOUNDBOARD_SOUND_CREATE.js | 4 +- .../handlers/GUILD_SOUNDBOARD_SOUND_UPDATE.js | 4 +- .../websocket/handlers/INVITE_CREATE.js | 4 +- .../websocket/handlers/INVITE_DELETE.js | 4 +- .../websocket/handlers/PRESENCE_UPDATE.js | 12 +- .../websocket/handlers/SOUNDBOARD_SOUNDS.js | 4 +- .../websocket/handlers/THREAD_DELETE.js | 4 +- .../websocket/handlers/THREAD_LIST_SYNC.js | 12 +- .../handlers/THREAD_MEMBER_UPDATE.js | 4 +- .../handlers/VOICE_CHANNEL_EFFECT_SEND.js | 4 +- .../websocket/handlers/VOICE_STATE_UPDATE.js | 4 +- .../websocket/handlers/WEBHOOKS_UPDATE.js | 4 +- packages/discord.js/src/errors/DJSError.js | 20 +- .../src/managers/ApplicationCommandManager.js | 28 +- .../ApplicationCommandPermissionsManager.js | 51 ++- .../src/managers/ApplicationEmojiManager.js | 26 +- .../src/managers/AutoModerationRuleManager.js | 9 +- .../discord.js/src/managers/CachedManager.js | 5 +- .../discord.js/src/managers/ChannelManager.js | 17 +- .../discord.js/src/managers/DataManager.js | 20 +- .../src/managers/EntitlementManager.js | 13 +- .../src/managers/GuildBanManager.js | 35 +- .../src/managers/GuildChannelManager.js | 56 ++- .../src/managers/GuildEmojiManager.js | 73 +++- .../src/managers/GuildInviteManager.js | 33 +- .../discord.js/src/managers/GuildManager.js | 8 +- .../src/managers/GuildMemberManager.js | 58 ++- .../src/managers/GuildMemberRoleManager.js | 20 +- .../src/managers/GuildMessageManager.js | 4 +- .../managers/GuildScheduledEventManager.js | 31 +- .../managers/GuildSoundboardSoundManager.js | 32 +- .../src/managers/GuildStickerManager.js | 17 +- .../src/managers/GuildTextThreadManager.js | 4 +- .../discord.js/src/managers/MessageManager.js | 38 +- .../managers/PermissionOverwriteManager.js | 9 +- .../src/managers/PresenceManager.js | 10 +- .../src/managers/ReactionUserManager.js | 5 +- .../discord.js/src/managers/RoleManager.js | 41 +- .../src/managers/StageInstanceManager.js | 31 +- .../src/managers/SubscriptionManager.js | 8 +- .../discord.js/src/managers/ThreadManager.js | 25 +- .../src/managers/ThreadMemberManager.js | 53 ++- .../discord.js/src/managers/UserManager.js | 38 +- .../src/managers/VoiceStateManager.js | 13 +- packages/discord.js/src/sharding/Shard.js | 62 ++- .../src/sharding/ShardClientUtil.js | 46 ++- .../src/sharding/ShardingManager.js | 48 ++- .../src/structures/AnonymousGuild.js | 8 +- .../src/structures/ApplicationCommand.js | 21 +- .../src/structures/ApplicationEmoji.js | 5 +- .../src/structures/AttachmentBuilder.js | 4 +- .../src/structures/AutocompleteInteraction.js | 4 +- .../discord.js/src/structures/BaseChannel.js | 4 +- .../src/structures/BaseGuildEmoji.js | 4 +- .../src/structures/BaseGuildTextChannel.js | 4 +- .../src/structures/BaseGuildVoiceChannel.js | 17 +- .../discord.js/src/structures/ClientUser.js | 8 +- .../src/structures/CommandInteraction.js | 29 +- .../CommandInteractionOptionResolver.js | 5 +- packages/discord.js/src/structures/Embed.js | 25 +- packages/discord.js/src/structures/Emoji.js | 9 +- .../discord.js/src/structures/Entitlement.js | 5 +- packages/discord.js/src/structures/Guild.js | 59 ++- .../src/structures/GuildAuditLogs.js | 14 +- .../src/structures/GuildAuditLogsEntry.js | 90 ++++- .../discord.js/src/structures/GuildChannel.js | 64 +++- .../discord.js/src/structures/GuildEmoji.js | 14 +- .../discord.js/src/structures/GuildInvite.js | 10 +- .../discord.js/src/structures/GuildMember.js | 58 ++- .../structures/GuildOnboardingPromptOption.js | 5 +- .../discord.js/src/structures/GuildPreview.js | 4 +- .../src/structures/GuildScheduledEvent.js | 9 +- .../src/structures/InteractionCollector.js | 67 +++- packages/discord.js/src/structures/Message.js | 115 ++++-- .../src/structures/MessageCollector.js | 19 +- .../src/structures/MessageMentions.js | 62 ++- .../src/structures/MessagePayload.js | 23 +- .../src/structures/MessageReaction.js | 48 ++- .../src/structures/ModalComponentResolver.js | 8 +- .../src/structures/ModalSubmitInteraction.js | 24 +- .../src/structures/PermissionOverwrites.js | 8 +- .../discord.js/src/structures/PollAnswer.js | 5 +- .../discord.js/src/structures/Presence.js | 10 +- .../src/structures/ReactionCollector.js | 31 +- packages/discord.js/src/structures/Role.js | 32 +- .../src/structures/SoundboardSound.js | 12 +- packages/discord.js/src/structures/Sticker.js | 15 +- .../src/structures/ThreadChannel.js | 47 ++- .../discord.js/src/structures/ThreadMember.js | 9 +- packages/discord.js/src/structures/User.js | 5 +- .../discord.js/src/structures/VoiceChannel.js | 14 +- .../discord.js/src/structures/VoiceState.js | 4 +- packages/discord.js/src/structures/Webhook.js | 58 ++- .../src/structures/interfaces/Collector.js | 27 +- .../interfaces/InteractionResponses.js | 72 +++- .../structures/interfaces/TextBasedChannel.js | 16 +- packages/discord.js/src/util/BitField.js | 37 +- packages/discord.js/src/util/Channels.js | 9 +- packages/discord.js/src/util/DataResolver.js | 24 +- packages/discord.js/src/util/Enums.js | 5 +- .../discord.js/src/util/LimitedCollection.js | 5 +- packages/discord.js/src/util/Sweepers.js | 56 ++- packages/discord.js/src/util/Transformers.js | 24 +- packages/discord.js/src/util/Util.js | 115 ++++-- packages/discord.js/typings/index.test-d.ts | 30 +- packages/docgen/src/types/item.ts | 15 +- .../formatters/__tests__/escapers.test.ts | 8 +- packages/formatters/src/escapers.ts | 90 ++++- packages/rest/__tests__/utils.test.ts | 45 ++- packages/rest/src/lib/REST.ts | 4 +- .../rest/src/lib/handlers/BurstHandler.ts | 4 +- .../src/lib/handlers/SequentialHandler.ts | 4 +- packages/rest/src/lib/handlers/Shared.ts | 12 +- packages/rest/src/lib/utils/utils.ts | 39 +- packages/scripts/package.json | 2 +- .../scripts/src/generateSplitDocumentation.ts | 18 +- packages/scripts/turbo/generators/config.ts | 2 +- packages/structures/src/Mixin.ts | 4 +- packages/structures/src/bitfields/BitField.ts | 42 +- packages/structures/src/users/User.ts | 5 +- packages/voice/__tests__/AudioPlayer.test.ts | 5 +- packages/voice/__tests__/demuxProbe.test.ts | 12 +- packages/voice/src/DataStore.ts | 23 +- packages/voice/src/VoiceConnection.ts | 68 +++- packages/voice/src/audio/AudioPlayer.ts | 27 +- packages/voice/src/audio/AudioResource.ts | 19 +- packages/voice/src/audio/TransformerGraph.ts | 10 +- packages/voice/src/networking/DAVESession.ts | 60 ++- packages/voice/src/networking/Networking.ts | 87 +++-- .../voice/src/networking/VoiceUDPSocket.ts | 5 +- .../voice/src/networking/VoiceWebSocket.ts | 5 +- packages/voice/src/receive/SSRCMap.ts | 5 +- packages/voice/src/receive/VoiceReceiver.ts | 33 +- .../src/util/generateDependencyReport.ts | 10 +- 189 files changed, 3172 insertions(+), 916 deletions(-) diff --git a/apps/guide/src/app/guide/layout.tsx b/apps/guide/src/app/guide/layout.tsx index 97db6fca3..cd0a13468 100644 --- a/apps/guide/src/app/guide/layout.tsx +++ b/apps/guide/src/app/guide/layout.tsx @@ -10,7 +10,9 @@ export default function Layout({ children }: { readonly children: ReactNode }) { tabs: { transform(option, node) { const meta = source.getNodeMeta(node); - if (!meta || !node.icon) return option; + if (!meta || !node.icon) { + return option; + } // category selection color based on path src/styles/base.css const color = `var(--${meta.file.path.split('/')[0]}-color, var(--color-fd-foreground))`; diff --git a/apps/guide/src/components/mdx/mermaid.tsx b/apps/guide/src/components/mdx/mermaid.tsx index 05e2589c8..1cdfe7d18 100644 --- a/apps/guide/src/components/mdx/mermaid.tsx +++ b/apps/guide/src/components/mdx/mermaid.tsx @@ -11,7 +11,10 @@ export function Mermaid({ chart }: { readonly chart: string }) { const { resolvedTheme } = useTheme(); useEffect(() => { - if (currentChartRef.current === chart || !containerRef.current) return; + if (currentChartRef.current === chart || !containerRef.current) { + return; + } + const container = containerRef.current; currentChartRef.current = chart; diff --git a/packages/actions/src/releasePackages/generateReleaseTree.ts b/packages/actions/src/releasePackages/generateReleaseTree.ts index c0f187f97..e7254ebe8 100644 --- a/packages/actions/src/releasePackages/generateReleaseTree.ts +++ b/packages/actions/src/releasePackages/generateReleaseTree.ts @@ -29,7 +29,10 @@ export interface ReleaseEntry { async function fetchDevVersion(pkg: string) { try { const res = await fetch(`https://registry.npmjs.org/${pkg}/dev`); - if (!res.ok) return null; + if (!res.ok) { + return null; + } + const packument = (await res.json()) as PackumentVersion; return packument.version; } catch { @@ -47,10 +50,18 @@ async function getReleaseEntries(dev: boolean, dry: boolean) { for (const pkg of packageList) { // Don't release private packages ever (npm will error anyways) - if (pkg.private) continue; + if (pkg.private) { + continue; + } + // Just in case - if (!pkg.version || !pkg.name) continue; - if (nonNodePackages.has(pkg.name)) continue; + if (!pkg.version || !pkg.name) { + continue; + } + + if (nonNodePackages.has(pkg.name)) { + continue; + } const release: ReleaseEntry = { name: pkg.name, @@ -198,7 +209,9 @@ export async function generateReleaseTree(dev: boolean, dry: boolean, packageNam } } - if (newThisBranch.length) excludedReleaseTree.unshift(newThisBranch); + if (newThisBranch.length) { + excludedReleaseTree.unshift(newThisBranch); + } } return excludedReleaseTree; @@ -224,7 +237,9 @@ export async function generateReleaseTree(dev: boolean, dry: boolean, packageNam } } - if (newThisBranch.length) packageReleaseTree.unshift(newThisBranch); + if (newThisBranch.length) { + packageReleaseTree.unshift(newThisBranch); + } } return packageReleaseTree; diff --git a/packages/actions/src/releasePackages/releasePackage.ts b/packages/actions/src/releasePackages/releasePackage.ts index 7892264fe..3a96d2e30 100644 --- a/packages/actions/src/releasePackages/releasePackage.ts +++ b/packages/actions/src/releasePackages/releasePackage.ts @@ -54,9 +54,13 @@ export async function releasePackage(release: ReleaseEntry, dev: boolean, dry: b await $`pnpm --filter=${release.name} publish --provenance --no-git-checks ${dev ? '--tag=dev' : ''}`; } - if (!dev) await gitTagAndRelease(release, dry); + if (!dev) { + await gitTagAndRelease(release, dry); + } - if (dry) return; + if (dry) { + return; + } const before = performance.now(); diff --git a/packages/api-extractor-model/src/mixins/ApiItemContainerMixin.ts b/packages/api-extractor-model/src/mixins/ApiItemContainerMixin.ts index 469e36e13..3d810ce77 100644 --- a/packages/api-extractor-model/src/mixins/ApiItemContainerMixin.ts +++ b/packages/api-extractor-model/src/mixins/ApiItemContainerMixin.ts @@ -413,7 +413,9 @@ export function ApiItemContainerMixin( default: for (const child of node.getChildNodes()) { const result = findPlainTextNode(child); - if (result) return result; + if (result) { + return result; + } } } @@ -540,13 +542,14 @@ export function ApiItemContainerMixin( ) { for (const [index, key] of (apiItem as ApiClass | ApiInterface).typeParameters.entries() ?? []) { const typeParameter = extendsType.typeParameters?.[index]; - if (typeParameter) + if (typeParameter) { mappedTypeParameters.set(key.name, { item: next.item as ApiDeclaredItem, range: typeParameter }); - else if (key.defaultTypeExcerpt) + } else if (key.defaultTypeExcerpt) { mappedTypeParameters.set(key.name, { item: apiItem as ApiDeclaredItem, range: key.defaultTypeExcerpt.tokenRange, }); + } } } diff --git a/packages/api-extractor-model/src/model/ApiPackage.ts b/packages/api-extractor-model/src/model/ApiPackage.ts index e55b843b9..594f3f56e 100644 --- a/packages/api-extractor-model/src/model/ApiPackage.ts +++ b/packages/api-extractor-model/src/model/ApiPackage.ts @@ -245,7 +245,10 @@ export class ApiPackage extends ApiItemContainerMixin(ApiNameMixin(ApiDocumented public static loadFromJson(rawJson: any, apiJsonFilename: string = ''): ApiPackage { const jsonObject = MinifyJSONMapping.metadata in rawJson ? this._mapFromMinified(rawJson) : (rawJson as IApiPackageJson); - if (!jsonObject?.metadata) throw new Error(util.inspect(rawJson, { depth: 2 })); + if (!jsonObject?.metadata) { + throw new Error(util.inspect(rawJson, { depth: 2 })); + } + if (!jsonObject?.metadata || typeof jsonObject.metadata.schemaVersion !== 'number') { throw new Error( `Error loading ${apiJsonFilename}:` + @@ -419,17 +422,19 @@ export class ApiPackage extends ApiItemContainerMixin(ApiNameMixin(ApiDocumented private _mapToMinified(jsonObject: IApiPackageJson) { const mapper = (item: any): any => { - if (Array.isArray(item)) return item.map(mapper); - else { + if (Array.isArray(item)) { + return item.map(mapper); + } else { const result: any = {}; for (const key of Object.keys(item)) { if (key === 'dependencies') { result[MinifyJSONMapping.dependencies] = item.dependencies; } else if (key === 'tsdocConfig') { result[MinifyJSONMapping.tsdocConfig] = item.tsdocConfig; - } else + } else { result[MinifyJSONMapping[key as keyof typeof MinifyJSONMapping]] = typeof item[key] === 'object' ? mapper(item[key]) : item[key]; + } } return result; @@ -441,20 +446,22 @@ export class ApiPackage extends ApiItemContainerMixin(ApiNameMixin(ApiDocumented private static _mapFromMinified(jsonObject: any): IApiPackageJson { const mapper = (item: any): any => { - if (Array.isArray(item)) return item.map(mapper); - else { + if (Array.isArray(item)) { + return item.map(mapper); + } else { const result: any = {}; for (const key of Object.keys(item)) { if (key === MinifyJSONMapping.dependencies) { result.dependencies = item[MinifyJSONMapping.dependencies]; } else if (key === MinifyJSONMapping.tsdocConfig) { result.tsdocConfig = item[MinifyJSONMapping.tsdocConfig]; - } else + } else { result[ Object.keys(MinifyJSONMapping).find( (look) => MinifyJSONMapping[look as keyof typeof MinifyJSONMapping] === key, )! ] = typeof item[key] === 'object' ? mapper(item[key]) : item[key]; + } } return result; diff --git a/packages/api-extractor-model/src/model/Deserializer.ts b/packages/api-extractor-model/src/model/Deserializer.ts index 454912626..f1e8c2839 100644 --- a/packages/api-extractor-model/src/model/Deserializer.ts +++ b/packages/api-extractor-model/src/model/Deserializer.ts @@ -489,22 +489,25 @@ export class Deserializer { }, ]; - if (_class.extends) + if (_class.extends) { excerptTokens.push({ kind: ExcerptTokenKind.Reference, text: formatVarType(_class.extends) ?? '', canonicalReference: `${_package}!${getFirstType(_class.extends) ?? ''}:class`, }); + } - if (_class.extends && _class.implements) + if (_class.extends && _class.implements) { excerptTokens.push({ kind: ExcerptTokenKind.Content, text: ' implements ' }); + } - if (_class.implements) + if (_class.implements) { excerptTokens.push({ kind: ExcerptTokenKind.Reference, text: formatVarType(_class.implements) ?? '', canonicalReference: `${_package}!${getFirstType(_class.implements) ?? ''}:class`, }); + } members.push({ members: classMembers, diff --git a/packages/api-extractor/src/collector/Collector.ts b/packages/api-extractor/src/collector/Collector.ts index 69e23b8be..ea2d41a6f 100644 --- a/packages/api-extractor/src/collector/Collector.ts +++ b/packages/api-extractor/src/collector/Collector.ts @@ -441,7 +441,9 @@ export class Collector { * The star is used as a delimiter because it is not a legal identifier character. */ public static getSortKeyIgnoringUnderscore(identifier: string | undefined): string { - if (!identifier) return ''; + if (!identifier) { + return ''; + } let parts: string[]; @@ -532,7 +534,10 @@ export class Collector { entryPoint: IWorkingPackageEntryPoint, alreadySeenAstEntities: Set, ): void { - if (alreadySeenAstEntities.has(astEntity)) return; + if (alreadySeenAstEntities.has(astEntity)) { + return; + } + alreadySeenAstEntities.add(astEntity); if (astEntity instanceof AstSymbol) { diff --git a/packages/api-extractor/src/collector/CollectorEntity.ts b/packages/api-extractor/src/collector/CollectorEntity.ts index 0e5580c24..247317777 100644 --- a/packages/api-extractor/src/collector/CollectorEntity.ts +++ b/packages/api-extractor/src/collector/CollectorEntity.ts @@ -122,7 +122,9 @@ export class CollectorEntity { */ public get exported(): boolean { // Exported from top-level? - if (this.exportedFromEntryPoint) return true; + if (this.exportedFromEntryPoint) { + return true; + } // Exported from parent? for (const localExportNames of this._localExportNamesByParent.values()) { @@ -162,7 +164,9 @@ export class CollectorEntity { */ public get consumable(): boolean { // Exported from top-level? - if (this.exportedFromEntryPoint) return true; + if (this.exportedFromEntryPoint) { + return true; + } // Exported from consumable parent? for (const [parent, localExportNames] of this._localExportNamesByParent) { diff --git a/packages/api-extractor/src/collector/SourceMapper.ts b/packages/api-extractor/src/collector/SourceMapper.ts index 130a6cae0..0fc22a9fa 100644 --- a/packages/api-extractor/src/collector/SourceMapper.ts +++ b/packages/api-extractor/src/collector/SourceMapper.ts @@ -99,14 +99,18 @@ export class SourceMapper { } const sourceMap: ISourceMap | null = this._getSourceMap(sourceFilePath); - if (!sourceMap) return; + if (!sourceMap) { + return; + } const nearestMappingItem: MappingItem | undefined = SourceMapper._findNearestMappingItem(sourceMap.mappingItems, { line: sourceFileLine, column: sourceFileColumn, }); - if (!nearestMappingItem) return; + if (!nearestMappingItem) { + return; + } const mappedFilePath: string = path.resolve(path.dirname(sourceFilePath), nearestMappingItem.source); @@ -132,7 +136,9 @@ export class SourceMapper { } // Don't translate coordinates to a file that doesn't exist - if (!originalFileInfo.fileExists) return; + if (!originalFileInfo.fileExists) { + return; + } // The nearestMappingItem anchor may be above/left of the real position, due to gaps in the mapping. Calculate // the delta and apply it to the original position. diff --git a/packages/brokers/src/brokers/redis/BaseRedis.ts b/packages/brokers/src/brokers/redis/BaseRedis.ts index 1e262afb1..66b972401 100644 --- a/packages/brokers/src/brokers/redis/BaseRedis.ts +++ b/packages/brokers/src/brokers/redis/BaseRedis.ts @@ -233,10 +233,14 @@ export abstract class BaseRedisBroker< for (const [id, packet] of messages) { const idx = packet.findIndex((value, idx) => value.toString('utf8') === 'data' && idx % 2 === 0); - if (idx < 0) continue; + if (idx < 0) { + continue; + } const payload = packet[idx + 1]; - if (!payload) continue; + if (!payload) { + continue; + } this.emitEvent(id, this.group, eventName, this.options.decode(payload)); } diff --git a/packages/builders/src/util/normalizeArray.ts b/packages/builders/src/util/normalizeArray.ts index b1545caaf..4f5c3b3cb 100644 --- a/packages/builders/src/util/normalizeArray.ts +++ b/packages/builders/src/util/normalizeArray.ts @@ -5,7 +5,10 @@ * @param arr - The (possibly variadic) data to normalize */ export function normalizeArray(arr: RestOrArray): ItemType[] { - if (Array.isArray(arr[0])) return [...arr[0]]; + if (Array.isArray(arr[0])) { + return [...arr[0]]; + } + return arr as ItemType[]; } diff --git a/packages/collection/__tests__/collection.test.ts b/packages/collection/__tests__/collection.test.ts index 3f0af6514..37164ba2c 100644 --- a/packages/collection/__tests__/collection.test.ts +++ b/packages/collection/__tests__/collection.test.ts @@ -672,7 +672,9 @@ describe('random() tests', () => { const chars = 'abcdefghijklmnopqrstuvwxyz'; const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26]; - for (let i = 0; i < chars.length; i++) coll.set(chars[i]!, numbers[i]!); + for (let i = 0; i < chars.length; i++) { + coll.set(chars[i]!, numbers[i]!); + } const random = coll.random(5); expect(random.length).toBe(5); diff --git a/packages/collection/src/collection.ts b/packages/collection/src/collection.ts index 2608a3f1b..dff918437 100644 --- a/packages/collection/src/collection.ts +++ b/packages/collection/src/collection.ts @@ -38,8 +38,14 @@ export class Collection extends Map { * ``` */ public ensure(key: Key, defaultValueGenerator: (key: Key, collection: this) => Value): Value { - if (this.has(key)) return this.get(key)!; - if (typeof defaultValueGenerator !== 'function') throw new TypeError(`${defaultValueGenerator} is not a function`); + if (this.has(key)) { + return this.get(key)!; + } + + if (typeof defaultValueGenerator !== 'function') { + throw new TypeError(`${defaultValueGenerator} is not a function`); + } + const defaultValue = defaultValueGenerator(key, this); this.set(key, defaultValue); return defaultValue; @@ -74,9 +80,17 @@ export class Collection extends Map { public first(): Value | undefined; public first(amount: number): Value[]; public first(amount?: number): Value | Value[] | undefined { - if (amount === undefined) return this.values().next().value; - if (amount < 0) return this.last(amount * -1); - if (amount >= this.size) return [...this.values()]; + if (amount === undefined) { + return this.values().next().value; + } + + if (amount < 0) { + return this.last(amount * -1); + } + + if (amount >= this.size) { + return [...this.values()]; + } const iter = this.values(); // eslint-disable-next-line unicorn/no-new-array @@ -98,9 +112,17 @@ export class Collection extends Map { public firstKey(): Key | undefined; public firstKey(amount: number): Key[]; public firstKey(amount?: number): Key | Key[] | undefined { - if (amount === undefined) return this.keys().next().value; - if (amount < 0) return this.lastKey(amount * -1); - if (amount >= this.size) return [...this.keys()]; + if (amount === undefined) { + return this.keys().next().value; + } + + if (amount < 0) { + return this.lastKey(amount * -1); + } + + if (amount >= this.size) { + return [...this.keys()]; + } const iter = this.keys(); // eslint-disable-next-line unicorn/no-new-array @@ -122,9 +144,17 @@ export class Collection extends Map { public last(): Value | undefined; public last(amount: number): Value[]; public last(amount?: number): Value | Value[] | undefined { - if (amount === undefined) return this.at(-1); - if (!amount) return []; - if (amount < 0) return this.first(amount * -1); + if (amount === undefined) { + return this.at(-1); + } + + if (!amount) { + return []; + } + + if (amount < 0) { + return this.first(amount * -1); + } const arr = [...this.values()]; return arr.slice(amount * -1); @@ -140,9 +170,17 @@ export class Collection extends Map { public lastKey(): Key | undefined; public lastKey(amount: number): Key[]; public lastKey(amount?: number): Key | Key[] | undefined { - if (amount === undefined) return this.keyAt(-1); - if (!amount) return []; - if (amount < 0) return this.firstKey(amount * -1); + if (amount === undefined) { + return this.keyAt(-1); + } + + if (!amount) { + return []; + } + + if (amount < 0) { + return this.firstKey(amount * -1); + } const arr = [...this.keys()]; return arr.slice(amount * -1); @@ -158,10 +196,14 @@ export class Collection extends Map { public at(index: number): Value | undefined { index = Math.trunc(index); if (index >= 0) { - if (index >= this.size) return undefined; + if (index >= this.size) { + return undefined; + } } else { index += this.size; - if (index < 0) return undefined; + if (index < 0) { + return undefined; + } } const iter = this.values(); @@ -182,10 +224,14 @@ export class Collection extends Map { public keyAt(index: number): Key | undefined { index = Math.trunc(index); if (index >= 0) { - if (index >= this.size) return undefined; + if (index >= this.size) { + return undefined; + } } else { index += this.size; - if (index < 0) return undefined; + if (index < 0) { + return undefined; + } } const iter = this.keys(); @@ -205,9 +251,14 @@ export class Collection extends Map { public random(): Value | undefined; public random(amount: number): Value[]; public random(amount?: number): Value | Value[] | undefined { - if (amount === undefined) return this.at(Math.floor(Math.random() * this.size)); + if (amount === undefined) { + return this.at(Math.floor(Math.random() * this.size)); + } + amount = Math.min(this.size, amount); - if (!amount) return []; + if (!amount) { + return []; + } const values = [...this.values()]; for (let sourceIndex = 0; sourceIndex < amount; sourceIndex++) { @@ -227,9 +278,14 @@ export class Collection extends Map { public randomKey(): Key | undefined; public randomKey(amount: number): Key[]; public randomKey(amount?: number): Key | Key[] | undefined { - if (amount === undefined) return this.keyAt(Math.floor(Math.random() * this.size)); + if (amount === undefined) { + return this.keyAt(Math.floor(Math.random() * this.size)); + } + amount = Math.min(this.size, amount); - if (!amount) return []; + if (!amount) { + return []; + } const keys = [...this.keys()]; for (let sourceIndex = 0; sourceIndex < amount; sourceIndex++) { @@ -247,7 +303,10 @@ export class Collection extends Map { public reverse() { const entries = [...this.entries()].reverse(); this.clear(); - for (const [key, value] of entries) this.set(key, value); + for (const [key, value] of entries) { + this.set(key, value); + } + return this; } @@ -278,10 +337,18 @@ export class Collection extends Map { thisArg: This, ): Value | undefined; public find(fn: (value: Value, key: Key, collection: this) => unknown, thisArg?: unknown): Value | undefined { - if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); - if (thisArg !== undefined) fn = fn.bind(thisArg); + if (typeof fn !== 'function') { + throw new TypeError(`${fn} is not a function`); + } + + if (thisArg !== undefined) { + fn = fn.bind(thisArg); + } + for (const [key, val] of this) { - if (fn(val, key, this)) return val; + if (fn(val, key, this)) { + return val; + } } return undefined; @@ -312,10 +379,18 @@ export class Collection extends Map { thisArg: This, ): Key | undefined; public findKey(fn: (value: Value, key: Key, collection: this) => unknown, thisArg?: unknown): Key | undefined { - if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); - if (thisArg !== undefined) fn = fn.bind(thisArg); + if (typeof fn !== 'function') { + throw new TypeError(`${fn} is not a function`); + } + + if (thisArg !== undefined) { + fn = fn.bind(thisArg); + } + for (const [key, val] of this) { - if (fn(val, key, this)) return key; + if (fn(val, key, this)) { + return key; + } } return undefined; @@ -341,13 +416,21 @@ export class Collection extends Map { thisArg: This, ): Value | undefined; public findLast(fn: (value: Value, key: Key, collection: this) => unknown, thisArg?: unknown): Value | undefined { - if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); - if (thisArg !== undefined) fn = fn.bind(thisArg); + if (typeof fn !== 'function') { + throw new TypeError(`${fn} is not a function`); + } + + if (thisArg !== undefined) { + fn = fn.bind(thisArg); + } + const entries = [...this.entries()]; for (let index = entries.length - 1; index >= 0; index--) { const val = entries[index]![1]; const key = entries[index]![0]; - if (fn(val, key, this)) return val; + if (fn(val, key, this)) { + return val; + } } return undefined; @@ -374,13 +457,21 @@ export class Collection extends Map { thisArg: This, ): Key | undefined; public findLastKey(fn: (value: Value, key: Key, collection: this) => unknown, thisArg?: unknown): Key | undefined { - if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); - if (thisArg !== undefined) fn = fn.bind(thisArg); + if (typeof fn !== 'function') { + throw new TypeError(`${fn} is not a function`); + } + + if (thisArg !== undefined) { + fn = fn.bind(thisArg); + } + const entries = [...this.entries()]; for (let index = entries.length - 1; index >= 0; index--) { const key = entries[index]![0]; const val = entries[index]![1]; - if (fn(val, key, this)) return key; + if (fn(val, key, this)) { + return key; + } } return undefined; @@ -396,11 +487,19 @@ export class Collection extends Map { public sweep(fn: (value: Value, key: Key, collection: this) => unknown): number; public sweep(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): number; public sweep(fn: (value: Value, key: Key, collection: this) => unknown, thisArg?: unknown): number { - if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); - if (thisArg !== undefined) fn = fn.bind(thisArg); + if (typeof fn !== 'function') { + throw new TypeError(`${fn} is not a function`); + } + + if (thisArg !== undefined) { + fn = fn.bind(thisArg); + } + const previousSize = this.size; for (const [key, val] of this) { - if (fn(val, key, this)) this.delete(key); + if (fn(val, key, this)) { + this.delete(key); + } } return previousSize - this.size; @@ -438,11 +537,19 @@ export class Collection extends Map { thisArg: This, ): Collection; public filter(fn: (value: Value, key: Key, collection: this) => unknown, thisArg?: unknown): Collection { - if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); - if (thisArg !== undefined) fn = fn.bind(thisArg); + if (typeof fn !== 'function') { + throw new TypeError(`${fn} is not a function`); + } + + if (thisArg !== undefined) { + fn = fn.bind(thisArg); + } + const results = new this.constructor[Symbol.species](); for (const [key, val] of this) { - if (fn(val, key, this)) results.set(key, val); + if (fn(val, key, this)) { + results.set(key, val); + } } return results; @@ -484,8 +591,14 @@ export class Collection extends Map { fn: (value: Value, key: Key, collection: this) => unknown, thisArg?: unknown, ): [Collection, Collection] { - if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); - if (thisArg !== undefined) fn = fn.bind(thisArg); + if (typeof fn !== 'function') { + throw new TypeError(`${fn} is not a function`); + } + + if (thisArg !== undefined) { + fn = fn.bind(thisArg); + } + const results: [Collection, Collection] = [ new this.constructor[Symbol.species](), new this.constructor[Symbol.species](), @@ -545,8 +658,14 @@ export class Collection extends Map { thisArg: This, ): NewValue[]; public map(fn: (value: Value, key: Key, collection: this) => NewValue, thisArg?: unknown): NewValue[] { - if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); - if (thisArg !== undefined) fn = fn.bind(thisArg); + if (typeof fn !== 'function') { + throw new TypeError(`${fn} is not a function`); + } + + if (thisArg !== undefined) { + fn = fn.bind(thisArg); + } + const iter = this.entries(); // eslint-disable-next-line unicorn/no-new-array const results: NewValue[] = new Array(this.size); @@ -578,10 +697,19 @@ export class Collection extends Map { fn: (value: Value, key: Key, collection: this) => NewValue, thisArg?: unknown, ): Collection { - if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); - if (thisArg !== undefined) fn = fn.bind(thisArg); + if (typeof fn !== 'function') { + throw new TypeError(`${fn} is not a function`); + } + + if (thisArg !== undefined) { + fn = fn.bind(thisArg); + } + const coll = new this.constructor[Symbol.species](); - for (const [key, val] of this) coll.set(key, fn(val, key, this)); + for (const [key, val] of this) { + coll.set(key, fn(val, key, this)); + } + return coll; } @@ -599,10 +727,18 @@ export class Collection extends Map { public some(fn: (value: Value, key: Key, collection: this) => unknown): boolean; public some(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): boolean; public some(fn: (value: Value, key: Key, collection: this) => unknown, thisArg?: unknown): boolean { - if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); - if (thisArg !== undefined) fn = fn.bind(thisArg); + if (typeof fn !== 'function') { + throw new TypeError(`${fn} is not a function`); + } + + if (thisArg !== undefined) { + fn = fn.bind(thisArg); + } + for (const [key, val] of this) { - if (fn(val, key, this)) return true; + if (fn(val, key, this)) { + return true; + } } return false; @@ -636,10 +772,18 @@ export class Collection extends Map { ): this is Collection; public every(fn: (this: This, value: Value, key: Key, collection: this) => unknown, thisArg: This): boolean; public every(fn: (value: Value, key: Key, collection: this) => unknown, thisArg?: unknown): boolean { - if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); - if (thisArg !== undefined) fn = fn.bind(thisArg); + if (typeof fn !== 'function') { + throw new TypeError(`${fn} is not a function`); + } + + if (thisArg !== undefined) { + fn = fn.bind(thisArg); + } + for (const [key, val] of this) { - if (!fn(val, key, this)) return false; + if (!fn(val, key, this)) { + return false; + } } return true; @@ -669,12 +813,18 @@ export class Collection extends Map { fn: (accumulator: InitialValue, value: Value, key: Key, collection: this) => InitialValue, initialValue?: InitialValue, ): InitialValue { - if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); + if (typeof fn !== 'function') { + throw new TypeError(`${fn} is not a function`); + } + let accumulator!: InitialValue; const iterator = this.entries(); if (initialValue === undefined) { - if (this.size === 0) throw new TypeError('Reduce of empty collection with no initial value'); + if (this.size === 0) { + throw new TypeError('Reduce of empty collection with no initial value'); + } + accumulator = iterator.next().value![1] as unknown as InitialValue; } else { accumulator = initialValue; @@ -706,13 +856,19 @@ export class Collection extends Map { fn: (accumulator: InitialValue, value: Value, key: Key, collection: this) => InitialValue, initialValue?: InitialValue, ): InitialValue { - if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); + if (typeof fn !== 'function') { + throw new TypeError(`${fn} is not a function`); + } + const entries = [...this.entries()]; let accumulator!: InitialValue; let index: number; if (initialValue === undefined) { - if (entries.length === 0) throw new TypeError('Reduce of empty collection with no initial value'); + if (entries.length === 0) { + throw new TypeError('Reduce of empty collection with no initial value'); + } + accumulator = entries[entries.length - 1]![1] as unknown as InitialValue; index = entries.length - 1; } else { @@ -747,8 +903,13 @@ export class Collection extends Map { public each(fn: (value: Value, key: Key, collection: this) => void): this; public each(fn: (this: This, value: Value, key: Key, collection: this) => void, thisArg: This): this; public each(fn: (value: Value, key: Key, collection: this) => void, thisArg?: unknown): this { - if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); - if (thisArg !== undefined) fn = fn.bind(thisArg); + if (typeof fn !== 'function') { + throw new TypeError(`${fn} is not a function`); + } + + if (thisArg !== undefined) { + fn = fn.bind(thisArg); + } for (const [key, value] of this) { fn(value, key, this); @@ -773,8 +934,14 @@ export class Collection extends Map { public tap(fn: (collection: this) => void): this; public tap(fn: (this: This, collection: this) => void, thisArg: This): this; public tap(fn: (collection: this) => void, thisArg?: unknown): this { - if (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`); - if (thisArg !== undefined) fn = fn.bind(thisArg); + if (typeof fn !== 'function') { + throw new TypeError(`${fn} is not a function`); + } + + if (thisArg !== undefined) { + fn = fn.bind(thisArg); + } + fn(this); return this; } @@ -803,7 +970,9 @@ export class Collection extends Map { public concat(...collections: ReadonlyCollection[]) { const newColl = this.clone(); for (const coll of collections) { - for (const [key, val] of coll) newColl.set(key, val); + for (const [key, val] of coll) { + newColl.set(key, val); + } } return newColl; @@ -818,9 +987,18 @@ export class Collection extends Map { * @returns Whether the collections have identical contents */ public equals(collection: ReadonlyCollection) { - if (!collection) return false; // runtime check - if (this === collection) return true; - if (this.size !== collection.size) return false; + if (!collection) { + return false; + } // runtime check + + if (this === collection) { + return true; + } + + if (this.size !== collection.size) { + return false; + } + for (const [key, value] of this) { if (!collection.has(key) || value !== collection.get(key)) { return false; @@ -874,7 +1052,9 @@ export class Collection extends Map { const coll = new this.constructor[Symbol.species](); for (const [key, value] of this) { - if (other.has(key)) coll.set(key, value); + if (other.has(key)) { + coll.set(key, value); + } } return coll; @@ -900,7 +1080,9 @@ export class Collection extends Map { const coll = new this.constructor[Symbol.species](this); for (const [key, value] of other) { - if (!coll.has(key)) coll.set(key, value); + if (!coll.has(key)) { + coll.set(key, value); + } } return coll; @@ -924,7 +1106,9 @@ export class Collection extends Map { const coll = new this.constructor[Symbol.species](); for (const [key, value] of this) { - if (!other.has(key)) coll.set(key, value); + if (!other.has(key)) { + coll.set(key, value); + } } return coll; @@ -949,11 +1133,15 @@ export class Collection extends Map { const coll = new this.constructor[Symbol.species](); for (const [key, value] of this) { - if (!other.has(key)) coll.set(key, value); + if (!other.has(key)) { + coll.set(key, value); + } } for (const [key, value] of other) { - if (!this.has(key)) coll.set(key, value); + if (!this.has(key)) { + coll.set(key, value); + } } return coll; @@ -1003,14 +1191,20 @@ export class Collection extends Map { if (hasInSelf) { if (hasInOther) { const result = whenInBoth(this.get(key)!, other.get(key)!, key); - if (result.keep) coll.set(key, result.value); + if (result.keep) { + coll.set(key, result.value); + } } else { const result = whenInSelf(this.get(key)!, key); - if (result.keep) coll.set(key, result.value); + if (result.keep) { + coll.set(key, result.value); + } } } else if (hasInOther) { const result = whenInOther(other.get(key)!, key); - if (result.keep) coll.set(key, result.value); + if (result.keep) { + coll.set(key, result.value); + } } } @@ -1052,13 +1246,24 @@ export class Collection extends Map { * operation with arguments `firstValue`, `secondValue` and `undefined`. */ private static defaultSort(firstValue: Value, secondValue: Value): number { - if (firstValue === undefined) return secondValue === undefined ? 0 : 1; - if (secondValue === undefined) return -1; + if (firstValue === undefined) { + return secondValue === undefined ? 0 : 1; + } + + if (secondValue === undefined) { + return -1; + } const x = String(firstValue); const y = String(secondValue); - if (x < y) return -1; - if (y < x) return 1; + if (x < y) { + return -1; + } + + if (y < x) { + return 1; + } + return 0; } diff --git a/packages/core/src/client.ts b/packages/core/src/client.ts index f143aac70..f2e026962 100644 --- a/packages/core/src/client.ts +++ b/packages/core/src/client.ts @@ -259,7 +259,9 @@ export class Client extends AsyncEventEmitter { }); for await (const [{ data }] of iterator) { - if (data.nonce !== nonce) continue; + if (data.nonce !== nonce) { + continue; + } clearTimeout(timer); timer = undefined; @@ -273,7 +275,9 @@ export class Client extends AsyncEventEmitter { chunkCount: data.chunk_count, }; - if (data.chunk_index >= data.chunk_count - 1) break; + if (data.chunk_index >= data.chunk_count - 1) { + break; + } timer = createTimer(controller, timeout); } @@ -310,8 +314,13 @@ export class Client extends AsyncEventEmitter { for await (const data of this.requestGuildMembersIterator({ ...options, nonce }, timeout)) { members.push(...data.members); - if (data.presences) presences.push(...data.presences); - if (data.notFound) notFound.push(...data.notFound); + if (data.presences) { + presences.push(...data.presences); + } + + if (data.notFound) { + notFound.push(...data.notFound); + } } return { members, nonce, notFound, presences }; @@ -360,7 +369,9 @@ export class Client extends AsyncEventEmitter { const guildIds = new Set(options.guild_ids); for await (const [{ data }] of iterator) { - if (!guildIds.has(data.guild_id)) continue; + if (!guildIds.has(data.guild_id)) { + continue; + } clearTimeout(timer); timer = undefined; @@ -372,7 +383,9 @@ export class Client extends AsyncEventEmitter { guildIds.delete(data.guild_id); - if (guildIds.size === 0) break; + if (guildIds.size === 0) { + break; + } timer = createTimer(controller, timeout); } diff --git a/packages/discord.js/scripts/generateRequires.mjs b/packages/discord.js/scripts/generateRequires.mjs index 8cec4d51a..922bffd8a 100644 --- a/packages/discord.js/scripts/generateRequires.mjs +++ b/packages/discord.js/scripts/generateRequires.mjs @@ -7,7 +7,9 @@ async function writeWebsocketHandlerImports() { const handlersDirectory = new URL('../src/client/websocket/handlers', import.meta.url); for (const file of (await readdir(handlersDirectory)).sort()) { - if (file === 'index.js') continue; + if (file === 'index.js') { + continue; + } lines.push(` ['${file.slice(0, -3)}', require('./${file}')],`); } @@ -35,7 +37,9 @@ async function writeClientActionImports() { const actionsDirectory = new URL('../src/client/actions', import.meta.url); for (const file of (await readdir(actionsDirectory)).sort()) { - if (file === 'Action.js' || file === 'ActionsManager.js') continue; + if (file === 'Action.js' || file === 'ActionsManager.js') { + continue; + } const actionName = file.slice(0, -3); diff --git a/packages/discord.js/src/client/Client.js b/packages/discord.js/src/client/Client.js index bd53a2b91..536614a1d 100644 --- a/packages/discord.js/src/client/Client.js +++ b/packages/discord.js/src/client/Client.js @@ -268,7 +268,10 @@ class Client extends BaseClient { * client.login('my token'); */ async login(token = this.token) { - if (!token || typeof token !== 'string') throw new DiscordjsError(ErrorCodes.TokenInvalid); + if (!token || typeof token !== 'string') { + throw new DiscordjsError(ErrorCodes.TokenInvalid); + } + this.token = token.replace(/^bot\s*/i, ''); this.rest.setToken(this.token); @@ -531,7 +534,10 @@ class Client extends BaseClient { async fetchVoiceRegions() { const apiRegions = await this.rest.get(Routes.voiceRegions()); const regions = new Collection(); - for (const region of apiRegions) regions.set(region.id, new VoiceRegion(region)); + for (const region of apiRegions) { + regions.set(region.id, new VoiceRegion(region)); + } + return regions; } @@ -604,7 +610,10 @@ class Client extends BaseClient { */ async fetchGuildPreview(guild) { const id = this.guilds.resolveId(guild); - if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable'); + if (!id) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable'); + } + const data = await this.rest.get(Routes.guildPreview(id)); return new GuildPreview(this, data); } @@ -617,7 +626,10 @@ class Client extends BaseClient { */ async fetchGuildWidget(guild) { const id = this.guilds.resolveId(guild); - if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable'); + if (!id) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'guild', 'GuildResolvable'); + } + const data = await this.rest.get(Routes.guildWidgetJSON(id)); return new Widget(this, data); } @@ -654,8 +666,13 @@ class Client extends BaseClient { * console.log(`Generated bot invite link: ${link}`); */ generateInvite(options = {}) { - if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); - if (!this.application) throw new DiscordjsError(ErrorCodes.ClientNotReady, 'generate an invite link'); + if (typeof options !== 'object') { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); + } + + if (!this.application) { + throw new DiscordjsError(ErrorCodes.ClientNotReady, 'generate an invite link'); + } const { scopes } = options; if (scopes === undefined) { @@ -688,12 +705,17 @@ class Client extends BaseClient { if (options.permissions) { const permissions = PermissionsBitField.resolve(options.permissions); - if (permissions) query.set('permissions', permissions.toString()); + if (permissions) { + query.set('permissions', permissions.toString()); + } } if (options.guild) { const guildId = this.guilds.resolveId(options.guild); - if (!guildId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options.guild', 'GuildResolvable'); + if (!guildId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options.guild', 'GuildResolvable'); + } + query.set('guild_id', guildId); } @@ -715,7 +737,9 @@ class Client extends BaseClient { * @private */ get _censoredToken() { - if (!this.token) return null; + if (!this.token) { + return null; + } return this.token .split('.') diff --git a/packages/discord.js/src/client/actions/Action.js b/packages/discord.js/src/client/actions/Action.js index 791fe480d..f44c02286 100644 --- a/packages/discord.js/src/client/actions/Action.js +++ b/packages/discord.js/src/client/actions/Action.js @@ -36,10 +36,14 @@ class Action { if (!('recipients' in data)) { // Try to resolve the recipient, but do not add the client user. const recipient = data.author ?? data.user ?? { id: data.user_id }; - if (recipient.id !== this.client.user.id) payloadData.recipients = [recipient]; + if (recipient.id !== this.client.user.id) { + payloadData.recipients = [recipient]; + } } - if (id !== undefined) payloadData.id = id; + if (id !== undefined) { + payloadData.id = id; + } return ( data[this.client.actions.injectedChannel] ?? @@ -68,7 +72,9 @@ class Action { getPoll(data, message, channel) { const includePollPartial = this.client.options.partials.includes(Partials.Poll); const includePollAnswerPartial = this.client.options.partials.includes(Partials.PollAnswer); - if (message.partial && (!includePollPartial || !includePollAnswerPartial)) return null; + if (message.partial && (!includePollPartial || !includePollAnswerPartial)) { + return null; + } if (!message.poll && includePollPartial) { message.poll = new Poll(this.client, data, message, channel); diff --git a/packages/discord.js/src/client/actions/ChannelUpdate.js b/packages/discord.js/src/client/actions/ChannelUpdate.js index 8a3b15d7b..48206d48c 100644 --- a/packages/discord.js/src/client/actions/ChannelUpdate.js +++ b/packages/discord.js/src/client/actions/ChannelUpdate.js @@ -20,7 +20,9 @@ class ChannelUpdateAction extends Action { } if (channel.isTextBased() && newChannel.isTextBased()) { - for (const [id, message] of channel.messages.cache) newChannel.messages.cache.set(id, message); + for (const [id, message] of channel.messages.cache) { + newChannel.messages.cache.set(id, message); + } } channel = newChannel; diff --git a/packages/discord.js/src/client/actions/GuildChannelsPositionUpdate.js b/packages/discord.js/src/client/actions/GuildChannelsPositionUpdate.js index 7a6d739c2..50a82b6f2 100644 --- a/packages/discord.js/src/client/actions/GuildChannelsPositionUpdate.js +++ b/packages/discord.js/src/client/actions/GuildChannelsPositionUpdate.js @@ -10,7 +10,9 @@ class GuildChannelsPositionUpdateAction extends Action { if (guild) { for (const partialChannel of data.channels) { const channel = guild.channels.cache.get(partialChannel.id); - if (channel) channel.rawPosition = partialChannel.position; + if (channel) { + channel.rawPosition = partialChannel.position; + } } } diff --git a/packages/discord.js/src/client/actions/GuildEmojiCreate.js b/packages/discord.js/src/client/actions/GuildEmojiCreate.js index 0bf6ae0fb..fcd4ddbff 100644 --- a/packages/discord.js/src/client/actions/GuildEmojiCreate.js +++ b/packages/discord.js/src/client/actions/GuildEmojiCreate.js @@ -13,7 +13,10 @@ class GuildEmojiCreateAction extends Action { * @event Client#emojiCreate * @param {GuildEmoji} emoji The emoji that was created */ - if (!already) this.client.emit(Events.GuildEmojiCreate, emoji); + if (!already) { + this.client.emit(Events.GuildEmojiCreate, emoji); + } + return { emoji }; } } diff --git a/packages/discord.js/src/client/actions/GuildEmojisUpdate.js b/packages/discord.js/src/client/actions/GuildEmojisUpdate.js index 942462b1f..9979c7381 100644 --- a/packages/discord.js/src/client/actions/GuildEmojisUpdate.js +++ b/packages/discord.js/src/client/actions/GuildEmojisUpdate.js @@ -5,7 +5,9 @@ const { Action } = require('./Action.js'); class GuildEmojisUpdateAction extends Action { handle(data) { const guild = this.client.guilds.cache.get(data.guild_id); - if (!guild?.emojis) return; + if (!guild?.emojis) { + return; + } const deletions = new Map(guild.emojis.cache); diff --git a/packages/discord.js/src/client/actions/GuildMemberUpdate.js b/packages/discord.js/src/client/actions/GuildMemberUpdate.js index fc999d952..df26a0672 100644 --- a/packages/discord.js/src/client/actions/GuildMemberUpdate.js +++ b/packages/discord.js/src/client/actions/GuildMemberUpdate.js @@ -27,7 +27,9 @@ class GuildMemberUpdateAction extends Action { * @param {GuildMember} oldMember The member before the update * @param {GuildMember} newMember The member after the update */ - if (!member.equals(old)) client.emit(Events.GuildMemberUpdate, old, member); + if (!member.equals(old)) { + client.emit(Events.GuildMemberUpdate, old, member); + } } else { const newMember = guild.members._add(data); /** diff --git a/packages/discord.js/src/client/actions/GuildRoleCreate.js b/packages/discord.js/src/client/actions/GuildRoleCreate.js index 2db31c6cd..41950f9c3 100644 --- a/packages/discord.js/src/client/actions/GuildRoleCreate.js +++ b/packages/discord.js/src/client/actions/GuildRoleCreate.js @@ -17,7 +17,9 @@ class GuildRoleCreateAction extends Action { * @event Client#roleCreate * @param {Role} role The role that was created */ - if (!already) client.emit(Events.GuildRoleCreate, role); + if (!already) { + client.emit(Events.GuildRoleCreate, role); + } } return { role }; diff --git a/packages/discord.js/src/client/actions/GuildRolesPositionUpdate.js b/packages/discord.js/src/client/actions/GuildRolesPositionUpdate.js index a940e3e6a..d41b52137 100644 --- a/packages/discord.js/src/client/actions/GuildRolesPositionUpdate.js +++ b/packages/discord.js/src/client/actions/GuildRolesPositionUpdate.js @@ -10,7 +10,9 @@ class GuildRolesPositionUpdateAction extends Action { if (guild) { for (const partialRole of data.roles) { const role = guild.roles.cache.get(partialRole.id); - if (role) role.rawPosition = partialRole.position; + if (role) { + role.rawPosition = partialRole.position; + } } } diff --git a/packages/discord.js/src/client/actions/GuildSoundboardSoundDelete.js b/packages/discord.js/src/client/actions/GuildSoundboardSoundDelete.js index de66d051c..849841e0c 100644 --- a/packages/discord.js/src/client/actions/GuildSoundboardSoundDelete.js +++ b/packages/discord.js/src/client/actions/GuildSoundboardSoundDelete.js @@ -7,7 +7,9 @@ class GuildSoundboardSoundDeleteAction extends Action { handle(data) { const guild = this.client.guilds.cache.get(data.guild_id); - if (!guild) return {}; + if (!guild) { + return {}; + } const soundboardSound = this.getSoundboardSound(data, guild); diff --git a/packages/discord.js/src/client/actions/GuildStickerCreate.js b/packages/discord.js/src/client/actions/GuildStickerCreate.js index bd88c357a..40c13a073 100644 --- a/packages/discord.js/src/client/actions/GuildStickerCreate.js +++ b/packages/discord.js/src/client/actions/GuildStickerCreate.js @@ -13,7 +13,10 @@ class GuildStickerCreateAction extends Action { * @event Client#stickerCreate * @param {Sticker} sticker The sticker that was created */ - if (!already) this.client.emit(Events.GuildStickerCreate, sticker); + if (!already) { + this.client.emit(Events.GuildStickerCreate, sticker); + } + return { sticker }; } } diff --git a/packages/discord.js/src/client/actions/GuildStickersUpdate.js b/packages/discord.js/src/client/actions/GuildStickersUpdate.js index f1fdbdf33..7c096e9b5 100644 --- a/packages/discord.js/src/client/actions/GuildStickersUpdate.js +++ b/packages/discord.js/src/client/actions/GuildStickersUpdate.js @@ -5,7 +5,9 @@ const { Action } = require('./Action.js'); class GuildStickersUpdateAction extends Action { handle(data) { const guild = this.client.guilds.cache.get(data.guild_id); - if (!guild?.stickers) return; + if (!guild?.stickers) { + return; + } const deletions = new Map(guild.stickers.cache); diff --git a/packages/discord.js/src/client/actions/InteractionCreate.js b/packages/discord.js/src/client/actions/InteractionCreate.js index 2e263425f..eb39b7f48 100644 --- a/packages/discord.js/src/client/actions/InteractionCreate.js +++ b/packages/discord.js/src/client/actions/InteractionCreate.js @@ -36,7 +36,10 @@ class InteractionCreateAction extends Action { InteractionClass = UserContextMenuCommandInteraction; break; case ApplicationCommandType.Message: - if (channel && !channel.isTextBased()) return; + if (channel && !channel.isTextBased()) { + return; + } + InteractionClass = MessageContextMenuCommandInteraction; break; case ApplicationCommandType.PrimaryEntryPoint: @@ -52,7 +55,9 @@ class InteractionCreateAction extends Action { break; case InteractionType.MessageComponent: - if (channel && !channel.isTextBased()) return; + if (channel && !channel.isTextBased()) { + return; + } switch (data.data.component_type) { case ComponentType.Button: diff --git a/packages/discord.js/src/client/actions/MessageCreate.js b/packages/discord.js/src/client/actions/MessageCreate.js index 15aa785d0..35709927d 100644 --- a/packages/discord.js/src/client/actions/MessageCreate.js +++ b/packages/discord.js/src/client/actions/MessageCreate.js @@ -12,7 +12,9 @@ class MessageCreateAction extends Action { ...('guild_id' in data && { guild_id: data.guild_id }), }); if (channel) { - if (!channel.isTextBased()) return {}; + if (!channel.isTextBased()) { + return {}; + } if (channel.isThread()) { channel.messageCount++; @@ -20,7 +22,10 @@ class MessageCreateAction extends Action { } const existing = channel.messages.cache.get(data.id); - if (existing && existing.author?.id !== this.client.user.id) return { message: existing }; + if (existing && existing.author?.id !== this.client.user.id) { + return { message: existing }; + } + const message = existing ?? channel.messages._add(data); channel.lastMessageId = data.id; diff --git a/packages/discord.js/src/client/actions/MessageDelete.js b/packages/discord.js/src/client/actions/MessageDelete.js index 753b88b48..c862f1af5 100644 --- a/packages/discord.js/src/client/actions/MessageDelete.js +++ b/packages/discord.js/src/client/actions/MessageDelete.js @@ -9,9 +9,13 @@ class MessageDeleteAction extends Action { const channel = this.getChannel({ id: data.channel_id, ...('guild_id' in data && { guild_id: data.guild_id }) }); let message; if (channel) { - if (!channel.isTextBased()) return {}; + if (!channel.isTextBased()) { + return {}; + } - if (channel.isThread()) channel.messageCount--; + if (channel.isThread()) { + channel.messageCount--; + } message = this.getMessage(data, channel); if (message) { diff --git a/packages/discord.js/src/client/actions/MessageDeleteBulk.js b/packages/discord.js/src/client/actions/MessageDeleteBulk.js index 44e5c0732..e76f862ef 100644 --- a/packages/discord.js/src/client/actions/MessageDeleteBulk.js +++ b/packages/discord.js/src/client/actions/MessageDeleteBulk.js @@ -10,9 +10,13 @@ class MessageDeleteBulkAction extends Action { const channel = client.channels.cache.get(data.channel_id); if (channel) { - if (!channel.isTextBased()) return {}; + if (!channel.isTextBased()) { + return {}; + } - if (channel.isThread()) channel.messageCount -= data.ids.length; + if (channel.isThread()) { + channel.messageCount -= data.ids.length; + } const ids = data.ids; const messages = new Collection(); @@ -38,7 +42,10 @@ class MessageDeleteBulkAction extends Action { * @param {Collection} messages The deleted messages, mapped by their id * @param {GuildTextBasedChannel} channel The channel that the messages were deleted in */ - if (messages.size > 0) client.emit(Events.MessageBulkDelete, messages, channel); + if (messages.size > 0) { + client.emit(Events.MessageBulkDelete, messages, channel); + } + return { messages }; } diff --git a/packages/discord.js/src/client/actions/MessagePollVoteAdd.js b/packages/discord.js/src/client/actions/MessagePollVoteAdd.js index 8c653fc04..8eb9423a6 100644 --- a/packages/discord.js/src/client/actions/MessagePollVoteAdd.js +++ b/packages/discord.js/src/client/actions/MessagePollVoteAdd.js @@ -6,16 +6,24 @@ const { Action } = require('./Action.js'); class MessagePollVoteAddAction extends Action { handle(data) { const channel = this.getChannel({ id: data.channel_id, ...('guild_id' in data && { guild_id: data.guild_id }) }); - if (!channel?.isTextBased()) return false; + if (!channel?.isTextBased()) { + return false; + } const message = this.getMessage(data, channel); - if (!message) return false; + if (!message) { + return false; + } const poll = this.getPoll(data, message, channel); - if (!poll) return false; + if (!poll) { + return false; + } const answer = poll.answers.get(data.answer_id); - if (!answer) return false; + if (!answer) { + return false; + } const user = this.getUser(data); diff --git a/packages/discord.js/src/client/actions/MessagePollVoteRemove.js b/packages/discord.js/src/client/actions/MessagePollVoteRemove.js index a8f1c87b3..bdef7bc23 100644 --- a/packages/discord.js/src/client/actions/MessagePollVoteRemove.js +++ b/packages/discord.js/src/client/actions/MessagePollVoteRemove.js @@ -6,16 +6,24 @@ const { Action } = require('./Action.js'); class MessagePollVoteRemoveAction extends Action { handle(data) { const channel = this.getChannel({ id: data.channel_id, ...('guild_id' in data && { guild_id: data.guild_id }) }); - if (!channel?.isTextBased()) return false; + if (!channel?.isTextBased()) { + return false; + } const message = this.getMessage(data, channel); - if (!message) return false; + if (!message) { + return false; + } const poll = this.getPoll(data, message, channel); - if (!poll) return false; + if (!poll) { + return false; + } const answer = poll.answers.get(data.answer_id); - if (!answer) return false; + if (!answer) { + return false; + } answer.voters.cache.delete(data.user_id); diff --git a/packages/discord.js/src/client/actions/MessageReactionAdd.js b/packages/discord.js/src/client/actions/MessageReactionAdd.js index 9e9b295b2..33145222c 100644 --- a/packages/discord.js/src/client/actions/MessageReactionAdd.js +++ b/packages/discord.js/src/client/actions/MessageReactionAdd.js @@ -17,10 +17,14 @@ const { Action } = require('./Action.js'); class MessageReactionAddAction extends Action { handle(data, fromStructure = false) { - if (!data.emoji) return false; + if (!data.emoji) { + return false; + } const user = this.getUserFromMember(data); - if (!user) return false; + if (!user) { + return false; + } // Verify channel const channel = this.getChannel({ @@ -30,24 +34,37 @@ class MessageReactionAddAction extends Action { ...this.spreadInjectedData(data), }); - if (!channel?.isTextBased()) return false; + if (!channel?.isTextBased()) { + return false; + } // Verify message const message = this.getMessage(data, channel); - if (!message) return false; + if (!message) { + return false; + } // Verify reaction const includePartial = this.client.options.partials.includes(Partials.Reaction); - if (message.partial && !includePartial) return false; + if (message.partial && !includePartial) { + return false; + } + const reaction = message.reactions._add({ emoji: data.emoji, count: message.partial ? null : 0, me: user.id === this.client.user.id, burst_colors: data.burst_colors, }); - if (!reaction) return false; + if (!reaction) { + return false; + } + reaction._add(user, data.burst); - if (fromStructure) return { message, reaction, user }; + if (fromStructure) { + return { message, reaction, user }; + } + /** * Provides additional information about altered reaction * diff --git a/packages/discord.js/src/client/actions/MessageReactionRemove.js b/packages/discord.js/src/client/actions/MessageReactionRemove.js index 6d4cb21f0..7756520c5 100644 --- a/packages/discord.js/src/client/actions/MessageReactionRemove.js +++ b/packages/discord.js/src/client/actions/MessageReactionRemove.js @@ -13,10 +13,14 @@ const { Action } = require('./Action.js'); class MessageReactionRemoveAction extends Action { handle(data) { - if (!data.emoji) return false; + if (!data.emoji) { + return false; + } const user = this.getUser(data); - if (!user) return false; + if (!user) { + return false; + } // Verify channel const channel = this.getChannel({ @@ -24,15 +28,22 @@ class MessageReactionRemoveAction extends Action { ...('guild_id' in data && { guild_id: data.guild_id }), user_id: data.user_id, }); - if (!channel?.isTextBased()) return false; + if (!channel?.isTextBased()) { + return false; + } // Verify message const message = this.getMessage(data, channel); - if (!message) return false; + if (!message) { + return false; + } // Verify reaction const reaction = this.getReaction(data, message, user); - if (!reaction) return false; + if (!reaction) { + return false; + } + reaction._remove(user, data.burst); /** * Emitted whenever a reaction is removed from a cached message. diff --git a/packages/discord.js/src/client/actions/MessageReactionRemoveAll.js b/packages/discord.js/src/client/actions/MessageReactionRemoveAll.js index 1338ad54b..8518931f0 100644 --- a/packages/discord.js/src/client/actions/MessageReactionRemoveAll.js +++ b/packages/discord.js/src/client/actions/MessageReactionRemoveAll.js @@ -7,11 +7,15 @@ class MessageReactionRemoveAllAction extends Action { handle(data) { // Verify channel const channel = this.getChannel({ id: data.channel_id, ...('guild_id' in data && { guild_id: data.guild_id }) }); - if (!channel?.isTextBased()) return false; + if (!channel?.isTextBased()) { + return false; + } // Verify message const message = this.getMessage(data, channel); - if (!message) return false; + if (!message) { + return false; + } // Copy removed reactions to emit for the event. const removed = message.reactions.cache.clone(); diff --git a/packages/discord.js/src/client/actions/MessageReactionRemoveEmoji.js b/packages/discord.js/src/client/actions/MessageReactionRemoveEmoji.js index 34c68af40..c5d917f83 100644 --- a/packages/discord.js/src/client/actions/MessageReactionRemoveEmoji.js +++ b/packages/discord.js/src/client/actions/MessageReactionRemoveEmoji.js @@ -6,14 +6,23 @@ const { Action } = require('./Action.js'); class MessageReactionRemoveEmojiAction extends Action { handle(data) { const channel = this.getChannel({ id: data.channel_id, ...('guild_id' in data && { guild_id: data.guild_id }) }); - if (!channel?.isTextBased()) return false; + if (!channel?.isTextBased()) { + return false; + } const message = this.getMessage(data, channel); - if (!message) return false; + if (!message) { + return false; + } const reaction = this.getReaction(data, message); - if (!reaction) return false; - if (!message.partial) message.reactions.cache.delete(reaction.emoji.id ?? reaction.emoji.name); + if (!reaction) { + return false; + } + + if (!message.partial) { + message.reactions.cache.delete(reaction.emoji.id ?? reaction.emoji.name); + } /** * Emitted when a bot removes an emoji reaction from a cached message. diff --git a/packages/discord.js/src/client/actions/MessageUpdate.js b/packages/discord.js/src/client/actions/MessageUpdate.js index ca84419af..ccfa1c0b2 100644 --- a/packages/discord.js/src/client/actions/MessageUpdate.js +++ b/packages/discord.js/src/client/actions/MessageUpdate.js @@ -6,7 +6,9 @@ class MessageUpdateAction extends Action { handle(data) { const channel = this.getChannel({ id: data.channel_id, ...('guild_id' in data && { guild_id: data.guild_id }) }); if (channel) { - if (!channel.isTextBased()) return {}; + if (!channel.isTextBased()) { + return {}; + } const { id, channel_id, guild_id, author, timestamp, type } = data; const message = this.getMessage({ id, channel_id, guild_id, author, timestamp, type }, channel); diff --git a/packages/discord.js/src/client/actions/ThreadMembersUpdate.js b/packages/discord.js/src/client/actions/ThreadMembersUpdate.js index 2e1ebf1ad..62f1ad984 100644 --- a/packages/discord.js/src/client/actions/ThreadMembersUpdate.js +++ b/packages/discord.js/src/client/actions/ThreadMembersUpdate.js @@ -20,7 +20,10 @@ class ThreadMembersUpdateAction extends Action { data.removed_member_ids?.reduce((removedMembersIds, removedMembersId) => { const threadMember = this.getThreadMember(removedMembersId, thread.members); - if (threadMember) removedMembersIds.set(threadMember.id, threadMember); + if (threadMember) { + removedMembersIds.set(threadMember.id, threadMember); + } + thread.members.cache.delete(removedMembersId); return removedMembersIds; }, removedMembers); diff --git a/packages/discord.js/src/client/actions/TypingStart.js b/packages/discord.js/src/client/actions/TypingStart.js index aa3e9a091..4a45bf3e1 100644 --- a/packages/discord.js/src/client/actions/TypingStart.js +++ b/packages/discord.js/src/client/actions/TypingStart.js @@ -7,7 +7,9 @@ const { Action } = require('./Action.js'); class TypingStartAction extends Action { handle(data) { const channel = this.getChannel({ id: data.channel_id, ...('guild_id' in data && { guild_id: data.guild_id }) }); - if (!channel) return; + if (!channel) { + return; + } if (!channel.isTextBased()) { this.client.emit(Events.Warn, `Discord sent a typing packet to a ${channel.type} channel ${channel.id}`); diff --git a/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_ACTION_EXECUTION.js b/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_ACTION_EXECUTION.js index 9ebc2c0fe..95a103eeb 100644 --- a/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_ACTION_EXECUTION.js +++ b/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_ACTION_EXECUTION.js @@ -5,7 +5,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } /** * Emitted whenever an auto moderation rule is triggered. diff --git a/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_CREATE.js b/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_CREATE.js index 666d7e1a0..4aac8f3ad 100644 --- a/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_CREATE.js +++ b/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_CREATE.js @@ -4,7 +4,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } const autoModerationRule = guild.autoModerationRules._add(data); diff --git a/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_DELETE.js b/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_DELETE.js index cec334fdd..5cb108041 100644 --- a/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_DELETE.js +++ b/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_DELETE.js @@ -4,10 +4,14 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } const autoModerationRule = guild.autoModerationRules.cache.get(data.id); - if (!autoModerationRule) return; + if (!autoModerationRule) { + return; + } guild.autoModerationRules.cache.delete(autoModerationRule.id); diff --git a/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_UPDATE.js index 681706953..33ad5ab64 100644 --- a/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/AUTO_MODERATION_RULE_UPDATE.js @@ -4,7 +4,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } const oldAutoModerationRule = guild.autoModerationRules.cache.get(data.id)?._clone() ?? null; const newAutoModerationRule = guild.autoModerationRules._add(data); diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js index 1456118a6..9cb9aabc6 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js @@ -5,7 +5,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } const auditLogEntry = new GuildAuditLogsEntry(guild, data); diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_BAN_ADD.js b/packages/discord.js/src/client/websocket/handlers/GUILD_BAN_ADD.js index d88d9c658..d15d0fa91 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_BAN_ADD.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_BAN_ADD.js @@ -4,7 +4,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } /** * Emitted whenever a member is banned from a guild. diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_BAN_REMOVE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_BAN_REMOVE.js index e0695a63f..75efc98ca 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_BAN_REMOVE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_BAN_REMOVE.js @@ -5,7 +5,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } const ban = guild.bans.cache.get(data.user.id) ?? new GuildBan(client, data, guild); diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_DELETE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_DELETE.js index 405313487..839ca7d5f 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_DELETE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_DELETE.js @@ -4,7 +4,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.id); - if (!guild) return; + if (!guild) { + return; + } if (data.unavailable) { guild.available = false; @@ -22,7 +24,10 @@ module.exports = (client, { d: data }) => { return; } - for (const channel of guild.channels.cache.values()) client.channels._remove(channel.id); + for (const channel of guild.channels.cache.values()) { + client.channels._remove(channel.id); + } + client.voice.adapters.get(data.id)?.destroy(); client.guilds.cache.delete(guild.id); diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_INTEGRATIONS_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_INTEGRATIONS_UPDATE.js index 61c391054..00b525e8b 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_INTEGRATIONS_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_INTEGRATIONS_UPDATE.js @@ -4,7 +4,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } /** * Emitted whenever a guild integration is updated diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js b/packages/discord.js/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js index 1d849e244..ee4851b91 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js @@ -5,12 +5,20 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } + const members = new Collection(); - for (const member of data.members) members.set(member.user.id, guild.members._add(member)); + for (const member of data.members) { + members.set(member.user.id, guild.members._add(member)); + } + if (data.presences) { - for (const presence of data.presences) guild.presences._add(Object.assign(presence, { guild })); + for (const presence of data.presences) { + guild.presences._add(Object.assign(presence, { guild })); + } } /** diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_ROLE_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_ROLE_UPDATE.js index e1b61e57f..11ace1d8b 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_ROLE_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_ROLE_UPDATE.js @@ -4,10 +4,14 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } const role = guild.roles.cache.get(data.role.id); - if (!role) return; + if (!role) { + return; + } const old = role._update(data.role); diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_CREATE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_CREATE.js index ecee9d5ae..8e477eced 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_CREATE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_CREATE.js @@ -4,7 +4,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } const guildScheduledEvent = guild.scheduledEvents._add(data); diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_UPDATE.js index 50c15501d..201b8bd1b 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_UPDATE.js @@ -4,7 +4,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } const oldGuildScheduledEvent = guild.scheduledEvents.cache.get(data.id)?._clone() ?? null; const newGuildScheduledEvent = guild.scheduledEvents._add(data); diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUNDS_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUNDS_UPDATE.js index 4445c2963..bc19994d2 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUNDS_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUNDS_UPDATE.js @@ -6,7 +6,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } const soundboardSounds = new Collection(); diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_CREATE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_CREATE.js index cdaf6a45b..8c328f3c5 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_CREATE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_CREATE.js @@ -5,7 +5,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } const soundboardSound = guild.soundboardSounds._add(data); diff --git a/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_UPDATE.js index 9f2aa43ee..2c6016050 100644 --- a/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/GUILD_SOUNDBOARD_SOUND_UPDATE.js @@ -5,7 +5,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } const oldGuildSoundboardSound = guild.soundboardSounds.cache.get(data.sound_id)?._clone() ?? null; const newGuildSoundboardSound = guild.soundboardSounds._add(data); diff --git a/packages/discord.js/src/client/websocket/handlers/INVITE_CREATE.js b/packages/discord.js/src/client/websocket/handlers/INVITE_CREATE.js index d3e1fc7bb..1ead7f2d3 100644 --- a/packages/discord.js/src/client/websocket/handlers/INVITE_CREATE.js +++ b/packages/discord.js/src/client/websocket/handlers/INVITE_CREATE.js @@ -5,7 +5,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const channel = client.channels.cache.get(data.channel_id); const guild = client.guilds.cache.get(data.guild_id); - if (!channel) return; + if (!channel) { + return; + } const inviteData = Object.assign(data, { channel, guild }); const invite = guild.invites._add(inviteData); diff --git a/packages/discord.js/src/client/websocket/handlers/INVITE_DELETE.js b/packages/discord.js/src/client/websocket/handlers/INVITE_DELETE.js index aa124683f..5541a25d4 100644 --- a/packages/discord.js/src/client/websocket/handlers/INVITE_DELETE.js +++ b/packages/discord.js/src/client/websocket/handlers/INVITE_DELETE.js @@ -6,7 +6,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const channel = client.channels.cache.get(data.channel_id); const guild = client.guilds.cache.get(data.guild_id); - if (!channel) return; + if (!channel) { + return; + } const inviteData = Object.assign(data, { channel, guild }); const invite = new GuildInvite(client, inviteData); diff --git a/packages/discord.js/src/client/websocket/handlers/PRESENCE_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/PRESENCE_UPDATE.js index bb1d8024e..654cedf27 100644 --- a/packages/discord.js/src/client/websocket/handlers/PRESENCE_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/PRESENCE_UPDATE.js @@ -9,12 +9,18 @@ module.exports = (client, { d: data }) => { user = client.users._add(data.user); } - if (!user) return; + if (!user) { + return; + } - if (data.user.username && !user._equals(data.user)) client.actions.UserUpdate.handle(data.user); + if (data.user.username && !user._equals(data.user)) { + client.actions.UserUpdate.handle(data.user); + } const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } const oldPresence = guild.presences.cache.get(user.id)?._clone() ?? null; diff --git a/packages/discord.js/src/client/websocket/handlers/SOUNDBOARD_SOUNDS.js b/packages/discord.js/src/client/websocket/handlers/SOUNDBOARD_SOUNDS.js index fd2e7ac94..4ef96d0ce 100644 --- a/packages/discord.js/src/client/websocket/handlers/SOUNDBOARD_SOUNDS.js +++ b/packages/discord.js/src/client/websocket/handlers/SOUNDBOARD_SOUNDS.js @@ -6,7 +6,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } const soundboardSounds = new Collection(); diff --git a/packages/discord.js/src/client/websocket/handlers/THREAD_DELETE.js b/packages/discord.js/src/client/websocket/handlers/THREAD_DELETE.js index ba4697181..b7475abb0 100644 --- a/packages/discord.js/src/client/websocket/handlers/THREAD_DELETE.js +++ b/packages/discord.js/src/client/websocket/handlers/THREAD_DELETE.js @@ -4,7 +4,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const thread = client.channels.cache.get(data.id); - if (!thread) return; + if (!thread) { + return; + } client.channels._remove(thread.id); diff --git a/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js b/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js index d92a86aa6..df9ae89d3 100644 --- a/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js +++ b/packages/discord.js/src/client/websocket/handlers/THREAD_LIST_SYNC.js @@ -5,12 +5,16 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } if (data.channel_ids) { for (const id of data.channel_ids) { const channel = client.channels.cache.get(id); - if (channel) removeStaleThreads(client, channel); + if (channel) { + removeStaleThreads(client, channel); + } } } else { for (const channel of guild.channels.cache.values()) { @@ -42,7 +46,9 @@ module.exports = (client, { d: data }) => { }; function removeStaleThreads(client, channel) { - if (!channel.threads) return; + if (!channel.threads) { + return; + } for (const thread of channel.threads.cache.values()) { if (!thread.archived) { diff --git a/packages/discord.js/src/client/websocket/handlers/THREAD_MEMBER_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/THREAD_MEMBER_UPDATE.js index 658481c37..bf9dfbfee 100644 --- a/packages/discord.js/src/client/websocket/handlers/THREAD_MEMBER_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/THREAD_MEMBER_UPDATE.js @@ -5,7 +5,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { // Discord sends the thread id as id in this object const thread = client.channels.cache.get(data.id); - if (!thread) return; + if (!thread) { + return; + } const member = thread.members.cache.get(data.user_id); if (!member) { diff --git a/packages/discord.js/src/client/websocket/handlers/VOICE_CHANNEL_EFFECT_SEND.js b/packages/discord.js/src/client/websocket/handlers/VOICE_CHANNEL_EFFECT_SEND.js index 87748880d..af9449488 100644 --- a/packages/discord.js/src/client/websocket/handlers/VOICE_CHANNEL_EFFECT_SEND.js +++ b/packages/discord.js/src/client/websocket/handlers/VOICE_CHANNEL_EFFECT_SEND.js @@ -5,7 +5,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } /** * Emitted when someone sends an effect, such as an emoji reaction, in a voice channel the client is connected to. diff --git a/packages/discord.js/src/client/websocket/handlers/VOICE_STATE_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/VOICE_STATE_UPDATE.js index fdbc5078c..195ac45d0 100644 --- a/packages/discord.js/src/client/websocket/handlers/VOICE_STATE_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/VOICE_STATE_UPDATE.js @@ -5,7 +5,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const guild = client.guilds.cache.get(data.guild_id); - if (!guild) return; + if (!guild) { + return; + } // Update the state const oldState = diff --git a/packages/discord.js/src/client/websocket/handlers/WEBHOOKS_UPDATE.js b/packages/discord.js/src/client/websocket/handlers/WEBHOOKS_UPDATE.js index 900d3b379..bc17e4d96 100644 --- a/packages/discord.js/src/client/websocket/handlers/WEBHOOKS_UPDATE.js +++ b/packages/discord.js/src/client/websocket/handlers/WEBHOOKS_UPDATE.js @@ -4,7 +4,9 @@ const { Events } = require('../../../util/Events.js'); module.exports = (client, { d: data }) => { const channel = client.channels.cache.get(data.channel_id); - if (!channel) return; + if (!channel) { + return; + } /** * Emitted whenever a channel has its webhooks changed. diff --git a/packages/discord.js/src/errors/DJSError.js b/packages/discord.js/src/errors/DJSError.js index 204bf2325..363a89983 100644 --- a/packages/discord.js/src/errors/DJSError.js +++ b/packages/discord.js/src/errors/DJSError.js @@ -34,11 +34,23 @@ function makeDiscordjsError(Base) { * @ignore */ function message(code, args) { - if (!(code in ErrorCodes)) throw new Error('Error code must be a valid DiscordjsErrorCodes'); + if (!(code in ErrorCodes)) { + throw new Error('Error code must be a valid DiscordjsErrorCodes'); + } + const msg = Messages[code]; - if (!msg) throw new Error(`No message associated with error code: ${code}.`); - if (typeof msg === 'function') return msg(...args); - if (!args?.length) return msg; + if (!msg) { + throw new Error(`No message associated with error code: ${code}.`); + } + + if (typeof msg === 'function') { + return msg(...args); + } + + if (!args?.length) { + return msg; + } + args.unshift(msg); return String(...args); } diff --git a/packages/discord.js/src/managers/ApplicationCommandManager.js b/packages/discord.js/src/managers/ApplicationCommandManager.js index cbf7672ef..c12d4961b 100644 --- a/packages/discord.js/src/managers/ApplicationCommandManager.js +++ b/packages/discord.js/src/managers/ApplicationCommandManager.js @@ -123,13 +123,19 @@ class ApplicationCommandManager extends CachedManager { * .catch(console.error) */ async fetch(options) { - if (!options) return this._fetchMany(); + if (!options) { + return this._fetchMany(); + } - if (typeof options === 'string') return this._fetchSingle({ id: options }); + if (typeof options === 'string') { + return this._fetchSingle({ id: options }); + } const { cache, force, guildId, id, locale, withLocalizations } = options; - if (id) return this._fetchSingle({ cache, force, guildId, id }); + if (id) { + return this._fetchSingle({ cache, force, guildId, id }); + } return this._fetchMany({ cache, guildId, locale, withLocalizations }); } @@ -137,7 +143,9 @@ class ApplicationCommandManager extends CachedManager { async _fetchSingle({ cache, force = false, guildId, id }) { if (!force) { const existing = this.cache.get(id); - if (existing) return existing; + if (existing) { + return existing; + } } const command = await this.client.rest.get(this.commandPath({ id, guildId })); @@ -229,7 +237,9 @@ class ApplicationCommandManager extends CachedManager { */ async edit(command, data, guildId) { const id = this.resolveId(command); - if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable'); + if (!id) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable'); + } const patched = await this.client.rest.patch(this.commandPath({ id, guildId }), { body: this.constructor.transformCommand(data), @@ -252,7 +262,9 @@ class ApplicationCommandManager extends CachedManager { */ async delete(command, guildId) { const id = this.resolveId(command); - if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable'); + if (!id) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable'); + } await this.client.rest.delete(this.commandPath({ id, guildId })); @@ -269,7 +281,9 @@ class ApplicationCommandManager extends CachedManager { * @private */ static transformCommand(command) { - if (isJSONEncodable(command)) return command.toJSON(); + if (isJSONEncodable(command)) { + return command.toJSON(); + } let default_member_permissions; diff --git a/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js b/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js index c80dfa248..18458df08 100644 --- a/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js +++ b/packages/discord.js/src/managers/ApplicationCommandPermissionsManager.js @@ -226,7 +226,9 @@ class ApplicationCommandPermissionsManager extends BaseManager { try { existingPermissions = await this.fetch({ guild: options.guildId, command: commandId }); } catch (error) { - if (error.code !== RESTJSONErrorCodes.UnknownApplicationCommandPermissions) throw error; + if (error.code !== RESTJSONErrorCodes.UnknownApplicationCommandPermissions) { + throw error; + } } const newPermissions = permissions.slice(); @@ -303,7 +305,10 @@ class ApplicationCommandPermissionsManager extends BaseManager { if (Array.isArray(users)) { for (const user of users) { const userId = this.client.users.resolveId(user); - if (!userId) throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'users', user); + if (!userId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'users', user); + } + resolvedUserIds.push(userId); } } @@ -316,9 +321,15 @@ class ApplicationCommandPermissionsManager extends BaseManager { continue; } - if (!this.guild) throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'roles'); + if (!this.guild) { + throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'roles'); + } + const roleId = this.guild.roles.resolveId(role); - if (!roleId) throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'users', role); + if (!roleId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'users', role); + } + resolvedRoleIds.push(roleId); } } @@ -331,9 +342,15 @@ class ApplicationCommandPermissionsManager extends BaseManager { continue; } - if (!this.guild) throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'channels'); + if (!this.guild) { + throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'channels'); + } + const channelId = this.guild.channels.resolveId(channel); - if (!channelId) throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'channels', channel); + if (!channelId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidElement, 'Array', 'channels', channel); + } + resolvedChannelIds.push(channelId); } } @@ -342,7 +359,9 @@ class ApplicationCommandPermissionsManager extends BaseManager { try { existing = await this.fetch({ guild: options.guildId, command: commandId }); } catch (error) { - if (error.code !== RESTJSONErrorCodes.UnknownApplicationCommandPermissions) throw error; + if (error.code !== RESTJSONErrorCodes.UnknownApplicationCommandPermissions) { + throw error; + } } const permissions = existing.filter(perm => { @@ -383,7 +402,9 @@ class ApplicationCommandPermissionsManager extends BaseManager { */ async has({ guild, command, permissionId, permissionType }) { const { guildId, commandId } = this._validateOptions(guild, command); - if (!commandId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable'); + if (!commandId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'command', 'ApplicationCommandResolvable'); + } if (!permissionId) { throw new DiscordjsTypeError( @@ -397,7 +418,10 @@ class ApplicationCommandPermissionsManager extends BaseManager { if (typeof permissionId !== 'string') { resolvedId = this.client.users.resolveId(permissionId); if (!resolvedId) { - if (!this.guild) throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'roles'); + if (!this.guild) { + throw new DiscordjsError(ErrorCodes.GuildUncachedEntityResolve, 'roles'); + } + resolvedId = this.guild.roles.resolveId(permissionId); } @@ -416,7 +440,9 @@ class ApplicationCommandPermissionsManager extends BaseManager { try { existing = await this.fetch({ guild: guildId, command: commandId }); } catch (error) { - if (error.code !== RESTJSONErrorCodes.UnknownApplicationCommandPermissions) throw error; + if (error.code !== RESTJSONErrorCodes.UnknownApplicationCommandPermissions) { + throw error; + } } // Check permission type if provided for the single edge case where a channel id is the same as the everyone role id @@ -425,7 +451,10 @@ class ApplicationCommandPermissionsManager extends BaseManager { _validateOptions(guild, command) { const guildId = this.guildId ?? this.client.guilds.resolveId(guild); - if (!guildId) throw new DiscordjsError(ErrorCodes.GlobalCommandPermissions); + if (!guildId) { + throw new DiscordjsError(ErrorCodes.GlobalCommandPermissions); + } + let commandId = this.commandId; if (command && !commandId) { commandId = this.manager.resolveId?.(command); diff --git a/packages/discord.js/src/managers/ApplicationEmojiManager.js b/packages/discord.js/src/managers/ApplicationEmojiManager.js index 97f058da7..005ec3b4f 100644 --- a/packages/discord.js/src/managers/ApplicationEmojiManager.js +++ b/packages/discord.js/src/managers/ApplicationEmojiManager.js @@ -54,7 +54,9 @@ class ApplicationEmojiManager extends CachedManager { */ async create({ attachment, name }) { const image = await resolveImage(attachment); - if (!image) throw new DiscordjsTypeError(ErrorCodes.ReqResourceType); + if (!image) { + throw new DiscordjsTypeError(ErrorCodes.ReqResourceType); + } const body = { image, name }; @@ -83,7 +85,9 @@ class ApplicationEmojiManager extends CachedManager { if (id) { if (!force) { const existing = this.cache.get(id); - if (existing) return existing; + if (existing) { + return existing; + } } const emoji = await this.client.rest.get(Routes.applicationEmoji(this.application.id, id)); @@ -92,7 +96,10 @@ class ApplicationEmojiManager extends CachedManager { const { items: data } = await this.client.rest.get(Routes.applicationEmojis(this.application.id)); const emojis = new Collection(); - for (const emoji of data) emojis.set(emoji.id, this._add(emoji, cache)); + for (const emoji of data) { + emojis.set(emoji.id, this._add(emoji, cache)); + } + return emojis; } @@ -104,7 +111,10 @@ class ApplicationEmojiManager extends CachedManager { */ async delete(emoji) { const id = this.resolveId(emoji); - if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true); + if (!id) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true); + } + await this.client.rest.delete(Routes.applicationEmoji(this.application.id, id)); } @@ -117,7 +127,9 @@ class ApplicationEmojiManager extends CachedManager { */ async edit(emoji, options) { const id = this.resolveId(emoji); - if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true); + if (!id) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true); + } const newData = await this.client.rest.patch(Routes.applicationEmoji(this.application.id, id), { body: { @@ -141,7 +153,9 @@ class ApplicationEmojiManager extends CachedManager { */ async fetchAuthor(emoji) { const id = this.resolveId(emoji); - if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true); + if (!id) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true); + } const data = await this.client.rest.get(Routes.applicationEmoji(this.application.id, id)); diff --git a/packages/discord.js/src/managers/AutoModerationRuleManager.js b/packages/discord.js/src/managers/AutoModerationRuleManager.js index c19414e4d..070c4b078 100644 --- a/packages/discord.js/src/managers/AutoModerationRuleManager.js +++ b/packages/discord.js/src/managers/AutoModerationRuleManager.js @@ -265,7 +265,10 @@ class AutoModerationRuleManager extends CachedManager { * .catch(console.error) */ async fetch(options) { - if (!options) return this._fetchMany(); + if (!options) { + return this._fetchMany(); + } + const { autoModerationRule, cache, force } = options; const resolvedAutoModerationRule = this.resolveId(autoModerationRule ?? options); if (resolvedAutoModerationRule) { @@ -278,7 +281,9 @@ class AutoModerationRuleManager extends CachedManager { async _fetchSingle({ autoModerationRule, cache, force = false }) { if (!force) { const existing = this.cache.get(autoModerationRule); - if (existing) return existing; + if (existing) { + return existing; + } } const data = await this.client.rest.get(Routes.guildAutoModerationRule(this.guild.id, autoModerationRule)); diff --git a/packages/discord.js/src/managers/CachedManager.js b/packages/discord.js/src/managers/CachedManager.js index 6a7959707..e0e291d7d 100644 --- a/packages/discord.js/src/managers/CachedManager.js +++ b/packages/discord.js/src/managers/CachedManager.js @@ -60,7 +60,10 @@ class CachedManager extends DataManager { } const entry = this.holds ? new this.holds(this.client, data, ...extras) : data; - if (cache) this.cache.set(id ?? entry.id, entry); + if (cache) { + this.cache.set(id ?? entry.id, entry); + } + return entry; } } diff --git a/packages/discord.js/src/managers/ChannelManager.js b/packages/discord.js/src/managers/ChannelManager.js index b1d3a183a..4d04e06ab 100644 --- a/packages/discord.js/src/managers/ChannelManager.js +++ b/packages/discord.js/src/managers/ChannelManager.js @@ -45,7 +45,10 @@ class ChannelManager extends CachedManager { _add(data, guild, { cache = true, allowUnknownGuild = false } = {}) { const existing = this.cache.get(data.id); if (existing) { - if (cache) existing._patch(data); + if (cache) { + existing._patch(data); + } + guild?.channels?._add(existing); if (ThreadChannelTypes.includes(existing.type)) { existing.parent?.threads?._add(existing); @@ -61,7 +64,9 @@ class ChannelManager extends CachedManager { return null; } - if (cache && !allowUnknownGuild) this.cache.set(channel.id, channel); + if (cache && !allowUnknownGuild) { + this.cache.set(channel.id, channel); + } return channel; } @@ -71,7 +76,9 @@ class ChannelManager extends CachedManager { channel?.guild?.channels.cache.delete(id); for (const [code, invite] of channel?.guild?.invites.cache ?? []) { - if (invite.channelId === id) channel.guild.invites.cache.delete(code); + if (invite.channelId === id) { + channel.guild.invites.cache.delete(code); + } } channel?.parent?.threads?.cache.delete(id); @@ -136,7 +143,9 @@ class ChannelManager extends CachedManager { async fetch(id, { allowUnknownGuild = false, cache = true, force = false } = {}) { if (!force) { const existing = this.cache.get(id); - if (existing && !existing.partial) return existing; + if (existing && !existing.partial) { + return existing; + } } const data = await this.client.rest.get(Routes.channel(id)); diff --git a/packages/discord.js/src/managers/DataManager.js b/packages/discord.js/src/managers/DataManager.js index 2321d67da..93724dae4 100644 --- a/packages/discord.js/src/managers/DataManager.js +++ b/packages/discord.js/src/managers/DataManager.js @@ -41,8 +41,14 @@ class DataManager extends BaseManager { * @returns {?Object} An instance from this Manager */ resolve(idOrInstance) { - if (idOrInstance instanceof this.holds) return idOrInstance; - if (typeof idOrInstance === 'string') return this.cache.get(idOrInstance) ?? null; + if (idOrInstance instanceof this.holds) { + return idOrInstance; + } + + if (typeof idOrInstance === 'string') { + return this.cache.get(idOrInstance) ?? null; + } + return null; } @@ -53,8 +59,14 @@ class DataManager extends BaseManager { * @returns {?Snowflake} */ resolveId(idOrInstance) { - if (idOrInstance instanceof this.holds) return idOrInstance.id; - if (typeof idOrInstance === 'string') return idOrInstance; + if (idOrInstance instanceof this.holds) { + return idOrInstance.id; + } + + if (typeof idOrInstance === 'string') { + return idOrInstance; + } + return null; } diff --git a/packages/discord.js/src/managers/EntitlementManager.js b/packages/discord.js/src/managers/EntitlementManager.js index 70cd518f9..0d2bc715a 100644 --- a/packages/discord.js/src/managers/EntitlementManager.js +++ b/packages/discord.js/src/managers/EntitlementManager.js @@ -72,7 +72,10 @@ class EntitlementManager extends CachedManager { * @returns {Promise>} */ async fetch(options) { - if (!options) return this._fetchMany(options); + if (!options) { + return this._fetchMany(options); + } + const { entitlement, cache, force } = options; const resolvedEntitlement = this.resolveId(entitlement ?? options); @@ -134,7 +137,9 @@ class EntitlementManager extends CachedManager { */ async createTest({ sku, guild, user }) { const skuId = resolveSKUId(sku); - if (!skuId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sku', 'SKUResolvable'); + if (!skuId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sku', 'SKUResolvable'); + } if ((guild && user) || (!guild && !user)) { throw new DiscordjsTypeError(ErrorCodes.EntitlementCreateInvalidOwner); @@ -165,7 +170,9 @@ class EntitlementManager extends CachedManager { */ async deleteTest(entitlement) { const resolved = this.resolveId(entitlement); - if (!resolved) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'entitlement', 'EntitlementResolvable'); + if (!resolved) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'entitlement', 'EntitlementResolvable'); + } await this.client.rest.delete(Routes.entitlement(this.client.application.id, resolved)); } diff --git a/packages/discord.js/src/managers/GuildBanManager.js b/packages/discord.js/src/managers/GuildBanManager.js index 4abb65a75..99ff5421d 100644 --- a/packages/discord.js/src/managers/GuildBanManager.js +++ b/packages/discord.js/src/managers/GuildBanManager.js @@ -102,10 +102,15 @@ class GuildBanManager extends CachedManager { * .catch(console.error); */ async fetch(options) { - if (!options) return this._fetchMany(); + if (!options) { + return this._fetchMany(); + } + const { user, cache, force, limit, before, after } = options; const resolvedUser = this.client.users.resolveId(user ?? options); - if (resolvedUser) return this._fetchSingle({ user: resolvedUser, cache, force }); + if (resolvedUser) { + return this._fetchSingle({ user: resolvedUser, cache, force }); + } if (!before && !after && !limit && cache === undefined) { throw new DiscordjsError(ErrorCodes.FetchBanResolveId); @@ -117,7 +122,9 @@ class GuildBanManager extends CachedManager { async _fetchSingle({ user, cache, force = false }) { if (!force) { const existing = this.cache.get(user); - if (existing && !existing.partial) return existing; + if (existing && !existing.partial) { + return existing; + } } const data = await this.client.rest.get(Routes.guildBan(this.guild.id, user)); @@ -152,9 +159,14 @@ class GuildBanManager extends CachedManager { * await guild.bans.create('84484653687267328'); */ async create(user, options = {}) { - if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); + if (typeof options !== 'object') { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); + } + const id = this.client.users.resolveId(user); - if (!id) throw new DiscordjsError(ErrorCodes.BanResolveId, true); + if (!id) { + throw new DiscordjsError(ErrorCodes.BanResolveId, true); + } await this.client.rest.put(Routes.guildBan(this.guild.id, id), { body: { @@ -176,7 +188,10 @@ class GuildBanManager extends CachedManager { */ async remove(user, reason) { const id = this.client.users.resolveId(user); - if (!id) throw new DiscordjsError(ErrorCodes.BanResolveId); + if (!id) { + throw new DiscordjsError(ErrorCodes.BanResolveId); + } + await this.client.rest.delete(Routes.guildBan(this.guild.id, id), { reason }); } @@ -208,10 +223,14 @@ class GuildBanManager extends CachedManager { throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'users', 'Array or Collection of UserResolvable', true); } - if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); + if (typeof options !== 'object') { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); + } const userIds = users.map(user => this.client.users.resolveId(user)); - if (userIds.length === 0) throw new DiscordjsError(ErrorCodes.BulkBanUsersOptionEmpty); + if (userIds.length === 0) { + throw new DiscordjsError(ErrorCodes.BulkBanUsersOptionEmpty); + } const result = await this.client.rest.post(Routes.guildBulkBan(this.guild.id), { body: { delete_message_seconds: options.deleteMessageSeconds, user_ids: userIds }, diff --git a/packages/discord.js/src/managers/GuildChannelManager.js b/packages/discord.js/src/managers/GuildChannelManager.js index 628f0603b..8b4c40424 100644 --- a/packages/discord.js/src/managers/GuildChannelManager.js +++ b/packages/discord.js/src/managers/GuildChannelManager.js @@ -55,7 +55,10 @@ class GuildChannelManager extends CachedManager { */ get channelCountWithoutThreads() { return this.cache.reduce((acc, channel) => { - if (ThreadChannelTypes.includes(channel.type)) return acc; + if (ThreadChannelTypes.includes(channel.type)) { + return acc; + } + return acc + 1; }, 0); } @@ -69,7 +72,10 @@ class GuildChannelManager extends CachedManager { _add(channel) { const existing = this.cache.get(channel.id); - if (existing) return existing; + if (existing) { + return existing; + } + this.cache.set(channel.id, channel); return channel; } @@ -90,7 +96,10 @@ class GuildChannelManager extends CachedManager { * @returns {?(GuildChannel|ThreadChannel)} */ resolve(channel) { - if (channel instanceof ThreadChannel) return super.cache.get(channel.id) ?? null; + if (channel instanceof ThreadChannel) { + return super.cache.get(channel.id) ?? null; + } + return super.resolve(channel); } @@ -101,7 +110,10 @@ class GuildChannelManager extends CachedManager { * @returns {?Snowflake} */ resolveId(channel) { - if (channel instanceof ThreadChannel) return super.resolveId(channel.id); + if (channel instanceof ThreadChannel) { + return super.resolveId(channel.id); + } + return super.resolveId(channel); } @@ -250,7 +262,9 @@ class GuildChannelManager extends CachedManager { */ async createWebhook({ channel, name, avatar, reason }) { const channelId = this.resolveId(channel); - if (!channelId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable'); + if (!channelId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable'); + } const resolvedAvatar = await resolveImage(avatar); @@ -309,7 +323,9 @@ class GuildChannelManager extends CachedManager { */ async edit(channel, options) { const resolvedChannel = this.resolve(channel); - if (!resolvedChannel) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable'); + if (!resolvedChannel) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable'); + } const parentId = options.parent && this.client.channels.resolveId(options.parent); @@ -380,7 +396,9 @@ class GuildChannelManager extends CachedManager { */ async setPosition(channel, position, { relative, reason } = {}) { const resolvedChannel = this.resolve(channel); - if (!resolvedChannel) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable'); + if (!resolvedChannel) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable'); + } const updatedChannels = await setPosition( resolvedChannel, @@ -420,19 +438,27 @@ class GuildChannelManager extends CachedManager { async fetch(id, { cache = true, force = false } = {}) { if (id && !force) { const existing = this.cache.get(id); - if (existing) return existing; + if (existing) { + return existing; + } } if (id) { const innerData = await this.client.rest.get(Routes.channel(id)); // Since this is the guild manager, throw if on a different guild - if (this.guild.id !== innerData.guild_id) throw new DiscordjsError(ErrorCodes.GuildChannelUnowned); + if (this.guild.id !== innerData.guild_id) { + throw new DiscordjsError(ErrorCodes.GuildChannelUnowned); + } + return this.client.channels._add(innerData, this.guild, { cache }); } const data = await this.client.rest.get(Routes.guildChannels(this.guild.id)); const channels = new Collection(); - for (const channel of data) channels.set(channel.id, this.client.channels._add(channel, this.guild, { cache })); + for (const channel of data) { + channels.set(channel.id, this.client.channels._add(channel, this.guild, { cache })); + } + return channels; } @@ -449,7 +475,10 @@ class GuildChannelManager extends CachedManager { */ async fetchWebhooks(channel) { const id = this.resolveId(channel); - if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable'); + if (!id) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable'); + } + const data = await this.client.rest.get(Routes.channelWebhooks(id)); return data.reduce((hooks, hook) => hooks.set(hook.id, new Webhook(this.client, hook)), new Collection()); } @@ -547,7 +576,10 @@ class GuildChannelManager extends CachedManager { */ async delete(channel, reason) { const id = this.resolveId(channel); - if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable'); + if (!id) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'channel', 'GuildChannelResolvable'); + } + await this.client.rest.delete(Routes.channel(id), { reason }); this.client.actions.ChannelDelete.handle({ id }); } diff --git a/packages/discord.js/src/managers/GuildEmojiManager.js b/packages/discord.js/src/managers/GuildEmojiManager.js index 83ef0e490..ce1cbdbe5 100644 --- a/packages/discord.js/src/managers/GuildEmojiManager.js +++ b/packages/discord.js/src/managers/GuildEmojiManager.js @@ -54,8 +54,14 @@ class GuildEmojiManager extends CachedManager { * @returns {?GuildEmoji} */ resolve(emoji) { - if (emoji instanceof ReactionEmoji) return super.cache.get(emoji.id) ?? null; - if (emoji instanceof ApplicationEmoji) return super.cache.get(emoji.id) ?? null; + if (emoji instanceof ReactionEmoji) { + return super.cache.get(emoji.id) ?? null; + } + + if (emoji instanceof ApplicationEmoji) { + return super.cache.get(emoji.id) ?? null; + } + return super.resolve(emoji); } @@ -66,8 +72,14 @@ class GuildEmojiManager extends CachedManager { * @returns {?Snowflake} */ resolveId(emoji) { - if (emoji instanceof ReactionEmoji) return emoji.id; - if (emoji instanceof ApplicationEmoji) return emoji.id; + if (emoji instanceof ReactionEmoji) { + return emoji.id; + } + + if (emoji instanceof ApplicationEmoji) { + return emoji.id; + } + return super.resolveId(emoji); } @@ -88,9 +100,18 @@ class GuildEmojiManager extends CachedManager { */ resolveIdentifier(emoji) { const emojiResolvable = this.resolve(emoji); - if (emojiResolvable) return emojiResolvable.identifier; - if (emoji instanceof ReactionEmoji) return emoji.identifier; - if (emoji instanceof ApplicationEmoji) return emoji.identifier; + if (emojiResolvable) { + return emojiResolvable.identifier; + } + + if (emoji instanceof ReactionEmoji) { + return emoji.identifier; + } + + if (emoji instanceof ApplicationEmoji) { + return emoji.identifier; + } + if (typeof emoji === 'string') { const res = parseEmoji(emoji); let identifier = emoji; @@ -98,7 +119,10 @@ class GuildEmojiManager extends CachedManager { identifier = `${res.animated ? 'a:' : ''}${res.name}${res.id ? `:${res.id}` : ''}`; } - if (!identifier.includes('%')) return encodeURIComponent(identifier); + if (!identifier.includes('%')) { + return encodeURIComponent(identifier); + } + return identifier; } @@ -133,7 +157,9 @@ class GuildEmojiManager extends CachedManager { */ async create({ attachment, name, roles, reason }) { const image = await resolveImage(attachment); - if (!image) throw new DiscordjsTypeError(ErrorCodes.ReqResourceType); + if (!image) { + throw new DiscordjsTypeError(ErrorCodes.ReqResourceType); + } const body = { image, name }; if (roles) { @@ -182,7 +208,9 @@ class GuildEmojiManager extends CachedManager { if (id) { if (!force) { const existing = this.cache.get(id); - if (existing) return existing; + if (existing) { + return existing; + } } const emoji = await this.client.rest.get(Routes.guildEmoji(this.guild.id, id)); @@ -191,7 +219,10 @@ class GuildEmojiManager extends CachedManager { const data = await this.client.rest.get(Routes.guildEmojis(this.guild.id)); const emojis = new Collection(); - for (const emoji of data) emojis.set(emoji.id, this._add(emoji, cache)); + for (const emoji of data) { + emojis.set(emoji.id, this._add(emoji, cache)); + } + return emojis; } @@ -204,7 +235,10 @@ class GuildEmojiManager extends CachedManager { */ async delete(emoji, reason) { const id = this.resolveId(emoji); - if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true); + if (!id) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true); + } + await this.client.rest.delete(Routes.guildEmoji(this.guild.id, id), { reason }); } @@ -217,7 +251,10 @@ class GuildEmojiManager extends CachedManager { */ async edit(emoji, options) { const id = this.resolveId(emoji); - if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true); + if (!id) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true); + } + const roles = options.roles?.map(role => this.guild.roles.resolveId(role)); const newData = await this.client.rest.patch(Routes.guildEmoji(this.guild.id, id), { body: { @@ -244,13 +281,19 @@ class GuildEmojiManager extends CachedManager { */ async fetchAuthor(emoji) { const resolvedEmoji = this.resolve(emoji); - if (!resolvedEmoji) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true); + if (!resolvedEmoji) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'emoji', 'EmojiResolvable', true); + } + if (resolvedEmoji.managed) { throw new DiscordjsError(ErrorCodes.EmojiManaged); } const { me } = this.guild.members; - if (!me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe); + if (!me) { + throw new DiscordjsError(ErrorCodes.GuildUncachedMe); + } + if (!me.permissions.has(PermissionFlagsBits.ManageGuildExpressions)) { throw new DiscordjsError(ErrorCodes.MissingManageGuildExpressionsPermission, this.guild); } diff --git a/packages/discord.js/src/managers/GuildInviteManager.js b/packages/discord.js/src/managers/GuildInviteManager.js index 960dbf364..d99f94b0e 100644 --- a/packages/discord.js/src/managers/GuildInviteManager.js +++ b/packages/discord.js/src/managers/GuildInviteManager.js @@ -142,21 +142,33 @@ class GuildInviteManager extends CachedManager { * .catch(console.error); */ async fetch(options) { - if (!options) return this._fetchMany(); + if (!options) { + return this._fetchMany(); + } + if (typeof options === 'string') { const code = resolveInviteCode(options); - if (!code) throw new DiscordjsError(ErrorCodes.InviteResolveCode); + if (!code) { + throw new DiscordjsError(ErrorCodes.InviteResolveCode); + } + return this._fetchSingle({ code, cache: true }); } if (!options.code) { if (options.channelId) { const id = this.guild.channels.resolveId(options.channelId); - if (!id) throw new DiscordjsError(ErrorCodes.GuildChannelResolve); + if (!id) { + throw new DiscordjsError(ErrorCodes.GuildChannelResolve); + } + return this._fetchChannelMany(id, options.cache); } - if ('cache' in options) return this._fetchMany(options.cache); + if ('cache' in options) { + return this._fetchMany(options.cache); + } + throw new DiscordjsError(ErrorCodes.InviteResolveCode); } @@ -169,12 +181,17 @@ class GuildInviteManager extends CachedManager { async _fetchSingle({ code, cache, force = false }) { if (!force) { const existing = this.cache.get(code); - if (existing) return existing; + if (existing) { + return existing; + } } const invites = await this._fetchMany(cache); const invite = invites.get(code); - if (!invite) throw new DiscordjsError(ErrorCodes.InviteNotFound); + if (!invite) { + throw new DiscordjsError(ErrorCodes.InviteNotFound); + } + return invite; } @@ -205,7 +222,9 @@ class GuildInviteManager extends CachedManager { { temporary, maxAge, maxUses, unique, targetUser, targetApplication, targetType, reason } = {}, ) { const id = this.guild.channels.resolveId(channel); - if (!id) throw new DiscordjsError(ErrorCodes.GuildChannelResolve); + if (!id) { + throw new DiscordjsError(ErrorCodes.GuildChannelResolve); + } const invite = await this.client.rest.post(Routes.channelInvites(id), { body: { diff --git a/packages/discord.js/src/managers/GuildManager.js b/packages/discord.js/src/managers/GuildManager.js index 573429464..35e0289fc 100644 --- a/packages/discord.js/src/managers/GuildManager.js +++ b/packages/discord.js/src/managers/GuildManager.js @@ -131,7 +131,9 @@ class GuildManager extends CachedManager { if (id) { if (!options.force) { const existing = this.cache.get(id); - if (existing) return existing; + if (existing) { + return existing; + } } const innerData = await this.client.rest.get(Routes.guild(id), { @@ -187,7 +189,9 @@ class GuildManager extends CachedManager { // eslint-disable-next-line no-use-before-define timeout.refresh(); - if (!remainingGuildIds.has(guild.id)) return; + if (!remainingGuildIds.has(guild.id)) { + return; + } fetchedSoundboardSounds.set(guild.id, soundboardSounds); diff --git a/packages/discord.js/src/managers/GuildMemberManager.js b/packages/discord.js/src/managers/GuildMemberManager.js index 5e1ad76b0..d90f1c4ae 100644 --- a/packages/discord.js/src/managers/GuildMemberManager.js +++ b/packages/discord.js/src/managers/GuildMemberManager.js @@ -51,9 +51,15 @@ class GuildMemberManager extends CachedManager { */ resolve(member) { const memberResolvable = super.resolve(member); - if (memberResolvable) return memberResolvable; + if (memberResolvable) { + return memberResolvable; + } + const userResolvable = this.client.users.resolveId(member); - if (userResolvable) return super.cache.get(userResolvable) ?? null; + if (userResolvable) { + return super.cache.get(userResolvable) ?? null; + } + return null; } @@ -65,7 +71,10 @@ class GuildMemberManager extends CachedManager { */ resolveId(member) { const memberResolvable = super.resolveId(member); - if (memberResolvable) return memberResolvable; + if (memberResolvable) { + return memberResolvable; + } + const userResolvable = this.client.users.resolveId(member); return this.cache.has(userResolvable) ? userResolvable : null; } @@ -98,10 +107,15 @@ class GuildMemberManager extends CachedManager { */ async add(user, options) { const userId = this.client.users.resolveId(user); - if (!userId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable'); + if (!userId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable'); + } + if (!options.force) { const cachedUser = this.cache.get(userId); - if (cachedUser) return cachedUser; + if (cachedUser) { + return cachedUser; + } } const resolvedOptions = { @@ -215,10 +229,16 @@ class GuildMemberManager extends CachedManager { * .catch(console.error); */ async fetch(options) { - if (!options) return this._fetchMany(); + if (!options) { + return this._fetchMany(); + } + const { user: users, limit, withPresences, cache, force } = options; const resolvedUser = this.client.users.resolveId(users ?? options); - if (resolvedUser && !limit && !withPresences) return this._fetchSingle({ user: resolvedUser, cache, force }); + if (resolvedUser && !limit && !withPresences) { + return this._fetchSingle({ user: resolvedUser, cache, force }); + } + const resolvedUsers = users?.map?.(user => this.client.users.resolveId(user)) ?? resolvedUser ?? undefined; return this._fetchMany({ ...options, users: resolvedUsers }); } @@ -226,7 +246,9 @@ class GuildMemberManager extends CachedManager { async _fetchSingle({ user, cache, force = false }) { if (!force) { const existing = this.cache.get(user); - if (existing && !existing.partial) return existing; + if (existing && !existing.partial) { + return existing; + } } const data = await this.client.rest.get(Routes.guildMember(this.guild.id, user)); @@ -241,7 +263,9 @@ class GuildMemberManager extends CachedManager { time = 120e3, 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 : ''); @@ -261,7 +285,9 @@ class GuildMemberManager extends CachedManager { const fetchedMembers = new Collection(); let index = 0; const handler = (members, _, chunk) => { - if (chunk.nonce !== nonce) return; + if (chunk.nonce !== nonce) { + return; + } // eslint-disable-next-line no-use-before-define timeout.refresh(); @@ -367,7 +393,9 @@ class GuildMemberManager extends CachedManager { */ async edit(user, { reason, ...options }) { const id = this.client.users.resolveId(user); - if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable'); + if (!id) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable'); + } if (options.channel) { options.channel = this.guild.channels.resolve(options.channel); @@ -469,7 +497,9 @@ class GuildMemberManager extends CachedManager { * .catch(console.error); */ async prune({ days, dry = false, count: compute_prune_count, roles = [], reason } = {}) { - if (typeof days !== 'number') throw new DiscordjsTypeError(ErrorCodes.PruneDaysType); + if (typeof days !== 'number') { + throw new DiscordjsTypeError(ErrorCodes.PruneDaysType); + } const query = { days }; const resolvedRoles = []; @@ -509,7 +539,9 @@ class GuildMemberManager extends CachedManager { */ async kick(user, reason) { const id = this.client.users.resolveId(user); - if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable'); + if (!id) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable'); + } await this.client.rest.delete(Routes.guildMember(this.guild.id, id), { reason }); } diff --git a/packages/discord.js/src/managers/GuildMemberRoleManager.js b/packages/discord.js/src/managers/GuildMemberRoleManager.js index 609ed43ed..043f50bb2 100644 --- a/packages/discord.js/src/managers/GuildMemberRoleManager.js +++ b/packages/discord.js/src/managers/GuildMemberRoleManager.js @@ -49,7 +49,10 @@ class GuildMemberRoleManager extends DataManager { */ get hoist() { const hoistedRoles = this.cache.filter(role => role.hoist); - if (!hoistedRoles.size) return null; + if (!hoistedRoles.size) { + return null; + } + return hoistedRoles.reduce((prev, role) => (role.comparePositionTo(prev) > 0 ? role : prev)); } @@ -61,7 +64,10 @@ class GuildMemberRoleManager extends DataManager { */ get icon() { const iconRoles = this.cache.filter(role => role.icon ?? role.unicodeEmoji); - if (!iconRoles.size) return null; + if (!iconRoles.size) { + return null; + } + return iconRoles.reduce((prev, role) => (role.comparePositionTo(prev) > 0 ? role : prev)); } @@ -73,7 +79,10 @@ class GuildMemberRoleManager extends DataManager { */ get color() { const coloredRoles = this.cache.filter(role => role.colors.primaryColor); - if (!coloredRoles.size) return null; + if (!coloredRoles.size) { + return null; + } + return coloredRoles.reduce((prev, role) => (role.comparePositionTo(prev) > 0 ? role : prev)); } @@ -105,7 +114,10 @@ class GuildMemberRoleManager extends DataManager { * @readonly */ get botRole() { - if (!this.member.user.bot) return null; + if (!this.member.user.bot) { + return null; + } + return this.cache.find(role => role.tags?.botId === this.member.user.id) ?? null; } diff --git a/packages/discord.js/src/managers/GuildMessageManager.js b/packages/discord.js/src/managers/GuildMessageManager.js index 3a9f17c5d..ea2ce6876 100644 --- a/packages/discord.js/src/managers/GuildMessageManager.js +++ b/packages/discord.js/src/managers/GuildMessageManager.js @@ -25,7 +25,9 @@ class GuildMessageManager extends MessageManager { */ async crosspost(message) { const messageId = this.resolveId(message); - if (!messageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable'); + if (!messageId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable'); + } const data = await this.client.rest.post(Routes.channelMessageCrosspost(this.channel.id, messageId)); return this.cache.get(data.id) ?? this._add(data); diff --git a/packages/discord.js/src/managers/GuildScheduledEventManager.js b/packages/discord.js/src/managers/GuildScheduledEventManager.js index fb5b3db49..b5b703490 100644 --- a/packages/discord.js/src/managers/GuildScheduledEventManager.js +++ b/packages/discord.js/src/managers/GuildScheduledEventManager.js @@ -92,7 +92,10 @@ class GuildScheduledEventManager extends CachedManager { * @returns {Promise} */ async create(options) { - if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); + if (typeof options !== 'object') { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); + } + const { privacyLevel, entityType, @@ -114,7 +117,10 @@ class GuildScheduledEventManager extends CachedManager { entity_metadata = { location: entityMetadata?.location }; } else { channel_id = this.guild.channels.resolveId(channel); - if (!channel_id) throw new DiscordjsError(ErrorCodes.GuildVoiceChannelResolve); + if (!channel_id) { + throw new DiscordjsError(ErrorCodes.GuildVoiceChannelResolve); + } + entity_metadata = entityMetadata === undefined ? entityMetadata : null; } @@ -167,7 +173,9 @@ class GuildScheduledEventManager extends CachedManager { if (id) { if (!options.force) { const existing = this.cache.get(id); - if (existing) return existing; + if (existing) { + return existing; + } } const innerData = await this.client.rest.get(Routes.guildScheduledEvent(this.guild.id, id), { @@ -218,9 +226,14 @@ class GuildScheduledEventManager extends CachedManager { */ async edit(guildScheduledEvent, options) { const guildScheduledEventId = this.resolveId(guildScheduledEvent); - if (!guildScheduledEventId) throw new DiscordjsError(ErrorCodes.GuildScheduledEventResolve); + if (!guildScheduledEventId) { + throw new DiscordjsError(ErrorCodes.GuildScheduledEventResolve); + } + + if (typeof options !== 'object') { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); + } - if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); const { privacyLevel, entityType, @@ -271,7 +284,9 @@ class GuildScheduledEventManager extends CachedManager { */ async delete(guildScheduledEvent) { const guildScheduledEventId = this.resolveId(guildScheduledEvent); - if (!guildScheduledEventId) throw new DiscordjsError(ErrorCodes.GuildScheduledEventResolve); + if (!guildScheduledEventId) { + throw new DiscordjsError(ErrorCodes.GuildScheduledEventResolve); + } await this.client.rest.delete(Routes.guildScheduledEvent(this.guild.id, guildScheduledEventId)); } @@ -305,7 +320,9 @@ class GuildScheduledEventManager extends CachedManager { */ async fetchSubscribers(guildScheduledEvent, options = {}) { const guildScheduledEventId = this.resolveId(guildScheduledEvent); - if (!guildScheduledEventId) throw new DiscordjsError(ErrorCodes.GuildScheduledEventResolve); + if (!guildScheduledEventId) { + throw new DiscordjsError(ErrorCodes.GuildScheduledEventResolve); + } const query = makeURLSearchParams({ limit: options.limit, diff --git a/packages/discord.js/src/managers/GuildSoundboardSoundManager.js b/packages/discord.js/src/managers/GuildSoundboardSoundManager.js index c5027c0fb..0458db732 100644 --- a/packages/discord.js/src/managers/GuildSoundboardSoundManager.js +++ b/packages/discord.js/src/managers/GuildSoundboardSoundManager.js @@ -63,8 +63,14 @@ class GuildSoundboardSoundManager extends CachedManager { * @returns {?Snowflake} */ resolveId(soundboardSound) { - if (soundboardSound instanceof this.holds) return soundboardSound.soundId; - if (typeof soundboardSound === 'string') return soundboardSound; + if (soundboardSound instanceof this.holds) { + return soundboardSound.soundId; + } + + if (typeof soundboardSound === 'string') { + return soundboardSound; + } + return null; } @@ -130,7 +136,9 @@ class GuildSoundboardSoundManager extends CachedManager { async edit(soundboardSound, options = {}) { const soundId = this.resolveId(soundboardSound); - if (!soundId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'soundboardSound', 'SoundboardSoundResolvable'); + if (!soundId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'soundboardSound', 'SoundboardSoundResolvable'); + } const { emojiId, emojiName, name, reason, volume } = options; @@ -163,7 +171,9 @@ class GuildSoundboardSoundManager extends CachedManager { async delete(soundboardSound, reason) { const soundId = this.resolveId(soundboardSound); - if (!soundId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'soundboardSound', 'SoundboardSoundResolvable'); + if (!soundId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'soundboardSound', 'SoundboardSoundResolvable'); + } await this.client.rest.delete(Routes.guildSoundboardSound(this.guild.id, soundId), { reason }); } @@ -199,17 +209,25 @@ class GuildSoundboardSoundManager extends CachedManager { * .catch(console.error); */ async fetch(options) { - if (!options) return this._fetchMany(); + if (!options) { + return this._fetchMany(); + } + const { cache, force, soundboardSound } = options; const resolvedSoundboardSound = this.resolveId(soundboardSound ?? options); - if (resolvedSoundboardSound) return this._fetchSingle({ cache, force, soundboardSound: resolvedSoundboardSound }); + if (resolvedSoundboardSound) { + return this._fetchSingle({ cache, force, soundboardSound: resolvedSoundboardSound }); + } + return this._fetchMany({ cache }); } async _fetchSingle({ cache, force, soundboardSound } = {}) { if (!force) { const existing = this.cache.get(soundboardSound); - if (existing) return existing; + if (existing) { + return existing; + } } const data = await this.client.rest.get(Routes.guildSoundboardSound(this.guild.id, soundboardSound)); diff --git a/packages/discord.js/src/managers/GuildStickerManager.js b/packages/discord.js/src/managers/GuildStickerManager.js index e8bd50f76..367be2694 100644 --- a/packages/discord.js/src/managers/GuildStickerManager.js +++ b/packages/discord.js/src/managers/GuildStickerManager.js @@ -114,7 +114,9 @@ class GuildStickerManager extends CachedManager { */ async edit(sticker, options = {}) { const stickerId = this.resolveId(sticker); - if (!stickerId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable'); + if (!stickerId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sticker', 'StickerResolvable'); + } const data = await this.client.rest.patch(Routes.guildSticker(this.guild.id, stickerId), { body: options, @@ -140,7 +142,9 @@ class GuildStickerManager extends CachedManager { */ async delete(sticker, reason) { const resolvedStickerId = this.resolveId(sticker); - if (!resolvedStickerId) 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, resolvedStickerId), { reason }); } @@ -166,7 +170,9 @@ class GuildStickerManager extends CachedManager { if (id) { if (!force) { const existing = this.cache.get(id); - if (existing) return existing; + if (existing) { + return existing; + } } const sticker = await this.client.rest.get(Routes.guildSticker(this.guild.id, id)); @@ -185,7 +191,10 @@ class GuildStickerManager extends CachedManager { */ async fetchUser(sticker) { const resolvedSticker = this.resolve(sticker); - if (!resolvedSticker) 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, resolvedSticker.id)); resolvedSticker._patch(data); return resolvedSticker.user; diff --git a/packages/discord.js/src/managers/GuildTextThreadManager.js b/packages/discord.js/src/managers/GuildTextThreadManager.js index aff88df15..1b44254e6 100644 --- a/packages/discord.js/src/managers/GuildTextThreadManager.js +++ b/packages/discord.js/src/managers/GuildTextThreadManager.js @@ -72,7 +72,9 @@ class GuildTextThreadManager extends ThreadManager { let startMessageId; if (startMessage) { startMessageId = this.channel.messages.resolveId(startMessage); - if (!startMessageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'startMessage', 'MessageResolvable'); + if (!startMessageId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'startMessage', 'MessageResolvable'); + } } else if (this.channel.type !== ChannelType.GuildAnnouncement) { resolvedType = type ?? resolvedType; } diff --git a/packages/discord.js/src/managers/MessageManager.js b/packages/discord.js/src/managers/MessageManager.js index 30a4bb42d..4db086786 100644 --- a/packages/discord.js/src/managers/MessageManager.js +++ b/packages/discord.js/src/managers/MessageManager.js @@ -98,17 +98,25 @@ class MessageManager extends CachedManager { * .catch(console.error); */ async fetch(options) { - if (!options) return this._fetchMany(); + if (!options) { + return this._fetchMany(); + } + const { message, cache, force } = options; const resolvedMessage = this.resolveId(message ?? options); - if (resolvedMessage) return this._fetchSingle({ message: resolvedMessage, cache, force }); + if (resolvedMessage) { + return this._fetchSingle({ message: resolvedMessage, cache, force }); + } + return this._fetchMany(options); } async _fetchSingle({ message, cache, force = false }) { if (!force) { const existing = this.cache.get(message); - if (existing && !existing.partial) return existing; + if (existing && !existing.partial) { + return existing; + } } const data = await this.client.rest.get(Routes.channelMessage(this.channel.id, message)); @@ -228,7 +236,9 @@ class MessageManager extends CachedManager { */ async edit(message, options) { const messageId = this.resolveId(message); - if (!messageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable'); + if (!messageId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable'); + } const { body, files } = await ( options instanceof MessagePayload @@ -258,7 +268,9 @@ class MessageManager extends CachedManager { */ async pin(message, reason) { const messageId = this.resolveId(message); - if (!messageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable'); + if (!messageId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable'); + } await this.client.rest.put(Routes.channelMessagesPin(this.channel.id, messageId), { reason }); } @@ -272,7 +284,9 @@ class MessageManager extends CachedManager { */ async unpin(message, reason) { const messageId = this.resolveId(message); - if (!messageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable'); + if (!messageId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable'); + } await this.client.rest.delete(Routes.channelMessagesPin(this.channel.id, messageId), { reason }); } @@ -286,10 +300,14 @@ class MessageManager extends CachedManager { */ async react(message, emoji) { const messageId = this.resolveId(message); - if (!messageId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable'); + if (!messageId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'message', 'MessageResolvable'); + } const resolvedEmoji = resolvePartialEmoji(emoji); - if (!resolvedEmoji) throw new DiscordjsTypeError(ErrorCodes.EmojiType, 'emoji', 'EmojiIdentifierResolvable'); + if (!resolvedEmoji) { + throw new DiscordjsTypeError(ErrorCodes.EmojiType, 'emoji', 'EmojiIdentifierResolvable'); + } const emojiId = resolvedEmoji.id ? `${resolvedEmoji.animated ? 'a:' : ''}${resolvedEmoji.name}:${resolvedEmoji.id}` @@ -306,7 +324,9 @@ class MessageManager extends CachedManager { */ async delete(message) { const messageId = this.resolveId(message); - if (!messageId) 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, messageId)); } diff --git a/packages/discord.js/src/managers/PermissionOverwriteManager.js b/packages/discord.js/src/managers/PermissionOverwriteManager.js index 83d98b943..29abc57aa 100644 --- a/packages/discord.js/src/managers/PermissionOverwriteManager.js +++ b/packages/discord.js/src/managers/PermissionOverwriteManager.js @@ -104,7 +104,10 @@ class PermissionOverwriteManager extends CachedManager { 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'); + if (!resolvedUserOrRole) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role'); + } + resolvedType = resolvedUserOrRole instanceof Role ? OverwriteType.Role : OverwriteType.Member; } @@ -167,7 +170,9 @@ class PermissionOverwriteManager extends CachedManager { */ async delete(userOrRole, reason) { const userOrRoleId = this.channel.guild.roles.resolveId(userOrRole) ?? this.client.users.resolveId(userOrRole); - if (!userOrRoleId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role'); + if (!userOrRoleId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'parameter', 'User nor a Role'); + } await this.client.rest.delete(Routes.channelPermission(this.channel.id, userOrRoleId), { reason }); return this.channel; diff --git a/packages/discord.js/src/managers/PresenceManager.js b/packages/discord.js/src/managers/PresenceManager.js index ad4217625..f2cdcfc35 100644 --- a/packages/discord.js/src/managers/PresenceManager.js +++ b/packages/discord.js/src/managers/PresenceManager.js @@ -41,7 +41,10 @@ class PresenceManager extends CachedManager { */ resolve(presence) { const presenceResolvable = super.resolve(presence); - if (presenceResolvable) return presenceResolvable; + if (presenceResolvable) { + return presenceResolvable; + } + const userId = this.client.users.resolveId(presence); return super.cache.get(userId) ?? null; } @@ -54,7 +57,10 @@ class PresenceManager extends CachedManager { */ resolveId(presence) { const presenceResolvable = super.resolveId(presence); - if (presenceResolvable) return presenceResolvable; + if (presenceResolvable) { + return presenceResolvable; + } + const userId = this.client.users.resolveId(presence); return this.cache.has(userId) ? userId : null; } diff --git a/packages/discord.js/src/managers/ReactionUserManager.js b/packages/discord.js/src/managers/ReactionUserManager.js index 378677519..a64f054b6 100644 --- a/packages/discord.js/src/managers/ReactionUserManager.js +++ b/packages/discord.js/src/managers/ReactionUserManager.js @@ -71,7 +71,10 @@ class ReactionUserManager extends CachedManager { */ async remove(user = this.client.user) { const userId = this.client.users.resolveId(user); - if (!userId) throw new DiscordjsError(ErrorCodes.ReactionResolveUser); + if (!userId) { + throw new DiscordjsError(ErrorCodes.ReactionResolveUser); + } + const message = this.reaction.message; const route = userId === this.client.user.id diff --git a/packages/discord.js/src/managers/RoleManager.js b/packages/discord.js/src/managers/RoleManager.js index e17f4f46d..16e879243 100644 --- a/packages/discord.js/src/managers/RoleManager.js +++ b/packages/discord.js/src/managers/RoleManager.js @@ -68,13 +68,18 @@ class RoleManager extends CachedManager { if (!id) { const innerData = await this.client.rest.get(Routes.guildRoles(this.guild.id)); const roles = new Collection(); - for (const role of innerData) roles.set(role.id, this._add(role, cache)); + for (const role of innerData) { + roles.set(role.id, this._add(role, cache)); + } + return roles; } if (!force) { const existing = this.cache.get(id); - if (existing) return existing; + if (existing) { + return existing; + } } const data = await this.client.rest.get(Routes.guildRole(this.guild.id, id)); @@ -175,11 +180,16 @@ class RoleManager extends CachedManager { async create(options = {}) { let { permissions, icon } = options; const { name, hoist, position, mentionable, reason, unicodeEmoji } = options; - if (permissions !== undefined) permissions = new PermissionsBitField(permissions); + if (permissions !== undefined) { + permissions = new PermissionsBitField(permissions); + } + if (icon) { const guildEmojiURL = this.guild.emojis.resolve(icon)?.imageURL(); icon = guildEmojiURL ? await resolveImage(guildEmojiURL) : await resolveImage(icon); - if (typeof icon !== 'string') icon = undefined; + if (typeof icon !== 'string') { + icon = undefined; + } } const colors = options.colors && { @@ -204,7 +214,10 @@ class RoleManager extends CachedManager { guild_id: this.guild.id, role: data, }); - if (position) return this.setPosition(role, position, { reason }); + if (position) { + return this.setPosition(role, position, { reason }); + } + return role; } @@ -229,7 +242,9 @@ class RoleManager extends CachedManager { */ async edit(role, options) { const resolvedRole = this.resolve(role); - if (!resolvedRole) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable'); + if (!resolvedRole) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable'); + } if (typeof options.position === 'number') { await this.setPosition(resolvedRole, options.position, { reason: options.reason }); @@ -239,7 +254,9 @@ class RoleManager extends CachedManager { if (icon) { const guildEmojiURL = this.guild.emojis.resolve(icon)?.imageURL(); icon = guildEmojiURL ? await resolveImage(guildEmojiURL) : await resolveImage(icon); - if (typeof icon !== 'string') icon = undefined; + if (typeof icon !== 'string') { + icon = undefined; + } } const colors = options.colors && { @@ -301,7 +318,10 @@ class RoleManager extends CachedManager { */ async setPosition(role, position, { relative, reason } = {}) { const resolvedRole = this.resolve(role); - if (!resolvedRole) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable'); + if (!resolvedRole) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'role', 'RoleResolvable'); + } + const updatedRoles = await setPosition( resolvedRole, position, @@ -386,7 +406,10 @@ class RoleManager extends CachedManager { */ botRoleFor(user) { const userId = this.client.users.resolveId(user); - if (!userId) return null; + if (!userId) { + return null; + } + return this.cache.find(role => role.tags?.botId === userId) ?? null; } diff --git a/packages/discord.js/src/managers/StageInstanceManager.js b/packages/discord.js/src/managers/StageInstanceManager.js index 53c152d52..beb4a74f5 100644 --- a/packages/discord.js/src/managers/StageInstanceManager.js +++ b/packages/discord.js/src/managers/StageInstanceManager.js @@ -65,8 +65,14 @@ class StageInstanceManager extends CachedManager { */ async create(channel, options) { const channelId = this.guild.channels.resolveId(channel); - if (!channelId) throw new DiscordjsError(ErrorCodes.StageChannelResolve); - if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); + if (!channelId) { + throw new DiscordjsError(ErrorCodes.StageChannelResolve); + } + + if (typeof options !== 'object') { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); + } + const { guildScheduledEvent, topic, privacyLevel, sendStartNotification } = options; const guildScheduledEventId = guildScheduledEvent && this.resolveId(guildScheduledEvent); @@ -98,11 +104,15 @@ class StageInstanceManager extends CachedManager { */ async fetch(channel, { cache = true, force = false } = {}) { const channelId = this.guild.channels.resolveId(channel); - if (!channelId) throw new DiscordjsError(ErrorCodes.StageChannelResolve); + if (!channelId) { + throw new DiscordjsError(ErrorCodes.StageChannelResolve); + } if (!force) { const existing = this.cache.find(stageInstance => stageInstance.channelId === channelId); - if (existing) return existing; + if (existing) { + return existing; + } } const data = await this.client.rest.get(Routes.stageInstance(channelId)); @@ -130,9 +140,14 @@ class StageInstanceManager extends CachedManager { * .catch(console.error); */ async edit(channel, options) { - if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); + if (typeof options !== 'object') { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); + } + const channelId = this.guild.channels.resolveId(channel); - if (!channelId) throw new DiscordjsError(ErrorCodes.StageChannelResolve); + if (!channelId) { + throw new DiscordjsError(ErrorCodes.StageChannelResolve); + } const { topic, privacyLevel } = options; @@ -160,7 +175,9 @@ class StageInstanceManager extends CachedManager { */ async delete(channel) { const channelId = this.guild.channels.resolveId(channel); - if (!channelId) throw new DiscordjsError(ErrorCodes.StageChannelResolve); + if (!channelId) { + throw new DiscordjsError(ErrorCodes.StageChannelResolve); + } await this.client.rest.delete(Routes.stageInstance(channelId)); } diff --git a/packages/discord.js/src/managers/SubscriptionManager.js b/packages/discord.js/src/managers/SubscriptionManager.js index 595704f09..b2059aef3 100644 --- a/packages/discord.js/src/managers/SubscriptionManager.js +++ b/packages/discord.js/src/managers/SubscriptionManager.js @@ -52,13 +52,17 @@ class SubscriptionManager extends CachedManager { * @returns {Promise>} */ async fetch(options = {}) { - if (typeof options !== 'object') throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); + if (typeof options !== 'object') { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'options', 'object', true); + } const { after, before, cache, limit, sku, subscriptionId, user } = options; const skuId = resolveSKUId(sku); - if (!skuId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sku', 'SKUResolvable'); + if (!skuId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'sku', 'SKUResolvable'); + } if (subscriptionId) { const subscription = await this.client.rest.get(Routes.skuSubscription(skuId, subscriptionId)); diff --git a/packages/discord.js/src/managers/ThreadManager.js b/packages/discord.js/src/managers/ThreadManager.js index 171a0969f..8ac0b1090 100644 --- a/packages/discord.js/src/managers/ThreadManager.js +++ b/packages/discord.js/src/managers/ThreadManager.js @@ -44,7 +44,10 @@ class ThreadManager extends CachedManager { _add(thread) { const existing = this.cache.get(thread.id); - if (existing) return existing; + if (existing) { + return existing; + } + this.cache.set(thread.id, thread); return thread; } @@ -92,11 +95,17 @@ class ThreadManager extends CachedManager { * .catch(console.error); */ async fetch(options, { cache, force } = {}) { - if (!options) return this.fetchActive(cache); + if (!options) { + return this.fetchActive(cache); + } + const channel = this.client.channels.resolveId(options); if (channel) { const threadChannel = await this.client.channels.fetch(channel, { cache, force }); - if (threadChannel.parentId !== this.channel.id) throw new DiscordjsTypeError(ErrorCodes.NotAThreadOfParent); + if (threadChannel.parentId !== this.channel.id) { + throw new DiscordjsTypeError(ErrorCodes.NotAThreadOfParent); + } + return threadChannel; } @@ -192,7 +201,10 @@ class ThreadManager extends CachedManager { static _mapThreads(rawThreads, client, { parent, guild, cache }) { const threads = rawThreads.threads.reduce((coll, raw) => { const thread = client.channels._add(raw, guild ?? parent?.guild, { cache }); - if (parent && thread.parentId !== parent.id) return coll; + if (parent && thread.parentId !== parent.id) { + return coll; + } + return coll.set(thread.id, thread); }, new Collection()); @@ -205,7 +217,10 @@ class ThreadManager extends CachedManager { const response = { threads, members: threadMembers }; // The GET `/guilds/{guild.id}/threads/active` route does not return `has_more`. - if ('has_more' in rawThreads) response.hasMore = rawThreads.has_more; + if ('has_more' in rawThreads) { + response.hasMore = rawThreads.has_more; + } + return response; } } diff --git a/packages/discord.js/src/managers/ThreadMemberManager.js b/packages/discord.js/src/managers/ThreadMemberManager.js index e96a4a289..ea7943b7b 100644 --- a/packages/discord.js/src/managers/ThreadMemberManager.js +++ b/packages/discord.js/src/managers/ThreadMemberManager.js @@ -33,11 +33,19 @@ class ThreadMemberManager extends CachedManager { _add(data, cache = true) { const existing = this.cache.get(data.user_id); - if (cache) existing?._patch(data, { cache }); - if (existing) return existing; + if (cache) { + existing?._patch(data, { cache }); + } + + if (existing) { + return existing; + } const member = new ThreadMember(this.thread, data, { cache }); - if (cache) this.cache.set(data.user_id, member); + if (cache) { + this.cache.set(data.user_id, member); + } + return member; } @@ -77,9 +85,15 @@ class ThreadMemberManager extends CachedManager { */ resolve(member) { const memberResolvable = super.resolve(member); - if (memberResolvable) return memberResolvable; + if (memberResolvable) { + return memberResolvable; + } + const userId = this.client.users.resolveId(member); - if (userId) return super.cache.get(userId) ?? null; + if (userId) { + return super.cache.get(userId) ?? null; + } + return null; } @@ -91,7 +105,10 @@ class ThreadMemberManager extends CachedManager { */ resolveId(member) { const memberResolvable = super.resolveId(member); - if (memberResolvable) return memberResolvable; + if (memberResolvable) { + return memberResolvable; + } + const userResolvable = this.client.users.resolveId(member); return this.cache.has(userResolvable) ? userResolvable : null; } @@ -104,7 +121,10 @@ class ThreadMemberManager extends CachedManager { */ async add(member) { const id = member === '@me' ? member : this.client.users.resolveId(member); - if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'member', 'UserResolvable'); + if (!id) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'member', 'UserResolvable'); + } + await this.client.rest.put(Routes.threadMembers(this.thread.id, id)); return id; } @@ -117,7 +137,10 @@ class ThreadMemberManager extends CachedManager { */ async remove(member) { const id = member === '@me' ? member : this.client.users.resolveId(member); - if (!id) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'member', 'UserResolvable'); + if (!id) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'member', 'UserResolvable'); + } + await this.client.rest.delete(Routes.threadMembers(this.thread.id, id)); return id; } @@ -165,17 +188,25 @@ class ThreadMemberManager extends CachedManager { * @returns {Promise>} */ async fetch(options) { - if (!options) return this._fetchMany(); + if (!options) { + return this._fetchMany(); + } + const { member, withMember, cache, force } = options; const resolvedMember = this.resolveId(member ?? options); - if (resolvedMember) return this._fetchSingle({ member: resolvedMember, withMember, cache, force }); + if (resolvedMember) { + return this._fetchSingle({ member: resolvedMember, withMember, cache, force }); + } + return this._fetchMany(options); } async _fetchSingle({ member, withMember, cache, force = false }) { if (!force) { const existing = this.cache.get(member); - if (existing) return existing; + if (existing) { + return existing; + } } const data = await this.client.rest.get(Routes.threadMembers(this.thread.id, member), { diff --git a/packages/discord.js/src/managers/UserManager.js b/packages/discord.js/src/managers/UserManager.js index 748c5181f..17f11f58e 100644 --- a/packages/discord.js/src/managers/UserManager.js +++ b/packages/discord.js/src/managers/UserManager.js @@ -62,7 +62,9 @@ class UserManager extends CachedManager { if (!force) { const dmChannel = this.dmChannel(id); - if (dmChannel && !dmChannel.partial) return dmChannel; + if (dmChannel && !dmChannel.partial) { + return dmChannel; + } } const data = await this.client.rest.post(Routes.userChannels(), { body: { recipient_id: id } }); @@ -78,7 +80,10 @@ class UserManager extends CachedManager { async deleteDM(user) { const id = this.resolveId(user); const dmChannel = this.dmChannel(id); - if (!dmChannel) throw new DiscordjsError(ErrorCodes.UserNoDMChannel); + if (!dmChannel) { + throw new DiscordjsError(ErrorCodes.UserNoDMChannel); + } + await this.client.rest.delete(Routes.channel(dmChannel.id)); this.client.channels._remove(dmChannel.id); return dmChannel; @@ -95,7 +100,9 @@ class UserManager extends CachedManager { const id = this.resolveId(user); if (!force) { const existing = this.cache.get(id); - if (existing && !existing.partial) return existing; + if (existing && !existing.partial) { + return existing; + } } const data = await this.client.rest.get(Routes.user(id)); @@ -120,8 +127,14 @@ class UserManager extends CachedManager { * @returns {?User} */ resolve(user) { - if (user instanceof GuildMember || user instanceof ThreadMember) return user.user; - if (user instanceof Message) return user.author; + if (user instanceof GuildMember || user instanceof ThreadMember) { + return user.user; + } + + if (user instanceof Message) { + return user.author; + } + return super.resolve(user); } @@ -132,9 +145,18 @@ class UserManager extends CachedManager { * @returns {?Snowflake} */ resolveId(user) { - if (user instanceof ThreadMember) return user.id; - if (user instanceof GuildMember) return user.user.id; - if (user instanceof Message) return user.author.id; + if (user instanceof ThreadMember) { + return user.id; + } + + if (user instanceof GuildMember) { + return user.user.id; + } + + if (user instanceof Message) { + return user.author.id; + } + return super.resolveId(user); } } diff --git a/packages/discord.js/src/managers/VoiceStateManager.js b/packages/discord.js/src/managers/VoiceStateManager.js index dc720647e..8961fa289 100644 --- a/packages/discord.js/src/managers/VoiceStateManager.js +++ b/packages/discord.js/src/managers/VoiceStateManager.js @@ -30,10 +30,15 @@ class VoiceStateManager extends CachedManager { _add(data, cache = true) { const existing = this.cache.get(data.user_id); - if (existing) return existing._patch(data); + if (existing) { + return existing._patch(data); + } const entry = new this.holds(this.guild, data); - if (cache) this.cache.set(data.user_id, entry); + if (cache) { + this.cache.set(data.user_id, entry); + } + return entry; } @@ -53,7 +58,9 @@ class VoiceStateManager extends CachedManager { const id = member === '@me' ? member : this.guild.members.resolveId(member); if (!force) { const existing = this.cache.get(id === '@me' ? this.client.user.id : id); - if (existing) return existing; + if (existing) { + return existing; + } } const data = await this.client.rest.get(Routes.guildVoiceState(this.guild.id, id)); diff --git a/packages/discord.js/src/sharding/Shard.js b/packages/discord.js/src/sharding/Shard.js index 3b1a6a03d..c7b11a01d 100644 --- a/packages/discord.js/src/sharding/Shard.js +++ b/packages/discord.js/src/sharding/Shard.js @@ -139,8 +139,13 @@ class Shard extends AsyncEventEmitter { * @returns {Promise} */ async spawn(timeout = 30_000) { - if (this.process) throw new DiscordjsError(ErrorCodes.ShardingProcessExists, this.id); - if (this.worker) throw new DiscordjsError(ErrorCodes.ShardingWorkerExists, this.id); + if (this.process) { + throw new DiscordjsError(ErrorCodes.ShardingProcessExists, this.id); + } + + if (this.worker) { + throw new DiscordjsError(ErrorCodes.ShardingWorkerExists, this.id); + } this._exitListener = this._handleExit.bind(this, undefined, timeout); @@ -182,7 +187,10 @@ class Shard extends AsyncEventEmitter { */ this.emit(ShardEvents.Spawn, child); - if (timeout === -1 || timeout === Infinity) return child; + if (timeout === -1 || timeout === Infinity) { + return child; + } + return new Promise((resolve, reject) => { const cleanup = () => { clearTimeout(spawnTimeoutTimer); @@ -251,7 +259,10 @@ class Shard extends AsyncEventEmitter { */ async respawn({ delay = 500, timeout = 30_000 } = {}) { this.kill(); - if (delay > 0) await sleep(delay); + if (delay > 0) { + await sleep(delay); + } + return this.spawn(timeout); } @@ -265,8 +276,11 @@ class Shard extends AsyncEventEmitter { return new Promise((resolve, reject) => { if (this.process) { this.process.send(message, err => { - if (err) reject(err); - else resolve(this); + if (err) { + reject(err); + } else { + resolve(this); + } }); } else { this.worker.postMessage(message); @@ -292,18 +306,26 @@ class Shard extends AsyncEventEmitter { } // Cached promise from previous call - if (this._fetches.has(prop)) return this._fetches.get(prop); + if (this._fetches.has(prop)) { + return this._fetches.get(prop); + } const promise = new Promise((resolve, reject) => { const child = this.process ?? this.worker; const listener = message => { - if (message?._fetchProp !== prop) return; + if (message?._fetchProp !== prop) { + return; + } + child.removeListener('message', listener); this.decrementMaxListeners(child); this._fetches.delete(prop); - if (message._error) reject(makeError(message._error)); - else resolve(message._result); + if (message._error) { + reject(makeError(message._error)); + } else { + resolve(message._result); + } }; this.incrementMaxListeners(child); @@ -338,18 +360,26 @@ class Shard extends AsyncEventEmitter { } // Cached promise from previous call - if (this._evals.has(_eval)) return this._evals.get(_eval); + if (this._evals.has(_eval)) { + return this._evals.get(_eval); + } const promise = new Promise((resolve, reject) => { const child = this.process ?? this.worker; const listener = message => { - if (message?._eval !== _eval) return; + if (message?._eval !== _eval) { + return; + } + child.removeListener('message', listener); this.decrementMaxListeners(child); this._evals.delete(_eval); - if (message._error) reject(makeError(message._error)); - else resolve(message._result); + if (message._error) { + reject(makeError(message._error)); + } else { + resolve(message._result); + } }; this.incrementMaxListeners(child); @@ -473,7 +503,9 @@ class Shard extends AsyncEventEmitter { this._evals.clear(); this._fetches.clear(); - if (respawn) this.spawn(timeout).catch(error => this.emit(ShardEvents.Error, error)); + if (respawn) { + this.spawn(timeout).catch(error => this.emit(ShardEvents.Error, error)); + } } /** diff --git a/packages/discord.js/src/sharding/ShardClientUtil.js b/packages/discord.js/src/sharding/ShardClientUtil.js index 799519b98..ead2e1df3 100644 --- a/packages/discord.js/src/sharding/ShardClientUtil.js +++ b/packages/discord.js/src/sharding/ShardClientUtil.js @@ -78,8 +78,11 @@ class ShardClientUtil { switch (this.mode) { case 'process': process.send(message, err => { - if (err) reject(err); - else resolve(); + if (err) { + reject(err); + } else { + resolve(); + } }); break; case 'worker': @@ -109,11 +112,17 @@ class ShardClientUtil { const parent = this.parentPort ?? process; const listener = message => { - if (message?._sFetchProp !== prop || message._sFetchPropShard !== shard) return; + if (message?._sFetchProp !== prop || message._sFetchPropShard !== shard) { + return; + } + parent.removeListener('message', listener); this.decrementMaxListeners(parent); - if (message._error) reject(makeError(message._error)); - else resolve(message._result); + if (message._error) { + reject(makeError(message._error)); + } else { + resolve(message._result); + } }; this.incrementMaxListeners(parent); @@ -150,11 +159,17 @@ class ShardClientUtil { const evalScript = `(${script})(this, ${JSON.stringify(options.context)})`; const listener = message => { - if (message?._sEval !== evalScript || message._sEvalShard !== options.shard) return; + if (message?._sEval !== evalScript || message._sEvalShard !== options.shard) { + return; + } + parent.removeListener('message', listener); this.decrementMaxListeners(parent); - if (message._error) reject(makeError(message._error)); - else resolve(message._result); + if (message._error) { + reject(makeError(message._error)); + } else { + resolve(message._result); + } }; this.incrementMaxListeners(parent); @@ -185,12 +200,18 @@ class ShardClientUtil { * @private */ async _handleMessage(message) { - if (!message) return; + if (!message) { + return; + } + if (message._fetchProp) { try { const props = message._fetchProp.split('.'); let value = this.client; - for (const prop of props) value = value[prop]; + for (const prop of props) { + value = value[prop]; + } + this._respond('fetchProp', { _fetchProp: message._fetchProp, _result: value }); } catch (error) { this._respond('fetchProp', { _fetchProp: message._fetchProp, _error: makePlainError(error) }); @@ -258,7 +279,10 @@ class ShardClientUtil { */ static shardIdForGuildId(guildId, shardCount) { const shard = calculateShardId(guildId, shardCount); - if (shard < 0) throw new DiscordjsError(ErrorCodes.ShardingShardMiscalculation, shard, guildId, shardCount); + if (shard < 0) { + throw new DiscordjsError(ErrorCodes.ShardingShardMiscalculation, shard, guildId, shardCount); + } + return shard; } diff --git a/packages/discord.js/src/sharding/ShardingManager.js b/packages/discord.js/src/sharding/ShardingManager.js index 148bb42c4..30aa63383 100644 --- a/packages/discord.js/src/sharding/ShardingManager.js +++ b/packages/discord.js/src/sharding/ShardingManager.js @@ -68,11 +68,19 @@ class ShardingManager extends AsyncEventEmitter { * @type {string} */ this.file = file; - if (!file) throw new DiscordjsError(ErrorCodes.ClientInvalidOption, 'File', 'specified.'); - if (!path.isAbsolute(file)) this.file = path.resolve(process.cwd(), file); + if (!file) { + throw new DiscordjsError(ErrorCodes.ClientInvalidOption, 'File', 'specified.'); + } + + if (!path.isAbsolute(file)) { + this.file = path.resolve(process.cwd(), file); + } + // eslint-disable-next-line n/no-sync const stats = fs.statSync(this.file); - if (!stats.isFile()) throw new DiscordjsError(ErrorCodes.ClientInvalidOption, 'File', 'a file'); + if (!stats.isFile()) { + throw new DiscordjsError(ErrorCodes.ClientInvalidOption, 'File', 'a file'); + } /** * List of shards this sharding manager spawns @@ -233,7 +241,10 @@ class ShardingManager extends AsyncEventEmitter { } // Make sure this many shards haven't already been spawned - if (this.shards.size >= shardAmount) 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 !== shardAmount) { this.shardList = [...range(shardAmount)]; } @@ -255,7 +266,10 @@ class ShardingManager extends AsyncEventEmitter { const promises = []; const shard = this.createShard(shardId); promises.push(shard.spawn(timeout)); - if (delay > 0 && this.shards.size !== this.shardList.length) promises.push(sleep(delay)); + if (delay > 0 && this.shards.size !== this.shardList.length) { + promises.push(sleep(delay)); + } + await Promise.all(promises); } @@ -270,7 +284,10 @@ class ShardingManager extends AsyncEventEmitter { */ async broadcast(message) { const promises = []; - for (const shard of this.shards.values()) promises.push(shard.send(message)); + for (const shard of this.shards.values()) { + promises.push(shard.send(message)); + } + return Promise.all(promises); } @@ -322,10 +339,15 @@ class ShardingManager extends AsyncEventEmitter { * @private */ async _performOnShards(method, args, shard) { - if (this.shards.size === 0) throw new DiscordjsError(ErrorCodes.ShardingNoShards); + if (this.shards.size === 0) { + throw new DiscordjsError(ErrorCodes.ShardingNoShards); + } if (typeof shard === 'number') { - if (this.shards.has(shard)) return this.shards.get(shard)[method](...args); + if (this.shards.has(shard)) { + return this.shards.get(shard)[method](...args); + } + throw new DiscordjsError(ErrorCodes.ShardingShardNotFound, shard); } @@ -334,7 +356,10 @@ class ShardingManager extends AsyncEventEmitter { } const promises = []; - for (const sh of this.shards.values()) promises.push(sh[method](...args)); + for (const sh of this.shards.values()) { + promises.push(sh[method](...args)); + } + return Promise.all(promises); } @@ -359,7 +384,10 @@ class ShardingManager extends AsyncEventEmitter { let shardCounter = 0; for (const shard of this.shards.values()) { const promises = [shard.respawn({ delay: respawnDelay, timeout })]; - if (++shardCounter < this.shards.size && shardDelay > 0) promises.push(sleep(shardDelay)); + if (++shardCounter < this.shards.size && shardDelay > 0) { + promises.push(sleep(shardDelay)); + } + await Promise.all(promises); } diff --git a/packages/discord.js/src/structures/AnonymousGuild.js b/packages/discord.js/src/structures/AnonymousGuild.js index 7738e2921..1b9f49711 100644 --- a/packages/discord.js/src/structures/AnonymousGuild.js +++ b/packages/discord.js/src/structures/AnonymousGuild.js @@ -11,11 +11,15 @@ const { BaseGuild } = require('./BaseGuild.js'); class AnonymousGuild extends BaseGuild { constructor(client, data, immediatePatch = true) { super(client, data); - if (immediatePatch) this._patch(data); + if (immediatePatch) { + this._patch(data); + } } _patch(data) { - if ('features' in data) this.features = data.features; + if ('features' in data) { + this.features = data.features; + } if ('splash' in data) { /** diff --git a/packages/discord.js/src/structures/ApplicationCommand.js b/packages/discord.js/src/structures/ApplicationCommand.js index e78e4ecad..76fbebe00 100644 --- a/packages/discord.js/src/structures/ApplicationCommand.js +++ b/packages/discord.js/src/structures/ApplicationCommand.js @@ -412,7 +412,9 @@ class ApplicationCommand extends Base { */ equals(command, enforceOptionOrder = false) { // If given an id, check if the id matches - if (command.id && this.id !== command.id) return false; + if (command.id && this.id !== command.id) { + return false; + } let defaultMemberPermissions = null; @@ -471,7 +473,10 @@ class ApplicationCommand extends Base { * @returns {boolean} */ static optionsEqual(existing, options, enforceOptionOrder = false) { - if (existing.length !== options.length) return false; + if (existing.length !== options.length) { + return false; + } + if (enforceOptionOrder) { return existing.every((option, index) => this._optionEquals(option, options[index], enforceOptionOrder)); } @@ -479,7 +484,9 @@ class ApplicationCommand extends Base { const newOptions = new Map(options.map(option => [option.name, option])); for (const option of existing) { const foundOption = newOptions.get(option.name); - if (!foundOption || !this._optionEquals(option, foundOption)) return false; + if (!foundOption || !this._optionEquals(option, foundOption)) { + return false; + } } return true; @@ -543,7 +550,9 @@ class ApplicationCommand extends Base { const newChoices = new Map(option.choices.map(choice => [choice.name, choice])); for (const choice of existing.choices) { const foundChoice = newChoices.get(choice.name); - if (!foundChoice || foundChoice.value !== choice.value) return false; + if (!foundChoice || foundChoice.value !== choice.value) { + return false; + } } } } @@ -551,7 +560,9 @@ class ApplicationCommand extends Base { if (existing.channelTypes) { const newTypes = option.channelTypes ?? option.channel_types; for (const type of existing.channelTypes) { - if (!newTypes.includes(type)) return false; + if (!newTypes.includes(type)) { + return false; + } } } diff --git a/packages/discord.js/src/structures/ApplicationEmoji.js b/packages/discord.js/src/structures/ApplicationEmoji.js index ccf733431..603a96671 100644 --- a/packages/discord.js/src/structures/ApplicationEmoji.js +++ b/packages/discord.js/src/structures/ApplicationEmoji.js @@ -22,7 +22,10 @@ class ApplicationEmoji extends Emoji { } _patch(data) { - if ('name' in data) this.name = data.name; + if ('name' in data) { + this.name = data.name; + } + if (data.user) { /** * The user who created this emoji diff --git a/packages/discord.js/src/structures/AttachmentBuilder.js b/packages/discord.js/src/structures/AttachmentBuilder.js index 3dd8d1e86..3aad0624e 100644 --- a/packages/discord.js/src/structures/AttachmentBuilder.js +++ b/packages/discord.js/src/structures/AttachmentBuilder.js @@ -131,7 +131,9 @@ class AttachmentBuilder { * @returns {AttachmentBuilder} This attachment */ setSpoiler(spoiler = true) { - if (spoiler === this.spoiler) return this; + if (spoiler === this.spoiler) { + return this; + } if (!spoiler) { while (this.spoiler) { diff --git a/packages/discord.js/src/structures/AutocompleteInteraction.js b/packages/discord.js/src/structures/AutocompleteInteraction.js index 83ec425d5..8acbdd5b5 100644 --- a/packages/discord.js/src/structures/AutocompleteInteraction.js +++ b/packages/discord.js/src/structures/AutocompleteInteraction.js @@ -91,7 +91,9 @@ class AutocompleteInteraction extends BaseInteraction { * .catch(console.error); */ async respond(options) { - if (this.responded) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied); + if (this.responded) { + throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied); + } await this.client.rest.post(Routes.interactionCallback(this.id, this.token), { body: { diff --git a/packages/discord.js/src/structures/BaseChannel.js b/packages/discord.js/src/structures/BaseChannel.js index 416d2c434..1f2889f64 100644 --- a/packages/discord.js/src/structures/BaseChannel.js +++ b/packages/discord.js/src/structures/BaseChannel.js @@ -24,7 +24,9 @@ class BaseChannel extends Base { */ this.type = data.type; - if (data && immediatePatch) this._patch(data); + if (data && immediatePatch) { + this._patch(data); + } } _patch(data) { diff --git a/packages/discord.js/src/structures/BaseGuildEmoji.js b/packages/discord.js/src/structures/BaseGuildEmoji.js index 0cc7c085b..943ddbf37 100644 --- a/packages/discord.js/src/structures/BaseGuildEmoji.js +++ b/packages/discord.js/src/structures/BaseGuildEmoji.js @@ -27,7 +27,9 @@ class BaseGuildEmoji extends Emoji { } _patch(data) { - if ('name' in data) this.name = data.name; + if ('name' in data) { + this.name = data.name; + } if ('require_colons' in data) { /** diff --git a/packages/discord.js/src/structures/BaseGuildTextChannel.js b/packages/discord.js/src/structures/BaseGuildTextChannel.js index ae7eb073e..5e7bb2f28 100644 --- a/packages/discord.js/src/structures/BaseGuildTextChannel.js +++ b/packages/discord.js/src/structures/BaseGuildTextChannel.js @@ -94,7 +94,9 @@ class BaseGuildTextChannel extends GuildChannel { } if ('messages' in data) { - for (const message of data.messages) this.messages._add(message); + for (const message of data.messages) { + this.messages._add(message); + } } } diff --git a/packages/discord.js/src/structures/BaseGuildVoiceChannel.js b/packages/discord.js/src/structures/BaseGuildVoiceChannel.js index 50a221315..4161541a6 100644 --- a/packages/discord.js/src/structures/BaseGuildVoiceChannel.js +++ b/packages/discord.js/src/structures/BaseGuildVoiceChannel.js @@ -83,7 +83,9 @@ class BaseGuildVoiceChannel extends GuildChannel { } if ('messages' in data) { - for (const message of data.messages) this.messages._add(message); + for (const message of data.messages) { + this.messages._add(message); + } } if ('rate_limit_per_user' in data) { @@ -134,12 +136,19 @@ class BaseGuildVoiceChannel extends GuildChannel { * @readonly */ get joinable() { - if (!this.viewable) return false; + if (!this.viewable) { + return false; + } + const permissions = this.permissionsFor(this.client.user); - if (!permissions) return false; + if (!permissions) { + return false; + } // This flag allows joining even if timed out - if (permissions.has(PermissionFlagsBits.Administrator, false)) return true; + if (permissions.has(PermissionFlagsBits.Administrator, false)) { + return true; + } return ( this.guild.members.me.communicationDisabledUntilTimestamp < Date.now() && diff --git a/packages/discord.js/src/structures/ClientUser.js b/packages/discord.js/src/structures/ClientUser.js index 8bf4e54e0..108801cbf 100644 --- a/packages/discord.js/src/structures/ClientUser.js +++ b/packages/discord.js/src/structures/ClientUser.js @@ -33,7 +33,9 @@ class ClientUser extends User { this.mfaEnabled ??= null; } - if ('token' in data) this.client.token = data.token; + if ('token' in data) { + this.client.token = data.token; + } } /** @@ -200,7 +202,9 @@ class ClientUser extends User { * client.user.setActivity('discord.js', { type: ActivityType.Watching }); */ async setActivity(name, options = {}) { - if (!name) return this.setPresence({ activities: [], shardId: options.shardId }); + if (!name) { + return this.setPresence({ activities: [], shardId: options.shardId }); + } const activity = { ...options, ...(typeof name === 'object' ? name : { name }) }; return this.setPresence({ activities: [activity], shardId: activity.shardId }); diff --git a/packages/discord.js/src/structures/CommandInteraction.js b/packages/discord.js/src/structures/CommandInteraction.js index 11aa38579..cb90541a2 100644 --- a/packages/discord.js/src/structures/CommandInteraction.js +++ b/packages/discord.js/src/structures/CommandInteraction.js @@ -139,24 +139,39 @@ class CommandInteraction extends BaseInteraction { type: option.type, }; - if ('value' in option) result.value = option.value; - if ('options' in option) result.options = option.options.map(opt => this.transformOption(opt, resolved)); + if ('value' in option) { + result.value = option.value; + } + + if ('options' in option) { + result.options = option.options.map(opt => this.transformOption(opt, resolved)); + } if (resolved) { const user = resolved.users?.[option.value]; - if (user) result.user = this.client.users._add(user); + if (user) { + result.user = this.client.users._add(user); + } const member = resolved.members?.[option.value]; - if (member) result.member = this.guild?.members._add({ user, ...member }) ?? member; + if (member) { + result.member = this.guild?.members._add({ user, ...member }) ?? member; + } const channel = resolved.channels?.[option.value]; - if (channel) result.channel = this.client.channels._add(channel, this.guild) ?? channel; + if (channel) { + result.channel = this.client.channels._add(channel, this.guild) ?? channel; + } const role = resolved.roles?.[option.value]; - if (role) result.role = this.guild?.roles._add(role) ?? role; + if (role) { + result.role = this.guild?.roles._add(role) ?? role; + } const attachment = resolved.attachments?.[option.value]; - if (attachment) result.attachment = new Attachment(attachment); + if (attachment) { + result.attachment = new Attachment(attachment); + } } return result; diff --git a/packages/discord.js/src/structures/CommandInteractionOptionResolver.js b/packages/discord.js/src/structures/CommandInteractionOptionResolver.js index a434510ff..2bcca8e54 100644 --- a/packages/discord.js/src/structures/CommandInteractionOptionResolver.js +++ b/packages/discord.js/src/structures/CommandInteractionOptionResolver.js @@ -328,7 +328,10 @@ class CommandInteractionOptionResolver { */ getFocused() { const focusedOption = this._hoistedOptions.find(option => option.focused); - if (!focusedOption) throw new DiscordjsTypeError(ErrorCodes.AutocompleteInteractionOptionNoFocusedOption); + if (!focusedOption) { + throw new DiscordjsTypeError(ErrorCodes.AutocompleteInteractionOptionNoFocusedOption); + } + return focusedOption; } } diff --git a/packages/discord.js/src/structures/Embed.js b/packages/discord.js/src/structures/Embed.js index 165febd5e..c08e9e728 100644 --- a/packages/discord.js/src/structures/Embed.js +++ b/packages/discord.js/src/structures/Embed.js @@ -92,7 +92,10 @@ class Embed { * @readonly */ get thumbnail() { - if (!this.data.thumbnail) return null; + if (!this.data.thumbnail) { + return null; + } + return { url: this.data.thumbnail.url, proxyURL: this.data.thumbnail.proxy_url, @@ -108,7 +111,10 @@ class Embed { * @readonly */ get image() { - if (!this.data.image) return null; + if (!this.data.image) { + return null; + } + return { url: this.data.image.url, proxyURL: this.data.image.proxy_url, @@ -124,7 +130,10 @@ class Embed { * @readonly */ get video() { - if (!this.data.video) return null; + if (!this.data.video) { + return null; + } + return { url: this.data.video.url, proxyURL: this.data.video.proxy_url, @@ -148,7 +157,10 @@ class Embed { * @readonly */ get author() { - if (!this.data.author) return null; + if (!this.data.author) { + return null; + } + return { name: this.data.author.name, url: this.data.author.url, @@ -181,7 +193,10 @@ class Embed { * @readonly */ get footer() { - if (!this.data.footer) return null; + if (!this.data.footer) { + return null; + } + return { text: this.data.footer.text, iconURL: this.data.footer.icon_url, diff --git a/packages/discord.js/src/structures/Emoji.js b/packages/discord.js/src/structures/Emoji.js index 2b93161c1..1c059ce7f 100644 --- a/packages/discord.js/src/structures/Emoji.js +++ b/packages/discord.js/src/structures/Emoji.js @@ -41,7 +41,10 @@ class Emoji extends Base { * @readonly */ get identifier() { - if (this.id) return `${this.animated ? 'a:' : ''}${this.name}:${this.id}`; + if (this.id) { + return `${this.animated ? 'a:' : ''}${this.name}:${this.id}`; + } + return encodeURIComponent(this.name); } @@ -52,7 +55,9 @@ class Emoji extends Base { * @returns {?string} */ imageURL(options = {}) { - if (!this.id) return null; + if (!this.id) { + return null; + } // Return a dynamic extension depending on whether the emoji is animated. const resolvedOptions = { extension: options.extension, size: options.size }; diff --git a/packages/discord.js/src/structures/Entitlement.js b/packages/discord.js/src/structures/Entitlement.js index 92db4b111..fbb565145 100644 --- a/packages/discord.js/src/structures/Entitlement.js +++ b/packages/discord.js/src/structures/Entitlement.js @@ -118,7 +118,10 @@ class Entitlement extends Base { * @type {?Guild} */ get guild() { - if (!this.guildId) return null; + if (!this.guildId) { + return null; + } + return this.client.guilds.cache.get(this.guildId) ?? null; } diff --git a/packages/discord.js/src/structures/Guild.js b/packages/discord.js/src/structures/Guild.js index 589333bb5..098bc6498 100644 --- a/packages/discord.js/src/structures/Guild.js +++ b/packages/discord.js/src/structures/Guild.js @@ -127,7 +127,10 @@ class Guild extends AnonymousGuild { */ this.soundboardSounds = new GuildSoundboardSoundManager(this); - if (!data) return; + if (!data) { + return; + } + if (data.unavailable) { /** * Whether the guild is available to access. If it is not available, it indicates a server outage @@ -137,7 +140,9 @@ class Guild extends AnonymousGuild { this.available = false; } else { this._patch(data); - if (!data.channels) this.available = false; + if (!data.channels) { + this.available = false; + } } /** @@ -151,8 +156,14 @@ class Guild extends AnonymousGuild { _patch(data) { super._patch(data); this.id = data.id; - if ('name' in data) this.name = data.name; - if ('icon' in data) this.icon = data.icon; + if ('name' in data) { + this.name = data.name; + } + + if ('icon' in data) { + this.icon = data.icon; + } + if ('unavailable' in data) { this.available = !data.unavailable; } else { @@ -440,12 +451,16 @@ class Guild extends AnonymousGuild { if (data.roles) { this.roles.cache.clear(); - for (const role of data.roles) this.roles._add(role); + for (const role of data.roles) { + this.roles._add(role); + } } if (data.members) { this.members.cache.clear(); - for (const guildUser of data.members) this.members._add(guildUser); + for (const guildUser of data.members) { + this.members._add(guildUser); + } } if ('owner_id' in data) { @@ -491,7 +506,11 @@ class Guild extends AnonymousGuild { * @type {GuildEmojiManager} */ this.emojis = new GuildEmojiManager(this); - if (data.emojis) for (const emoji of data.emojis) this.emojis._add(emoji); + if (data.emojis) { + for (const emoji of data.emojis) { + this.emojis._add(emoji); + } + } } else if (data.emojis) { this.client.actions.GuildEmojisUpdate.handle({ guild_id: this.id, @@ -506,7 +525,11 @@ class Guild extends AnonymousGuild { * @type {GuildStickerManager} */ this.stickers = new GuildStickerManager(this); - if (data.stickers) for (const sticker of data.stickers) this.stickers._add(sticker); + if (data.stickers) { + for (const sticker of data.stickers) { + this.stickers._add(sticker); + } + } } else if (data.stickers) { this.client.actions.GuildStickersUpdate.handle({ guild_id: this.id, @@ -767,7 +790,10 @@ class Guild extends AnonymousGuild { async fetchWebhooks() { const apiHooks = await this.client.rest.get(Routes.guildWebhooks(this.id)); const hooks = new Collection(); - for (const hook of apiHooks) hooks.set(hook.id, new Webhook(this.client, hook)); + for (const hook of apiHooks) { + hooks.set(hook.id, new Webhook(this.client, hook)); + } + return hooks; } @@ -865,7 +891,10 @@ class Guild extends AnonymousGuild { if (user) { const userId = this.client.users.resolveId(user); - if (!userId) throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable'); + if (!userId) { + throw new DiscordjsTypeError(ErrorCodes.InvalidType, 'user', 'UserResolvable'); + } + query.set('user_id', userId); } @@ -1425,7 +1454,10 @@ class Guild extends AnonymousGuild { * .catch(console.error); */ async leave() { - if (this.ownerId === this.client.user.id) throw new DiscordjsError(ErrorCodes.GuildOwned); + if (this.ownerId === this.client.user.id) { + throw new DiscordjsError(ErrorCodes.GuildOwned); + } + await this.client.rest.delete(Routes.userGuild(this.id)); return this; } @@ -1438,7 +1470,10 @@ class Guild extends AnonymousGuild { */ async disableInvites(disabled = true) { const features = this.features.filter(feature => feature !== GuildFeature.InvitesDisabled); - if (disabled) features.push(GuildFeature.InvitesDisabled); + if (disabled) { + features.push(GuildFeature.InvitesDisabled); + } + return this.edit({ features }); } diff --git a/packages/discord.js/src/structures/GuildAuditLogs.js b/packages/discord.js/src/structures/GuildAuditLogs.js index d91ec6e75..162d68abd 100644 --- a/packages/discord.js/src/structures/GuildAuditLogs.js +++ b/packages/discord.js/src/structures/GuildAuditLogs.js @@ -12,8 +12,18 @@ const { Webhook } = require('./Webhook.js'); */ class GuildAuditLogs { constructor(guild, data) { - if (data.users) for (const user of data.users) guild.client.users._add(user); - if (data.threads) for (const thread of data.threads) guild.client.channels._add(thread, guild); + if (data.users) { + for (const user of data.users) { + guild.client.users._add(user); + } + } + + if (data.threads) { + for (const thread of data.threads) { + guild.client.channels._add(thread, guild); + } + } + /** * Cached webhooks * diff --git a/packages/discord.js/src/structures/GuildAuditLogsEntry.js b/packages/discord.js/src/structures/GuildAuditLogsEntry.js index dd4ab4e5e..d97a0df49 100644 --- a/packages/discord.js/src/structures/GuildAuditLogsEntry.js +++ b/packages/discord.js/src/structures/GuildAuditLogsEntry.js @@ -402,24 +402,78 @@ class GuildAuditLogsEntry { * @returns {AuditLogTargetType} */ static targetType(target) { - if (target < 10) return Targets.Guild; - if (target < 20) return Targets.Channel; - if (target < 30) return Targets.User; - if (target < 40) return Targets.Role; - if (target < 50) return Targets.Invite; - if (target < 60) return Targets.Webhook; - if (target < 70) return Targets.Emoji; - if (target < 80) return Targets.Message; - if (target < 83) return Targets.Integration; - if (target < 86) return Targets.StageInstance; - if (target < 100) return Targets.Sticker; - if (target < 110) return Targets.GuildScheduledEvent; - if (target < 120) return Targets.Thread; - if (target < 130) return Targets.ApplicationCommand; - if (target < 140) return Targets.SoundboardSound; - if (target < 143) return Targets.AutoModeration; - if (target < 146) return Targets.User; - if (target >= 163 && target <= 165) return Targets.GuildOnboardingPrompt; + if (target < 10) { + return Targets.Guild; + } + + if (target < 20) { + return Targets.Channel; + } + + if (target < 30) { + return Targets.User; + } + + if (target < 40) { + return Targets.Role; + } + + if (target < 50) { + return Targets.Invite; + } + + if (target < 60) { + return Targets.Webhook; + } + + if (target < 70) { + return Targets.Emoji; + } + + if (target < 80) { + return Targets.Message; + } + + if (target < 83) { + return Targets.Integration; + } + + if (target < 86) { + return Targets.StageInstance; + } + + if (target < 100) { + return Targets.Sticker; + } + + if (target < 110) { + return Targets.GuildScheduledEvent; + } + + if (target < 120) { + return Targets.Thread; + } + + if (target < 130) { + return Targets.ApplicationCommand; + } + + if (target < 140) { + return Targets.SoundboardSound; + } + + if (target < 143) { + return Targets.AutoModeration; + } + + if (target < 146) { + return Targets.User; + } + + if (target >= 163 && target <= 165) { + return Targets.GuildOnboardingPrompt; + } + return Targets.Unknown; } diff --git a/packages/discord.js/src/structures/GuildChannel.js b/packages/discord.js/src/structures/GuildChannel.js index 231aa9c02..eec2c8059 100644 --- a/packages/discord.js/src/structures/GuildChannel.js +++ b/packages/discord.js/src/structures/GuildChannel.js @@ -46,7 +46,9 @@ class GuildChannel extends BaseChannel { */ this.permissionOverwrites = new PermissionOverwriteManager(this); - if (data && immediatePatch) this._patch(data); + if (data && immediatePatch) { + this._patch(data); + } } _patch(data) { @@ -116,7 +118,9 @@ class GuildChannel extends BaseChannel { * @readonly */ get permissionsLocked() { - if (!this.parent) return null; + if (!this.parent) { + return null; + } // Get all overwrites const overwriteIds = new Set([ @@ -163,10 +167,18 @@ class GuildChannel extends BaseChannel { let count = 0; for (const channel of this.guild.channels.cache.values()) { - if (!types.includes(channel.type)) continue; - if (!selfIsCategory && channel.parentId !== this.parentId) continue; + if (!types.includes(channel.type)) { + continue; + } + + if (!selfIsCategory && channel.parentId !== this.parentId) { + continue; + } + if (this.rawPosition === channel.rawPosition) { - if (Snowflake.compare(channel.id, this.id) === -1) count++; + if (Snowflake.compare(channel.id, this.id) === -1) { + count++; + } } else if (this.rawPosition > channel.rawPosition) { count++; } @@ -185,14 +197,19 @@ class GuildChannel extends BaseChannel { */ permissionsFor(memberOrRole, checkAdmin = true) { const member = this.guild.members.resolve(memberOrRole); - if (member) return this.memberPermissions(member, checkAdmin); + if (member) { + return this.memberPermissions(member, checkAdmin); + } + const role = this.guild.roles.resolve(memberOrRole); return role && this.rolePermissions(role, checkAdmin); } overwritesFor(member, verified = false, roles = null) { const resolvedMember = verified ? member : this.guild.members.resolve(member); - if (!resolvedMember) return []; + if (!resolvedMember) { + return []; + } const resolvedRoles = roles ?? resolvedMember.roles.cache; const roleOverwrites = []; @@ -281,7 +298,10 @@ class GuildChannel extends BaseChannel { * @returns {Promise} */ async lockPermissions() { - if (!this.parent) throw new DiscordjsError(ErrorCodes.GuildChannelOrphan); + if (!this.parent) { + throw new DiscordjsError(ErrorCodes.GuildChannelOrphan); + } + const permissionOverwrites = this.parent.permissionOverwrites.cache.map(overwrite => overwrite.toJSON()); return this.edit({ permissionOverwrites }); } @@ -462,13 +482,23 @@ class GuildChannel extends BaseChannel { * @readonly */ get manageable() { - if (this.client.user.id === this.guild.ownerId) return true; + if (this.client.user.id === this.guild.ownerId) { + return true; + } + const permissions = this.permissionsFor(this.client.user); - if (!permissions) return false; + if (!permissions) { + return false; + } // This flag allows managing even if timed out - if (permissions.has(PermissionFlagsBits.Administrator, false)) return true; - if (this.guild.members.me.communicationDisabledUntilTimestamp > Date.now()) return false; + if (permissions.has(PermissionFlagsBits.Administrator, false)) { + return true; + } + + if (this.guild.members.me.communicationDisabledUntilTimestamp > Date.now()) { + return false; + } const bitfield = VoiceBasedChannelTypes.includes(this.type) ? PermissionFlagsBits.ManageChannels | PermissionFlagsBits.Connect @@ -483,9 +513,15 @@ class GuildChannel extends BaseChannel { * @readonly */ get viewable() { - if (this.client.user.id === this.guild.ownerId) return true; + if (this.client.user.id === this.guild.ownerId) { + return true; + } + const permissions = this.permissionsFor(this.client.user); - if (!permissions) return false; + if (!permissions) { + return false; + } + return permissions.has(PermissionFlagsBits.ViewChannel, false); } diff --git a/packages/discord.js/src/structures/GuildEmoji.js b/packages/discord.js/src/structures/GuildEmoji.js index 2e673e8dd..7ed92f20d 100644 --- a/packages/discord.js/src/structures/GuildEmoji.js +++ b/packages/discord.js/src/structures/GuildEmoji.js @@ -49,8 +49,13 @@ class GuildEmoji extends BaseGuildEmoji { _patch(data) { super._patch(data); - if (data.user) this.author = this.client.users._add(data.user); - if (data.roles) this._roles = data.roles; + if (data.user) { + this.author = this.client.users._add(data.user); + } + + if (data.roles) { + this._roles = data.roles; + } } /** @@ -60,7 +65,10 @@ class GuildEmoji extends BaseGuildEmoji { * @readonly */ get deletable() { - if (!this.guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe); + if (!this.guild.members.me) { + throw new DiscordjsError(ErrorCodes.GuildUncachedMe); + } + return !this.managed && this.guild.members.me.permissions.has(PermissionFlagsBits.ManageGuildExpressions); } diff --git a/packages/discord.js/src/structures/GuildInvite.js b/packages/discord.js/src/structures/GuildInvite.js index 2ac2c2cbb..508ebdbee 100644 --- a/packages/discord.js/src/structures/GuildInvite.js +++ b/packages/discord.js/src/structures/GuildInvite.js @@ -188,8 +188,14 @@ class GuildInvite extends BaseInvite { */ get deletable() { const guild = this.guild; - if (!guild || !this.client.guilds.cache.has(guild.id)) return false; - if (!guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe); + if (!guild || !this.client.guilds.cache.has(guild.id)) { + return false; + } + + if (!guild.members.me) { + throw new DiscordjsError(ErrorCodes.GuildUncachedMe); + } + return Boolean( this.channel?.permissionsFor(this.client.user).has(PermissionFlagsBits.ManageChannels, false) || guild.members.me.permissions.has(PermissionFlagsBits.ManageGuild), diff --git a/packages/discord.js/src/structures/GuildMember.js b/packages/discord.js/src/structures/GuildMember.js index 065cd06a5..baec8e27f 100644 --- a/packages/discord.js/src/structures/GuildMember.js +++ b/packages/discord.js/src/structures/GuildMember.js @@ -68,7 +68,9 @@ class GuildMember extends Base { */ Object.defineProperty(this, '_roles', { value: [], writable: true }); - if (data) this._patch(data); + if (data) { + this._patch(data); + } } _patch(data) { @@ -81,7 +83,10 @@ class GuildMember extends Base { this.user = this.client.users._add(data.user, true); } - if ('nick' in data) this.nickname = data.nick; + if ('nick' in data) { + this.nickname = data.nick; + } + if ('avatar' in data) { /** * The guild member's avatar hash @@ -104,12 +109,17 @@ class GuildMember extends Base { this.banner ??= null; } - if ('joined_at' in data) this.joinedTimestamp = Date.parse(data.joined_at); + if ('joined_at' in data) { + this.joinedTimestamp = Date.parse(data.joined_at); + } + if ('premium_since' in data) { this.premiumSinceTimestamp = data.premium_since ? Date.parse(data.premium_since) : null; } - if ('roles' in data) this._roles = data.roles; + if ('roles' in data) { + this._roles = data.roles; + } if ('pending' in data) { this.pending = data.pending; @@ -343,7 +353,10 @@ class GuildMember extends Base { * @readonly */ get permissions() { - if (this.user.id === this.guild.ownerId) return new PermissionsBitField(PermissionsBitField.All).freeze(); + if (this.user.id === this.guild.ownerId) { + return new PermissionsBitField(PermissionsBitField.All).freeze(); + } + return new PermissionsBitField(this.roles.cache.map(role => role.permissions)).freeze(); } @@ -355,10 +368,22 @@ class GuildMember extends Base { * @readonly */ get manageable() { - if (this.user.id === this.guild.ownerId) return false; - if (this.user.id === this.client.user.id) return false; - if (this.client.user.id === this.guild.ownerId) return true; - if (!this.guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe); + if (this.user.id === this.guild.ownerId) { + return false; + } + + if (this.user.id === this.client.user.id) { + return false; + } + + if (this.client.user.id === this.guild.ownerId) { + return true; + } + + if (!this.guild.members.me) { + throw new DiscordjsError(ErrorCodes.GuildUncachedMe); + } + return this.guild.members.me.roles.highest.comparePositionTo(this.roles.highest) > 0; } @@ -369,7 +394,10 @@ class GuildMember extends Base { * @readonly */ get kickable() { - if (!this.guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe); + if (!this.guild.members.me) { + throw new DiscordjsError(ErrorCodes.GuildUncachedMe); + } + return this.manageable && this.guild.members.me.permissions.has(PermissionFlagsBits.KickMembers); } @@ -380,7 +408,10 @@ class GuildMember extends Base { * @readonly */ get bannable() { - if (!this.guild.members.me) throw new DiscordjsError(ErrorCodes.GuildUncachedMe); + if (!this.guild.members.me) { + throw new DiscordjsError(ErrorCodes.GuildUncachedMe); + } + return this.manageable && this.guild.members.me.permissions.has(PermissionFlagsBits.BanMembers); } @@ -416,7 +447,10 @@ class GuildMember extends Base { */ permissionsIn(channel) { const resolvedChannel = this.guild.channels.resolve(channel); - if (!resolvedChannel) throw new DiscordjsError(ErrorCodes.GuildChannelResolve); + if (!resolvedChannel) { + throw new DiscordjsError(ErrorCodes.GuildChannelResolve); + } + return resolvedChannel.permissionsFor(this); } diff --git a/packages/discord.js/src/structures/GuildOnboardingPromptOption.js b/packages/discord.js/src/structures/GuildOnboardingPromptOption.js index 7c78f51a0..b043bfdbb 100644 --- a/packages/discord.js/src/structures/GuildOnboardingPromptOption.js +++ b/packages/discord.js/src/structures/GuildOnboardingPromptOption.js @@ -88,7 +88,10 @@ class GuildOnboardingPromptOption extends Base { * @type {?(GuildEmoji|Emoji)} */ get emoji() { - if (!this._emoji.id && !this._emoji.name) return null; + if (!this._emoji.id && !this._emoji.name) { + return null; + } + return this.guild.emojis.cache.get(this._emoji.id) ?? new Emoji(this.client, this._emoji); } } diff --git a/packages/discord.js/src/structures/GuildPreview.js b/packages/discord.js/src/structures/GuildPreview.js index 08e0fbbfc..167d7c9ef 100644 --- a/packages/discord.js/src/structures/GuildPreview.js +++ b/packages/discord.js/src/structures/GuildPreview.js @@ -16,7 +16,9 @@ class GuildPreview extends Base { constructor(client, data) { super(client); - if (!data) return; + if (!data) { + return; + } this._patch(data); } diff --git a/packages/discord.js/src/structures/GuildScheduledEvent.js b/packages/discord.js/src/structures/GuildScheduledEvent.js index 50914fc28..44a116d50 100644 --- a/packages/discord.js/src/structures/GuildScheduledEvent.js +++ b/packages/discord.js/src/structures/GuildScheduledEvent.js @@ -369,9 +369,14 @@ class GuildScheduledEvent extends Base { async createInviteURL(options) { let channelId = this.channelId; if (this.entityType === GuildScheduledEventEntityType.External) { - if (!options?.channel) throw new DiscordjsError(ErrorCodes.InviteOptionsMissingChannel); + if (!options?.channel) { + throw new DiscordjsError(ErrorCodes.InviteOptionsMissingChannel); + } + channelId = this.guild.channels.resolveId(options.channel); - if (!channelId) throw new DiscordjsError(ErrorCodes.GuildChannelResolve); + if (!channelId) { + throw new DiscordjsError(ErrorCodes.GuildChannelResolve); + } } const invite = await this.guild.invites.create(channelId, options); diff --git a/packages/discord.js/src/structures/InteractionCollector.js b/packages/discord.js/src/structures/InteractionCollector.js index 9443310bb..9be7e4995 100644 --- a/packages/discord.js/src/structures/InteractionCollector.js +++ b/packages/discord.js/src/structures/InteractionCollector.js @@ -92,7 +92,9 @@ class InteractionCollector extends Collector { this.client.incrementMaxListeners(); const bulkDeleteListener = messages => { - if (messages.has(this.messageId)) this.stop('messageDelete'); + if (messages.has(this.messageId)) { + this.stop('messageDelete'); + } }; if (this.messageId) { @@ -146,11 +148,25 @@ class InteractionCollector extends Collector { * @param {BaseInteraction} interaction The interaction that was collected */ - if (this.interactionType && interaction.type !== this.interactionType) return null; - if (this.componentType && interaction.componentType !== this.componentType) return null; - if (this.messageId && interaction.message?.id !== this.messageId) return null; - if (this.channelId && interaction.channelId !== this.channelId) return null; - if (this.guildId && interaction.guildId !== this.guildId) return null; + if (this.interactionType && interaction.type !== this.interactionType) { + return null; + } + + if (this.componentType && interaction.componentType !== this.componentType) { + return null; + } + + if (this.messageId && interaction.message?.id !== this.messageId) { + return null; + } + + if (this.channelId && interaction.channelId !== this.channelId) { + return null; + } + + if (this.guildId && interaction.guildId !== this.guildId) { + return null; + } return interaction.id; } @@ -168,11 +184,25 @@ class InteractionCollector extends Collector { * @event InteractionCollector#dispose * @param {BaseInteraction} interaction The interaction that was disposed of */ - if (this.type && interaction.type !== this.type) return null; - if (this.componentType && interaction.componentType !== this.componentType) return null; - if (this.messageId && interaction.message?.id !== this.messageId) return null; - if (this.channelId && interaction.channelId !== this.channelId) return null; - if (this.guildId && interaction.guildId !== this.guildId) return null; + if (this.type && interaction.type !== this.type) { + return null; + } + + if (this.componentType && interaction.componentType !== this.componentType) { + return null; + } + + if (this.messageId && interaction.message?.id !== this.messageId) { + return null; + } + + if (this.channelId && interaction.channelId !== this.channelId) { + return null; + } + + if (this.guildId && interaction.guildId !== this.guildId) { + return null; + } return interaction.id; } @@ -194,9 +224,18 @@ class InteractionCollector extends Collector { * @readonly */ get endReason() { - if (this.options.max && this.total >= this.options.max) return 'limit'; - if (this.options.maxComponents && this.collected.size >= this.options.maxComponents) return 'componentLimit'; - if (this.options.maxUsers && this.users.size >= this.options.maxUsers) return 'userLimit'; + if (this.options.max && this.total >= this.options.max) { + return 'limit'; + } + + if (this.options.maxComponents && this.collected.size >= this.options.maxComponents) { + return 'componentLimit'; + } + + if (this.options.maxUsers && this.users.size >= this.options.maxUsers) { + return 'userLimit'; + } + return super.endReason; } diff --git a/packages/discord.js/src/structures/Message.js b/packages/discord.js/src/structures/Message.js index fd49f1d72..f0645f622 100644 --- a/packages/discord.js/src/structures/Message.js +++ b/packages/discord.js/src/structures/Message.js @@ -646,8 +646,11 @@ class Message extends Base { return new Promise((resolve, reject) => { const collector = this.createReactionCollector(options); collector.once('end', (reactions, reason) => { - if (options.errors?.includes(reason)) reject(reactions); - else resolve(reactions); + if (options.errors?.includes(reason)) { + reject(reactions); + } else { + resolve(reactions); + } }); }); } @@ -710,8 +713,11 @@ class Message extends Base { const collector = this.createMessageComponentCollector(_options); collector.once('end', (interactions, reason) => { const interaction = interactions.first(); - if (interaction) resolve(interaction); - else reject(new DiscordjsError(ErrorCodes.InteractionCollectorError, reason)); + if (interaction) { + resolve(interaction); + } else { + reject(new DiscordjsError(ErrorCodes.InteractionCollectorError, reason)); + } }); }); } @@ -732,10 +738,15 @@ class Message extends Base { // Regardless of permissions thread messages cannot be edited if // the thread is archived or the thread is locked and the bot does not have permission to manage threads. if (this.channel?.isThread()) { - if (this.channel.archived) return false; + if (this.channel.archived) { + return false; + } + if (this.channel.locked) { const permissions = this.channel.permissionsFor(this.client.user); - if (!permissions?.has(PermissionFlagsBits.ManageThreads, true)) return false; + if (!permissions?.has(PermissionFlagsBits.ManageThreads, true)) { + return false; + } } } @@ -749,7 +760,9 @@ class Message extends Base { * @readonly */ get deletable() { - if (UndeletableMessageTypes.includes(this.type)) return false; + if (UndeletableMessageTypes.includes(this.type)) { + return false; + } if (!this.guild) { return this.author.id === this.client.user.id; @@ -761,9 +774,14 @@ class Message extends Base { } const permissions = this.channel?.permissionsFor(this.client.user); - if (!permissions) return false; + if (!permissions) { + return false; + } + // This flag allows deleting even if timed out - if (permissions.has(PermissionFlagsBits.Administrator, false)) return true; + if (permissions.has(PermissionFlagsBits.Administrator, false)) { + return true; + } // The auto moderation action message author is the reference message author return ( @@ -813,11 +831,20 @@ class Message extends Base { * @returns {Promise} */ async fetchReference() { - if (!this.reference) throw new DiscordjsError(ErrorCodes.MessageReferenceMissing); + if (!this.reference) { + throw new DiscordjsError(ErrorCodes.MessageReferenceMissing); + } + const { channelId, messageId } = this.reference; - if (!messageId) throw new DiscordjsError(ErrorCodes.MessageReferenceMissing); + if (!messageId) { + throw new DiscordjsError(ErrorCodes.MessageReferenceMissing); + } + const channel = this.client.channels.resolve(channelId); - if (!channel) throw new DiscordjsError(ErrorCodes.GuildChannelResolve); + if (!channel) { + throw new DiscordjsError(ErrorCodes.GuildChannelResolve); + } + return channel.messages.fetch(messageId); } @@ -855,7 +882,10 @@ class Message extends Base { * .catch(console.error); */ async edit(options) { - if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached); + if (!this.channel) { + throw new DiscordjsError(ErrorCodes.ChannelNotCached); + } + return this.channel.messages.edit(this, options); } @@ -872,7 +902,10 @@ class Message extends Base { * } */ async crosspost() { - if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached); + if (!this.channel) { + throw new DiscordjsError(ErrorCodes.ChannelNotCached); + } + return this.channel.messages.crosspost(this.id); } @@ -888,7 +921,10 @@ class Message extends Base { * .catch(console.error) */ async pin(reason) { - if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached); + if (!this.channel) { + throw new DiscordjsError(ErrorCodes.ChannelNotCached); + } + await this.channel.messages.pin(this.id, reason); return this; } @@ -905,7 +941,10 @@ class Message extends Base { * .catch(console.error) */ async unpin(reason) { - if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached); + if (!this.channel) { + throw new DiscordjsError(ErrorCodes.ChannelNotCached); + } + await this.channel.messages.unpin(this.id, reason); return this; } @@ -927,7 +966,10 @@ class Message extends Base { * .catch(console.error); */ async react(emoji) { - if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached); + if (!this.channel) { + throw new DiscordjsError(ErrorCodes.ChannelNotCached); + } + await this.channel.messages.react(this.id, emoji); return this.client.actions.MessageReactionAdd.handle( @@ -952,7 +994,10 @@ class Message extends Base { * .catch(console.error); */ async delete() { - if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached); + if (!this.channel) { + throw new DiscordjsError(ErrorCodes.ChannelNotCached); + } + await this.channel.messages.delete(this.id); return this; } @@ -1032,12 +1077,18 @@ class Message extends Base { * @returns {Promise} */ async startThread(options = {}) { - if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached); + if (!this.channel) { + throw new DiscordjsError(ErrorCodes.ChannelNotCached); + } + if (![ChannelType.GuildText, ChannelType.GuildAnnouncement].includes(this.channel.type)) { throw new DiscordjsError(ErrorCodes.MessageThreadParent); } - if (this.hasThread) throw new DiscordjsError(ErrorCodes.MessageExistingThread); + if (this.hasThread) { + throw new DiscordjsError(ErrorCodes.MessageExistingThread); + } + return this.channel.threads.create({ ...options, startMessage: this }); } @@ -1048,7 +1099,10 @@ class Message extends Base { * @returns {Promise} */ async fetch(force = true) { - if (!this.channel) throw new DiscordjsError(ErrorCodes.ChannelNotCached); + if (!this.channel) { + throw new DiscordjsError(ErrorCodes.ChannelNotCached); + } + return this.channel.messages.fetch({ message: this.id, force }); } @@ -1058,8 +1112,14 @@ class Message extends Base { * @returns {Promise} */ async fetchWebhook() { - if (!this.webhookId) throw new DiscordjsError(ErrorCodes.WebhookMessage); - if (this.webhookId === this.applicationId) throw new DiscordjsError(ErrorCodes.WebhookApplication); + if (!this.webhookId) { + throw new DiscordjsError(ErrorCodes.WebhookMessage); + } + + if (this.webhookId === this.applicationId) { + throw new DiscordjsError(ErrorCodes.WebhookApplication); + } + return this.client.fetchWebhook(this.webhookId); } @@ -1110,9 +1170,14 @@ class Message extends Base { * @returns {boolean} */ equals(message, rawData) { - if (!message) return false; + if (!message) { + return false; + } + const embedUpdate = !message.author && !message.attachments; - if (embedUpdate) return this.id === message.id && this.embeds.length === message.embeds.length; + if (embedUpdate) { + return this.id === message.id && this.embeds.length === message.embeds.length; + } let equal = this.id === message.id && diff --git a/packages/discord.js/src/structures/MessageCollector.js b/packages/discord.js/src/structures/MessageCollector.js index 257472828..4a4cd496f 100644 --- a/packages/discord.js/src/structures/MessageCollector.js +++ b/packages/discord.js/src/structures/MessageCollector.js @@ -41,7 +41,9 @@ class MessageCollector extends Collector { this.received = 0; const bulkDeleteListener = async messages => { - for (const message of messages.values()) await this.handleDispose(message); + for (const message of messages.values()) { + await this.handleDispose(message); + } }; this._handleChannelDeletion = this._handleChannelDeletion.bind(this); @@ -81,7 +83,10 @@ class MessageCollector extends Collector { * @event MessageCollector#collect * @param {Message} message The message that was collected */ - if (message.channelId !== this.channel.id) return null; + if (message.channelId !== this.channel.id) { + return null; + } + this.received++; return message.id; } @@ -109,8 +114,14 @@ class MessageCollector extends Collector { * @readonly */ get endReason() { - if (this.options.max && this.collected.size >= this.options.max) return 'limit'; - if (this.options.maxProcessed && this.received === this.options.maxProcessed) return 'processedLimit'; + if (this.options.max && this.collected.size >= this.options.max) { + return 'limit'; + } + + if (this.options.maxProcessed && this.received === this.options.maxProcessed) { + return 'processedLimit'; + } + return super.endReason; } diff --git a/packages/discord.js/src/structures/MessageMentions.js b/packages/discord.js/src/structures/MessageMentions.js index fdb2e0c77..4a06ea8f5 100644 --- a/packages/discord.js/src/structures/MessageMentions.js +++ b/packages/discord.js/src/structures/MessageMentions.js @@ -133,7 +133,9 @@ class MessageMentions { if (guild) { for (const mention of roles) { const role = guild.roles.cache.get(mention); - if (role) this.roles.set(role.id, role); + if (role) { + this.roles.set(role.id, role); + } } } } else { @@ -214,12 +216,20 @@ class MessageMentions { * @readonly */ get members() { - if (this._members) return this._members; - if (!this.guild) return null; + if (this._members) { + return this._members; + } + + if (!this.guild) { + return null; + } + this._members = new Collection(); for (const user of this.users.values()) { const member = this.guild.members.resolve(user); - if (member) this._members.set(member.user.id, member); + if (member) { + this._members.set(member.user.id, member); + } } return this._members; @@ -233,13 +243,18 @@ class MessageMentions { * @readonly */ get channels() { - if (this._channels) return this._channels; + if (this._channels) { + return this._channels; + } + this._channels = new Collection(); let matches; while ((matches = this.constructor.GlobalChannelsPattern.exec(this._content)) !== null) { const channel = this.client.channels.cache.get(matches.groups.id); - if (channel) this._channels.set(channel.id, channel); + if (channel) { + this._channels.set(channel.id, channel); + } } return this._channels; @@ -253,12 +268,17 @@ class MessageMentions { * @readonly */ get parsedUsers() { - if (this._parsedUsers) return this._parsedUsers; + if (this._parsedUsers) { + return this._parsedUsers; + } + this._parsedUsers = new Collection(); let matches; while ((matches = this.constructor.GlobalUsersPattern.exec(this._content)) !== null) { const user = this.client.users.cache.get(matches[1]); - if (user) this._parsedUsers.set(user.id, user); + if (user) { + this._parsedUsers.set(user.id, user); + } } return this._parsedUsers; @@ -286,26 +306,40 @@ class MessageMentions { has(data, { ignoreDirect = false, ignoreRoles = false, ignoreRepliedUser = false, ignoreEveryone = false } = {}) { const user = this.client.users.resolve(data); - if (!ignoreEveryone && user && this.everyone) return true; + if (!ignoreEveryone && user && this.everyone) { + return true; + } const userWasRepliedTo = user && this.repliedUser?.id === user.id; - if (!ignoreRepliedUser && userWasRepliedTo && this.users.has(user.id)) return true; + if (!ignoreRepliedUser && userWasRepliedTo && this.users.has(user.id)) { + return true; + } if (!ignoreDirect) { - if (user && (!ignoreRepliedUser || this.parsedUsers.has(user.id)) && this.users.has(user.id)) return true; + if (user && (!ignoreRepliedUser || this.parsedUsers.has(user.id)) && this.users.has(user.id)) { + return true; + } const role = this.guild?.roles.resolve(data); - if (role && this.roles.has(role.id)) return true; + if (role && this.roles.has(role.id)) { + return true; + } const channel = this.client.channels.resolve(data); - if (channel && this.channels.has(channel.id)) return true; + if (channel && this.channels.has(channel.id)) { + return true; + } } if (!ignoreRoles) { const member = this.guild?.members.resolve(data); if (member) { - for (const mentionedRole of this.roles.values()) if (member.roles.cache.has(mentionedRole.id)) return true; + for (const mentionedRole of this.roles.values()) { + if (member.roles.cache.has(mentionedRole.id)) { + return true; + } + } } } diff --git a/packages/discord.js/src/structures/MessagePayload.js b/packages/discord.js/src/structures/MessagePayload.js index 58d62c92f..f14b5f5bf 100644 --- a/packages/discord.js/src/structures/MessagePayload.js +++ b/packages/discord.js/src/structures/MessagePayload.js @@ -114,7 +114,10 @@ class MessagePayload { * @returns {MessagePayload} */ resolveBody() { - if (this.body) return this; + if (this.body) { + return this; + } + const isWebhook = this.isWebhook; const content = this.makeContent(); @@ -151,9 +154,17 @@ class MessagePayload { let appliedTags; if (isWebhook) { username = this.options.username ?? this.target.name; - if (this.options.avatarURL) avatarURL = this.options.avatarURL; - if (this.options.threadName) threadName = this.options.threadName; - if (this.options.appliedTags) appliedTags = this.options.appliedTags; + if (this.options.avatarURL) { + avatarURL = this.options.avatarURL; + } + + if (this.options.threadName) { + threadName = this.options.threadName; + } + + if (this.options.appliedTags) { + appliedTags = this.options.appliedTags; + } } let flags; @@ -251,7 +262,9 @@ class MessagePayload { * @returns {Promise} */ async resolveFiles() { - if (this.files) return this; + if (this.files) { + return this; + } this.files = await Promise.all(this.options.files?.map(file => this.constructor.resolveFile(file)) ?? []); return this; diff --git a/packages/discord.js/src/structures/MessageReaction.js b/packages/discord.js/src/structures/MessageReaction.js index 145ebdf42..3dd955b0e 100644 --- a/packages/discord.js/src/structures/MessageReaction.js +++ b/packages/discord.js/src/structures/MessageReaction.js @@ -129,8 +129,14 @@ class MessageReaction { * @readonly */ get emoji() { - if (this._emoji instanceof GuildEmoji) return this._emoji; - if (this._emoji instanceof ApplicationEmoji) return this._emoji; + if (this._emoji instanceof GuildEmoji) { + return this._emoji; + } + + if (this._emoji instanceof ApplicationEmoji) { + return this._emoji; + } + // Check to see if the emoji has become known to the client if (this._emoji.id) { const applicationEmojis = this.message.client.application.emojis.cache; @@ -177,32 +183,50 @@ class MessageReaction { } _add(user, burst) { - if (this.partial) return; + if (this.partial) { + return; + } + this.users.cache.set(user.id, user); if (!this.me || user.id !== this.message.client.user.id || this.count === 0) { this.count++; - if (burst) this.countDetails.burst++; - else this.countDetails.normal++; + if (burst) { + this.countDetails.burst++; + } else { + this.countDetails.normal++; + } } if (user.id === this.message.client.user.id) { - if (burst) this.meBurst = true; - else this.me = true; + if (burst) { + this.meBurst = true; + } else { + this.me = true; + } } } _remove(user, burst) { - if (this.partial) return; + if (this.partial) { + return; + } + this.users.cache.delete(user.id); if (!this.me || user.id !== this.message.client.user.id) { this.count--; - if (burst) this.countDetails.burst--; - else this.countDetails.normal--; + if (burst) { + this.countDetails.burst--; + } else { + this.countDetails.normal--; + } } if (user.id === this.message.client.user.id) { - if (burst) this.meBurst = false; - else this.me = false; + if (burst) { + this.meBurst = false; + } else { + this.me = false; + } } if (this.count <= 0 && this.users.cache.size === 0) { diff --git a/packages/discord.js/src/structures/ModalComponentResolver.js b/packages/discord.js/src/structures/ModalComponentResolver.js index 3991316cd..d07dd28cf 100644 --- a/packages/discord.js/src/structures/ModalComponentResolver.js +++ b/packages/discord.js/src/structures/ModalComponentResolver.js @@ -48,7 +48,9 @@ class ModalComponentResolver { this.hoistedComponents = components.reduce((accumulator, next) => { // For legacy support of action rows if ('components' in next) { - for (const component of next.components) accumulator.set(component.customId, component); + for (const component of next.components) { + accumulator.set(component.customId, component); + } } // For label components @@ -69,7 +71,9 @@ class ModalComponentResolver { getComponent(customId) { const component = this.hoistedComponents.get(customId); - if (!component) throw new DiscordjsTypeError(ErrorCodes.ModalSubmitInteractionComponentNotFound, customId); + if (!component) { + throw new DiscordjsTypeError(ErrorCodes.ModalSubmitInteractionComponentNotFound, customId); + } return component; } diff --git a/packages/discord.js/src/structures/ModalSubmitInteraction.js b/packages/discord.js/src/structures/ModalSubmitInteraction.js index 2cb92f1d1..cfb91c364 100644 --- a/packages/discord.js/src/structures/ModalSubmitInteraction.js +++ b/packages/discord.js/src/structures/ModalSubmitInteraction.js @@ -148,9 +148,13 @@ class ModalSubmitInteraction extends BaseInteraction { }; // Text display components do not have custom ids. - if ('custom_id' in rawComponent) data.customId = rawComponent.custom_id; + if ('custom_id' in rawComponent) { + data.customId = rawComponent.custom_id; + } - if ('value' in rawComponent) data.value = rawComponent.value; + if ('value' in rawComponent) { + data.value = rawComponent.value; + } if (rawComponent.values) { data.values = rawComponent.values; @@ -167,19 +171,27 @@ class ModalSubmitInteraction extends BaseInteraction { }; const users = resolveCollection(resolved.users, user => this.client.users._add(user)); - if (users) data.users = users; + if (users) { + data.users = users; + } const channels = resolveCollection( resolved.channels, channel => this.client.channels._add(channel, this.guild) ?? channel, ); - if (channels) data.channels = channels; + if (channels) { + data.channels = channels; + } const members = resolveCollection(resolved.members, member => this.guild?.members._add(member) ?? member); - if (members) data.members = members; + if (members) { + data.members = members; + } const roles = resolveCollection(resolved.roles, role => this.guild?.roles._add(role) ?? role); - if (roles) data.roles = roles; + if (roles) { + data.roles = roles; + } } } diff --git a/packages/discord.js/src/structures/PermissionOverwrites.js b/packages/discord.js/src/structures/PermissionOverwrites.js index ea7d96d82..998ef995e 100644 --- a/packages/discord.js/src/structures/PermissionOverwrites.js +++ b/packages/discord.js/src/structures/PermissionOverwrites.js @@ -24,7 +24,9 @@ class PermissionOverwrites extends Base { */ Object.defineProperty(this, 'channel', { value: channel }); - if (data) this._patch(data); + if (data) { + this._patch(data); + } } _patch(data) { @@ -184,7 +186,9 @@ class PermissionOverwrites extends Base { * @returns {RawOverwriteData} */ static resolve(overwrite, guild) { - if (overwrite instanceof this) return overwrite.toJSON(); + if (overwrite instanceof this) { + return overwrite.toJSON(); + } const id = guild.roles.resolveId(overwrite.id) ?? guild.client.users.resolveId(overwrite.id); if (!id) { diff --git a/packages/discord.js/src/structures/PollAnswer.js b/packages/discord.js/src/structures/PollAnswer.js index f6e736c9c..76640795a 100644 --- a/packages/discord.js/src/structures/PollAnswer.js +++ b/packages/discord.js/src/structures/PollAnswer.js @@ -80,7 +80,10 @@ class PollAnswer extends Base { * @type {?(GuildEmoji|Emoji)} */ get emoji() { - if (!this._emoji || (!this._emoji.id && !this._emoji.name)) return null; + if (!this._emoji || (!this._emoji.id && !this._emoji.name)) { + return null; + } + return resolveGuildEmoji(this.client, this._emoji.id) ?? new Emoji(this.client, this._emoji); } diff --git a/packages/discord.js/src/structures/Presence.js b/packages/discord.js/src/structures/Presence.js index de5ca9f97..4c3206e8e 100644 --- a/packages/discord.js/src/structures/Presence.js +++ b/packages/discord.js/src/structures/Presence.js @@ -382,7 +382,10 @@ class RichPresenceAssets { * @returns {?string} */ smallImageURL(options = {}) { - if (!this.smallImage) return null; + if (!this.smallImage) { + return null; + } + if (this.smallImage.includes(':')) { const [platform, id] = this.smallImage.split(':'); switch (platform) { @@ -403,7 +406,10 @@ class RichPresenceAssets { * @returns {?string} */ largeImageURL(options = {}) { - if (!this.largeImage) return null; + if (!this.largeImage) { + return null; + } + if (this.largeImage.includes(':')) { const [platform, id] = this.largeImage.split(':'); switch (platform) { diff --git a/packages/discord.js/src/structures/ReactionCollector.js b/packages/discord.js/src/structures/ReactionCollector.js index 13c484e97..63744b10c 100644 --- a/packages/discord.js/src/structures/ReactionCollector.js +++ b/packages/discord.js/src/structures/ReactionCollector.js @@ -57,7 +57,9 @@ class ReactionCollector extends Collector { this._handleMessageDeletion = this._handleMessageDeletion.bind(this); const bulkDeleteListener = messages => { - if (messages.has(this.message.id)) this.stop('messageDelete'); + if (messages.has(this.message.id)) { + this.stop('messageDelete'); + } }; this.client.incrementMaxListeners(); @@ -102,7 +104,9 @@ class ReactionCollector extends Collector { this.on('remove', (_reaction, user) => { this.total--; - if (!this.collected.some(reaction => reaction.users.cache.has(user.id))) this.users.delete(user.id); + if (!this.collected.some(reaction => reaction.users.cache.has(user.id))) { + this.users.delete(user.id); + } }); } @@ -121,7 +125,9 @@ class ReactionCollector extends Collector { * @param {MessageReaction} reaction The reaction that was collected * @param {User} user The user that added the reaction */ - if (reaction.message.id !== this.message.id) return null; + if (reaction.message.id !== this.message.id) { + return null; + } return ReactionCollector.key(reaction); } @@ -141,7 +147,9 @@ class ReactionCollector extends Collector { * @param {MessageReaction} reaction The reaction that was disposed of * @param {User} user The user that removed the reaction */ - if (reaction.message.id !== this.message.id) return null; + if (reaction.message.id !== this.message.id) { + return null; + } /** * Emitted when the reaction had one user removed and the `dispose` option is set to true. @@ -174,9 +182,18 @@ class ReactionCollector extends Collector { * @readonly */ get endReason() { - if (this.options.max && this.total >= this.options.max) return 'limit'; - if (this.options.maxEmojis && this.collected.size >= this.options.maxEmojis) return 'emojiLimit'; - if (this.options.maxUsers && this.users.size >= this.options.maxUsers) return 'userLimit'; + if (this.options.max && this.total >= this.options.max) { + return 'limit'; + } + + if (this.options.maxEmojis && this.collected.size >= this.options.maxEmojis) { + return 'emojiLimit'; + } + + if (this.options.maxUsers && this.users.size >= this.options.maxUsers) { + return 'userLimit'; + } + return super.endReason; } diff --git a/packages/discord.js/src/structures/Role.js b/packages/discord.js/src/structures/Role.js index 4f58186ac..bd3f94640 100644 --- a/packages/discord.js/src/structures/Role.js +++ b/packages/discord.js/src/structures/Role.js @@ -38,7 +38,9 @@ class Role extends Base { */ this.unicodeEmoji = null; - if (data) this._patch(data); + if (data) { + this._patch(data); + } } _patch(data) { @@ -125,9 +127,13 @@ class Role extends Base { this.mentionable = data.mentionable; } - if ('icon' in data) this.icon = data.icon; + if ('icon' in data) { + this.icon = data.icon; + } - if ('unicode_emoji' in data) this.unicodeEmoji = data.unicode_emoji; + if ('unicode_emoji' in data) { + this.unicodeEmoji = data.unicode_emoji; + } if ('flags' in data) { /** @@ -228,9 +234,15 @@ class Role extends Base { * @readonly */ get editable() { - if (this.managed) return false; + if (this.managed) { + return false; + } + const clientMember = this.guild.members.resolve(this.client.user); - if (!clientMember.permissions.has(PermissionFlagsBits.ManageRoles)) return false; + if (!clientMember.permissions.has(PermissionFlagsBits.ManageRoles)) { + return false; + } + return clientMember.roles.highest.comparePositionTo(this) > 0; } @@ -308,7 +320,10 @@ class Role extends Base { */ permissionsIn(channel, checkAdmin = true) { const resolvedChannel = this.guild.channels.resolve(channel); - if (!resolvedChannel) throw new DiscordjsError(ErrorCodes.GuildChannelResolve); + if (!resolvedChannel) { + throw new DiscordjsError(ErrorCodes.GuildChannelResolve); + } + return resolvedChannel.rolePermissions(this, checkAdmin); } @@ -519,7 +534,10 @@ class Role extends Base { * console.log(`Role: ${role}`); */ toString() { - if (this.id === this.guild.id) return '@everyone'; + if (this.id === this.guild.id) { + return '@everyone'; + } + return roleMention(this.id); } diff --git a/packages/discord.js/src/structures/SoundboardSound.js b/packages/discord.js/src/structures/SoundboardSound.js index b0f85394d..62b375b52 100644 --- a/packages/discord.js/src/structures/SoundboardSound.js +++ b/packages/discord.js/src/structures/SoundboardSound.js @@ -123,7 +123,9 @@ class SoundboardSound extends Base { * @readonly */ get emoji() { - if (!this._emoji) return null; + if (!this._emoji) { + return null; + } return this.guild?.emojis.cache.get(this._emoji.id) ?? new Emoji(this.client, this._emoji); } @@ -160,7 +162,9 @@ class SoundboardSound extends Base { * .catch(console.error); */ async edit(options) { - if (!this.guildId) throw new DiscordjsError(ErrorCodes.NotGuildSoundboardSound, 'edited'); + if (!this.guildId) { + throw new DiscordjsError(ErrorCodes.NotGuildSoundboardSound, 'edited'); + } return this.guild.soundboardSounds.edit(this, options); } @@ -177,7 +181,9 @@ class SoundboardSound extends Base { * .catch(console.error); */ async delete(reason) { - if (!this.guildId) throw new DiscordjsError(ErrorCodes.NotGuildSoundboardSound, 'deleted'); + if (!this.guildId) { + throw new DiscordjsError(ErrorCodes.NotGuildSoundboardSound, 'deleted'); + } await this.guild.soundboardSounds.delete(this, reason); diff --git a/packages/discord.js/src/structures/Sticker.js b/packages/discord.js/src/structures/Sticker.js index a181cf6af..c61bcde31 100644 --- a/packages/discord.js/src/structures/Sticker.js +++ b/packages/discord.js/src/structures/Sticker.js @@ -202,7 +202,10 @@ class Sticker extends Base { * @returns {Promise} The sticker pack or `null` if this sticker does not belong to one. */ async fetchPack() { - if (!this.packId) return null; + if (!this.packId) { + return null; + } + return this.client.fetchStickerPacks({ packId: this.packId }); } @@ -212,8 +215,14 @@ class Sticker extends Base { * @returns {Promise} */ async fetchUser() { - if (this.partial) await this.fetch(); - if (!this.guildId) throw new DiscordjsError(ErrorCodes.NotGuildSticker); + if (this.partial) { + await this.fetch(); + } + + if (!this.guildId) { + throw new DiscordjsError(ErrorCodes.NotGuildSticker); + } + return this.guild.stickers.fetchUser(this); } diff --git a/packages/discord.js/src/structures/ThreadChannel.js b/packages/discord.js/src/structures/ThreadChannel.js index 967a190b3..aaec73cde 100644 --- a/packages/discord.js/src/structures/ThreadChannel.js +++ b/packages/discord.js/src/structures/ThreadChannel.js @@ -55,13 +55,17 @@ class ThreadChannel extends BaseChannel { * @type {ThreadMemberManager} */ this.members = new ThreadMemberManager(this); - if (data) this._patch(data); + if (data) { + this._patch(data); + } } _patch(data) { super._patch(data); - if ('message' in data) this.messages._add(data.message); + if ('message' in data) { + this.messages._add(data.message); + } if ('name' in data) { /** @@ -212,8 +216,15 @@ class ThreadChannel extends BaseChannel { this.totalMessageSent ??= null; } - if (data.member && this.client.user) this.members._add({ user_id: this.client.user.id, ...data.member }); - if (data.messages) for (const message of data.messages) this.messages._add(message); + if (data.member && this.client.user) { + this.members._add({ user_id: this.client.user.id, ...data.member }); + } + + if (data.messages) { + for (const message of data.messages) { + this.messages._add(message); + } + } if ('applied_tags' in data) { /** @@ -565,9 +576,14 @@ class ThreadChannel extends BaseChannel { */ get manageable() { const permissions = this.permissionsFor(this.client.user); - if (!permissions) return false; + if (!permissions) { + return false; + } + // This flag allows managing even if timed out - if (permissions.has(PermissionFlagsBits.Administrator, false)) return true; + if (permissions.has(PermissionFlagsBits.Administrator, false)) { + return true; + } return ( this.guild.members.me.communicationDisabledUntilTimestamp < Date.now() && @@ -582,9 +598,15 @@ class ThreadChannel extends BaseChannel { * @readonly */ get viewable() { - if (this.client.user.id === this.guild.ownerId) return true; + if (this.client.user.id === this.guild.ownerId) { + return true; + } + const permissions = this.permissionsFor(this.client.user); - if (!permissions) return false; + if (!permissions) { + return false; + } + return permissions.has(PermissionFlagsBits.ViewChannel, false); } @@ -596,9 +618,14 @@ class ThreadChannel extends BaseChannel { */ get sendable() { const permissions = this.permissionsFor(this.client.user); - if (!permissions) return false; + if (!permissions) { + return false; + } + // This flag allows sending even if timed out - if (permissions.has(PermissionFlagsBits.Administrator, false)) return true; + if (permissions.has(PermissionFlagsBits.Administrator, false)) { + return true; + } return ( !(this.archived && this.locked && !this.manageable) && diff --git a/packages/discord.js/src/structures/ThreadMember.js b/packages/discord.js/src/structures/ThreadMember.js index 047ba212d..ed942bf90 100644 --- a/packages/discord.js/src/structures/ThreadMember.js +++ b/packages/discord.js/src/structures/ThreadMember.js @@ -44,8 +44,13 @@ class ThreadMember extends Base { } _patch(data, extra = {}) { - if ('join_timestamp' in data) this.joinedTimestamp = Date.parse(data.join_timestamp); - if ('flags' in data) this.flags = new ThreadMemberFlagsBitField(data.flags).freeze(); + if ('join_timestamp' in data) { + this.joinedTimestamp = Date.parse(data.join_timestamp); + } + + if ('flags' in data) { + this.flags = new ThreadMemberFlagsBitField(data.flags).freeze(); + } if ('member' in data) { /** diff --git a/packages/discord.js/src/structures/User.js b/packages/discord.js/src/structures/User.js index 46e7b26cf..c2cdff51c 100644 --- a/packages/discord.js/src/structures/User.js +++ b/packages/discord.js/src/structures/User.js @@ -293,7 +293,10 @@ class User extends Base { * @readonly */ get hexAccentColor() { - if (typeof this.accentColor !== 'number') return this.accentColor; + if (typeof this.accentColor !== 'number') { + return this.accentColor; + } + return `#${this.accentColor.toString(16).padStart(6, '0')}`; } diff --git a/packages/discord.js/src/structures/VoiceChannel.js b/packages/discord.js/src/structures/VoiceChannel.js index c5dd819a6..50ce12814 100644 --- a/packages/discord.js/src/structures/VoiceChannel.js +++ b/packages/discord.js/src/structures/VoiceChannel.js @@ -16,7 +16,10 @@ class VoiceChannel extends BaseGuildVoiceChannel { * @readonly */ get joinable() { - if (!super.joinable) return false; + if (!super.joinable) { + return false; + } + return !this.full || this.permissionsFor(this.client.user).has(PermissionFlagsBits.MoveMembers, false); } @@ -28,9 +31,14 @@ class VoiceChannel extends BaseGuildVoiceChannel { */ get speakable() { const permissions = this.permissionsFor(this.client.user); - if (!permissions) return false; + if (!permissions) { + return false; + } + // This flag allows speaking even if timed out - if (permissions.has(PermissionFlagsBits.Administrator, false)) return true; + if (permissions.has(PermissionFlagsBits.Administrator, false)) { + return true; + } return ( this.guild.members.me.communicationDisabledUntilTimestamp < Date.now() && diff --git a/packages/discord.js/src/structures/VoiceState.js b/packages/discord.js/src/structures/VoiceState.js index 9842397f2..4f0da316d 100644 --- a/packages/discord.js/src/structures/VoiceState.js +++ b/packages/discord.js/src/structures/VoiceState.js @@ -243,7 +243,9 @@ class VoiceState extends Base { * @returns {Promise} */ async edit(options) { - if (this.channel?.type !== ChannelType.GuildStageVoice) throw new DiscordjsError(ErrorCodes.VoiceNotStageChannel); + if (this.channel?.type !== ChannelType.GuildStageVoice) { + throw new DiscordjsError(ErrorCodes.VoiceNotStageChannel); + } const target = this.client.user.id === this.id ? '@me' : this.id; diff --git a/packages/discord.js/src/structures/Webhook.js b/packages/discord.js/src/structures/Webhook.js index 2edfb94c1..29b9d5377 100644 --- a/packages/discord.js/src/structures/Webhook.js +++ b/packages/discord.js/src/structures/Webhook.js @@ -23,7 +23,9 @@ class Webhook { * @readonly */ Object.defineProperty(this, 'client', { value: client }); - if (data) this._patch(data); + if (data) { + this._patch(data); + } } _patch(data) { @@ -224,7 +226,9 @@ class Webhook { * .catch(console.error); */ async send(options) { - if (!this.token) throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable); + if (!this.token) { + throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable); + } let messagePayload; @@ -248,7 +252,10 @@ class Webhook { auth: false, }); - if (!this.client.channels) return data; + if (!this.client.channels) { + return data; + } + return ( this.client.channels.cache.get(data.channel_id)?.messages._add(data, false) ?? new (getMessage())(this.client, data) @@ -275,7 +282,9 @@ class Webhook { * @see {@link https://api.slack.com/messaging/webhooks} */ async sendSlackMessage(body) { - if (!this.token) throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable); + if (!this.token) { + throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable); + } const data = await this.client.rest.post(Routes.webhookPlatform(this.id, this.token, 'slack'), { query: makeURLSearchParams({ wait: true }), @@ -338,14 +347,19 @@ class Webhook { * @returns {Promise} Returns the message sent by this webhook */ async fetchMessage(message, { threadId } = {}) { - if (!this.token) throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable); + if (!this.token) { + throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable); + } const data = await this.client.rest.get(Routes.webhookMessage(this.id, this.token, message), { query: threadId ? makeURLSearchParams({ thread_id: threadId }) : undefined, auth: false, }); - if (!this.client.channels) return data; + if (!this.client.channels) { + return data; + } + return ( this.client.channels.cache.get(data.channel_id)?.messages._add(data, false) ?? new (getMessage())(this.client, data) @@ -360,12 +374,17 @@ class Webhook { * @returns {Promise} Returns the message edited by this webhook */ async editMessage(message, options) { - if (!this.token) throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable); + if (!this.token) { + throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable); + } let messagePayload; - if (options instanceof MessagePayload) messagePayload = options; - else messagePayload = MessagePayload.create(this, options); + if (options instanceof MessagePayload) { + messagePayload = options; + } else { + messagePayload = MessagePayload.create(this, options); + } const { body, files } = await messagePayload.resolveBody().resolveFiles(); @@ -385,13 +404,19 @@ class Webhook { ); const channelManager = this.client.channels; - if (!channelManager) return data; + if (!channelManager) { + return data; + } const messageManager = channelManager.cache.get(data.channel_id)?.messages; - if (!messageManager) return new (getMessage())(this.client, data); + if (!messageManager) { + return new (getMessage())(this.client, data); + } const existing = messageManager.cache.get(data.id); - if (!existing) return messageManager._add(data); + if (!existing) { + return messageManager._add(data); + } const clone = existing._clone(); clone._patch(data); @@ -416,7 +441,9 @@ class Webhook { * @returns {Promise} */ async deleteMessage(message, threadId) { - if (!this.token) throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable); + if (!this.token) { + throw new DiscordjsError(ErrorCodes.WebhookTokenUnavailable); + } await this.client.rest.delete( Routes.webhookMessage(this.id, this.token, typeof message === 'string' ? message : message.id), @@ -516,7 +543,10 @@ class Webhook { 'createdAt', 'url', ]) { - if (ignore.includes(prop)) continue; + if (ignore.includes(prop)) { + continue; + } + Object.defineProperty(structure.prototype, prop, Object.getOwnPropertyDescriptor(Webhook.prototype, prop)); } } diff --git a/packages/discord.js/src/structures/interfaces/Collector.js b/packages/discord.js/src/structures/interfaces/Collector.js index a5fde7db4..dd2b64027 100644 --- a/packages/discord.js/src/structures/interfaces/Collector.js +++ b/packages/discord.js/src/structures/interfaces/Collector.js @@ -104,8 +104,13 @@ class Collector extends AsyncEventEmitter { this.handleCollect = this.handleCollect.bind(this); this.handleDispose = this.handleDispose.bind(this); - if (options.time) this._timeout = setTimeout(() => this.stop('time'), options.time).unref(); - if (options.idle) this._idletimeout = setTimeout(() => this.stop('idle'), options.idle).unref(); + if (options.time) { + this._timeout = setTimeout(() => this.stop('time'), options.time).unref(); + } + + if (options.idle) { + this._idletimeout = setTimeout(() => this.stop('idle'), options.idle).unref(); + } /** * The timestamp at which this collector last collected an item @@ -174,10 +179,15 @@ class Collector extends AsyncEventEmitter { * @emits Collector#dispose */ async handleDispose(...args) { - if (!this.options.dispose) return; + if (!this.options.dispose) { + return; + } const dispose = this.dispose(...args); - if (!dispose || !(await this.filter(...args)) || !this.collected.has(dispose)) return; + if (!dispose || !(await this.filter(...args)) || !this.collected.has(dispose)) { + return; + } + this.collected.delete(dispose); /** @@ -233,7 +243,9 @@ class Collector extends AsyncEventEmitter { * @emits Collector#end */ stop(reason = 'user') { - if (this.ended) return; + if (this.ended) { + return; + } if (this._timeout) { clearTimeout(this._timeout); @@ -290,7 +302,10 @@ class Collector extends AsyncEventEmitter { */ checkEnd() { const reason = this.endReason; - if (reason) this.stop(reason); + if (reason) { + this.stop(reason); + } + return Boolean(reason); } diff --git a/packages/discord.js/src/structures/interfaces/InteractionResponses.js b/packages/discord.js/src/structures/interfaces/InteractionResponses.js index 04b987156..97170d4b9 100644 --- a/packages/discord.js/src/structures/interfaces/InteractionResponses.js +++ b/packages/discord.js/src/structures/interfaces/InteractionResponses.js @@ -80,7 +80,9 @@ class InteractionResponses { * .catch(console.error); */ async deferReply(options = {}) { - if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied); + if (this.deferred || this.replied) { + throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied); + } const resolvedFlags = new MessageFlagsBitField(options.flags); @@ -121,11 +123,16 @@ class InteractionResponses { * .catch(console.error); */ async reply(options) { - if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied); + if (this.deferred || this.replied) { + throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied); + } let messagePayload; - if (options instanceof MessagePayload) messagePayload = options; - else messagePayload = MessagePayload.create(this, options); + if (options instanceof MessagePayload) { + messagePayload = options; + } else { + messagePayload = MessagePayload.create(this, options); + } const { body: data, files } = await messagePayload.resolveBody().resolveFiles(); @@ -181,7 +188,10 @@ class InteractionResponses { * .catch(console.error); */ async editReply(options) { - if (!this.deferred && !this.replied) throw new DiscordjsError(ErrorCodes.InteractionNotReplied); + if (!this.deferred && !this.replied) { + throw new DiscordjsError(ErrorCodes.InteractionNotReplied); + } + const msg = await this.webhook.editMessage(options.message ?? '@original', options); this.replied = true; return msg; @@ -200,7 +210,9 @@ class InteractionResponses { * .catch(console.error); */ async deleteReply(message = '@original') { - if (!this.deferred && !this.replied) throw new DiscordjsError(ErrorCodes.InteractionNotReplied); + if (!this.deferred && !this.replied) { + throw new DiscordjsError(ErrorCodes.InteractionNotReplied); + } await this.webhook.deleteMessage(message); } @@ -212,7 +224,10 @@ class InteractionResponses { * @returns {Promise} */ async followUp(options) { - if (!this.deferred && !this.replied) throw new DiscordjsError(ErrorCodes.InteractionNotReplied); + if (!this.deferred && !this.replied) { + throw new DiscordjsError(ErrorCodes.InteractionNotReplied); + } + const msg = await this.webhook.send(options); this.replied = true; return msg; @@ -230,7 +245,10 @@ class InteractionResponses { * .catch(console.error); */ async deferUpdate(options = {}) { - if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied); + if (this.deferred || this.replied) { + throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied); + } + const response = await this.client.rest.post(Routes.interactionCallback(this.id, this.token), { body: { type: InteractionResponseType.DeferredMessageUpdate, @@ -258,11 +276,16 @@ class InteractionResponses { * .catch(console.error); */ async update(options = {}) { - if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied); + if (this.deferred || this.replied) { + throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied); + } let messagePayload; - if (options instanceof MessagePayload) messagePayload = options; - else messagePayload = MessagePayload.create(this, options); + if (options instanceof MessagePayload) { + messagePayload = options; + } else { + messagePayload = MessagePayload.create(this, options); + } const { body: data, files } = await messagePayload.resolveBody().resolveFiles(); @@ -287,7 +310,10 @@ class InteractionResponses { * @returns {Promise} */ async launchActivity({ withResponse } = {}) { - if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied); + if (this.deferred || this.replied) { + throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied); + } + const response = await this.client.rest.post(Routes.interactionCallback(this.id, this.token), { query: makeURLSearchParams({ with_response: withResponse ?? false }), body: { @@ -308,7 +334,10 @@ class InteractionResponses { * @returns {Promise} */ async showModal(modal, options = {}) { - if (this.deferred || this.replied) throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied); + if (this.deferred || this.replied) { + throw new DiscordjsError(ErrorCodes.InteractionAlreadyReplied); + } + const response = await this.client.rest.post(Routes.interactionCallback(this.id, this.token), { body: { type: InteractionResponseType.Modal, @@ -344,14 +373,20 @@ class InteractionResponses { * .catch(console.error); */ async awaitModalSubmit(options) { - if (typeof options.time !== 'number') throw new DiscordjsError(ErrorCodes.InvalidType, 'time', 'number'); + if (typeof options.time !== 'number') { + throw new DiscordjsError(ErrorCodes.InvalidType, 'time', 'number'); + } + const _options = { ...options, max: 1, interactionType: InteractionType.ModalSubmit }; return new Promise((resolve, reject) => { const collector = new InteractionCollector(this.client, _options); collector.once('end', (interactions, reason) => { const interaction = interactions.first(); - if (interaction) resolve(interaction); - else reject(new DiscordjsError(ErrorCodes.InteractionCollectorError, reason)); + if (interaction) { + resolve(interaction); + } else { + reject(new DiscordjsError(ErrorCodes.InteractionCollectorError, reason)); + } }); }); } @@ -372,7 +407,10 @@ class InteractionResponses { ]; for (const prop of props) { - if (ignore.includes(prop)) continue; + if (ignore.includes(prop)) { + continue; + } + Object.defineProperty( structure.prototype, prop, diff --git a/packages/discord.js/src/structures/interfaces/TextBasedChannel.js b/packages/discord.js/src/structures/interfaces/TextBasedChannel.js index 473c96467..52e7c1f8f 100644 --- a/packages/discord.js/src/structures/interfaces/TextBasedChannel.js +++ b/packages/discord.js/src/structures/interfaces/TextBasedChannel.js @@ -285,8 +285,11 @@ class TextBasedChannel { const collector = this.createMessageComponentCollector(_options); collector.once('end', (interactions, reason) => { const interaction = interactions.first(); - if (interaction) resolve(interaction); - else reject(new DiscordjsError(ErrorCodes.InteractionCollectorError, reason)); + if (interaction) { + resolve(interaction); + } else { + reject(new DiscordjsError(ErrorCodes.InteractionCollectorError, reason)); + } }); }); } @@ -315,7 +318,9 @@ class TextBasedChannel { ); } - if (messageIds.length === 0) return []; + if (messageIds.length === 0) { + return []; + } if (messageIds.length === 1) { await this.client.rest.delete(Routes.channelMessage(this.id, messageIds[0])); @@ -416,7 +421,10 @@ class TextBasedChannel { ]; for (const prop of props) { - if (ignore.includes(prop)) continue; + if (ignore.includes(prop)) { + continue; + } + Object.defineProperty( structure.prototype, prop, diff --git a/packages/discord.js/src/util/BitField.js b/packages/discord.js/src/util/BitField.js index 98d477d06..25f6e9aa3 100644 --- a/packages/discord.js/src/util/BitField.js +++ b/packages/discord.js/src/util/BitField.js @@ -99,7 +99,10 @@ class BitField { total |= this.constructor.resolve(bit); } - if (Object.isFrozen(this)) return new this.constructor(this.bitfield | total); + if (Object.isFrozen(this)) { + return new this.constructor(this.bitfield | total); + } + this.bitfield |= total; return this; } @@ -116,7 +119,10 @@ class BitField { total |= this.constructor.resolve(bit); } - if (Object.isFrozen(this)) return new this.constructor(this.bitfield & ~total); + if (Object.isFrozen(this)) { + return new this.constructor(this.bitfield & ~total); + } + this.bitfield &= ~total; return this; } @@ -131,7 +137,9 @@ class BitField { serialize(...hasParams) { const serialized = {}; for (const [flag, bit] of Object.entries(this.constructor.Flags)) { - if (isNaN(flag)) serialized[flag] = this.has(bit, ...hasParams); + if (isNaN(flag)) { + serialized[flag] = this.has(bit, ...hasParams); + } } return serialized; @@ -157,7 +165,9 @@ class BitField { *[Symbol.iterator](...hasParams) { for (const bitName of Object.keys(this.constructor.Flags)) { - if (isNaN(bitName) && this.has(bitName, ...hasParams)) yield bitName; + if (isNaN(bitName) && this.has(bitName, ...hasParams)) { + yield bitName; + } } } @@ -179,15 +189,26 @@ class BitField { */ static resolve(bit) { const { DefaultBit } = this; - if (typeof DefaultBit === typeof bit && bit >= DefaultBit) return bit; - if (bit instanceof BitField) return bit.bitfield; + if (typeof DefaultBit === typeof bit && bit >= DefaultBit) { + return bit; + } + + if (bit instanceof BitField) { + return bit.bitfield; + } + if (Array.isArray(bit)) { return bit.map(bit_ => this.resolve(bit_)).reduce((prev, bit_) => prev | bit_, DefaultBit); } if (typeof bit === 'string') { - if (!isNaN(bit)) return typeof DefaultBit === 'bigint' ? BigInt(bit) : Number(bit); - if (this.Flags[bit] !== undefined) return this.Flags[bit]; + if (!isNaN(bit)) { + return typeof DefaultBit === 'bigint' ? BigInt(bit) : Number(bit); + } + + if (this.Flags[bit] !== undefined) { + return this.Flags[bit]; + } } throw new DiscordjsRangeError(ErrorCodes.BitFieldInvalid, bit); diff --git a/packages/discord.js/src/util/Channels.js b/packages/discord.js/src/util/Channels.js index ebd99bf57..e17e478b3 100644 --- a/packages/discord.js/src/util/Channels.js +++ b/packages/discord.js/src/util/Channels.js @@ -74,7 +74,10 @@ function createChannel(client, data, guild, { allowUnknownGuild } = {}) { case ChannelType.PublicThread: case ChannelType.PrivateThread: { channel = new (getThreadChannel())(resolvedGuild, data, client); - if (!allowUnknownGuild) channel.parent?.threads.cache.set(channel.id, channel); + if (!allowUnknownGuild) { + channel.parent?.threads.cache.set(channel.id, channel); + } + break; } @@ -91,7 +94,9 @@ function createChannel(client, data, guild, { allowUnknownGuild } = {}) { break; } - if (channel && !allowUnknownGuild) resolvedGuild.channels?.cache.set(channel.id, channel); + if (channel && !allowUnknownGuild) { + resolvedGuild.channels?.cache.set(channel.id, channel); + } } return channel; diff --git a/packages/discord.js/src/util/DataResolver.js b/packages/discord.js/src/util/DataResolver.js index 5e2c0adfd..7321b71ff 100644 --- a/packages/discord.js/src/util/DataResolver.js +++ b/packages/discord.js/src/util/DataResolver.js @@ -88,11 +88,16 @@ function resolveGuildTemplateCode(data) { * @private */ async function resolveFile(resource) { - if (Buffer.isBuffer(resource)) return { data: resource }; + if (Buffer.isBuffer(resource)) { + return { data: resource }; + } if (typeof resource[Symbol.asyncIterator] === 'function') { const buffers = []; - for await (const data of resource) buffers.push(Buffer.from(data)); + for await (const data of resource) { + buffers.push(Buffer.from(data)); + } + return { data: Buffer.concat(buffers) }; } @@ -105,7 +110,10 @@ async function resolveFile(resource) { const file = path.resolve(resource); const stats = await fs.stat(file); - if (!stats.isFile()) throw new DiscordjsError(ErrorCodes.FileNotFound, file); + if (!stats.isFile()) { + throw new DiscordjsError(ErrorCodes.FileNotFound, file); + } + return { data: await fs.readFile(file) }; } @@ -129,7 +137,10 @@ async function resolveFile(resource) { * @private */ function resolveBase64(data, contentType = 'image/jpg') { - if (Buffer.isBuffer(data)) return `data:${contentType};base64,${data.toString('base64')}`; + if (Buffer.isBuffer(data)) { + return `data:${contentType};base64,${data.toString('base64')}`; + } + return data; } @@ -141,7 +152,10 @@ function resolveBase64(data, contentType = 'image/jpg') { * @private */ async function resolveImage(image) { - if (!image) return null; + if (!image) { + return null; + } + if (typeof image === 'string' && image.startsWith('data:')) { return image; } diff --git a/packages/discord.js/src/util/Enums.js b/packages/discord.js/src/util/Enums.js index 1536c7e18..185da92a1 100644 --- a/packages/discord.js/src/util/Enums.js +++ b/packages/discord.js/src/util/Enums.js @@ -3,7 +3,10 @@ function createEnum(keys) { const obj = {}; for (const [index, key] of keys.entries()) { - if (key === null) continue; + if (key === null) { + continue; + } + obj[key] = index; obj[index] = key; } diff --git a/packages/discord.js/src/util/LimitedCollection.js b/packages/discord.js/src/util/LimitedCollection.js index ea96a8586..2a30d851b 100644 --- a/packages/discord.js/src/util/LimitedCollection.js +++ b/packages/discord.js/src/util/LimitedCollection.js @@ -53,7 +53,10 @@ class LimitedCollection extends Collection { } set(key, value) { - if (this.maxSize === 0 && !this.keepOverLimit?.(value, key, this)) return this; + if (this.maxSize === 0 && !this.keepOverLimit?.(value, key, this)) { + return this; + } + if (this.size >= this.maxSize && !this.has(key)) { for (const [iteratedKey, iteratedValue] of this.entries()) { const keep = this.keepOverLimit?.(iteratedValue, iteratedKey, this) ?? false; diff --git a/packages/discord.js/src/util/Sweepers.js b/packages/discord.js/src/util/Sweepers.js index 2451fe809..81b6c739d 100644 --- a/packages/discord.js/src/util/Sweepers.js +++ b/packages/discord.js/src/util/Sweepers.js @@ -40,7 +40,9 @@ class Sweepers { this.intervals = Object.fromEntries(SweeperKeys.map(key => [key, null])); for (const key of SweeperKeys) { - if (!(key in options)) continue; + if (!(key in options)) { + continue; + } this._validateProperties(key); @@ -179,7 +181,9 @@ class Sweepers { let messages = 0; for (const channel of this.client.channels.cache.values()) { - if (!channel.isTextBased()) continue; + if (!channel.isTextBased()) { + continue; + } channels++; messages += channel.messages.cache.sweep(filter); @@ -215,7 +219,10 @@ class Sweepers { let reactions = 0; for (const channel of this.client.channels.cache.values()) { - if (!channel.isTextBased()) continue; + if (!channel.isTextBased()) { + continue; + } + channels++; for (const message of channel.messages.cache.values()) { @@ -266,7 +273,10 @@ class Sweepers { let threads = 0; let members = 0; for (const channel of this.client.channels.cache.values()) { - if (!ThreadChannelTypes.includes(channel.type)) continue; + if (!ThreadChannelTypes.includes(channel.type)) { + continue; + } + threads++; members += channel.members.cache.sweep(filter); } @@ -297,7 +307,10 @@ class Sweepers { let threads = 0; for (const [key, val] of this.client.channels.cache.entries()) { - if (!ThreadChannelTypes.includes(val.type)) continue; + if (!ThreadChannelTypes.includes(val.type)) { + continue; + } + if (filter(val, key, this.client.channels.cache)) { threads++; this.client.channels._remove(key); @@ -343,7 +356,9 @@ class Sweepers { */ destroy() { for (const key of SweeperKeys) { - if (this.intervals[key]) clearInterval(this.intervals[key]); + if (this.intervals[key]) { + clearInterval(this.intervals[key]); + } } } @@ -383,7 +398,10 @@ class Sweepers { } return () => { - if (lifetime <= 0) return null; + if (lifetime <= 0) { + return null; + } + const lifetimeMs = lifetime * 1_000; const now = Date.now(); return (entry, key, coll) => { @@ -392,7 +410,10 @@ class Sweepers { } const comparisonTimestamp = getComparisonTimestamp(entry, key, coll); - if (!comparisonTimestamp || typeof comparisonTimestamp !== 'number') return false; + if (!comparisonTimestamp || typeof comparisonTimestamp !== 'number') { + return false; + } + return now - comparisonTimestamp > lifetimeMs; }; }; @@ -466,7 +487,9 @@ class Sweepers { for (const guild of this.client.guilds.cache.values()) { // We may be unable to sweep the cache if the guild is unavailable and was never patched - if (!guild.available) continue; + if (!guild.available) { + continue; + } const { cache } = guild[key]; @@ -520,11 +543,20 @@ class Sweepers { * @private */ _initInterval(intervalKey, sweepKey, opts) { - if (opts.interval <= 0 || opts.interval === Infinity) return; + if (opts.interval <= 0 || opts.interval === Infinity) { + return; + } + this.intervals[intervalKey] = setInterval(() => { const sweepFn = opts.filter(); - if (sweepFn === null) return; - if (typeof sweepFn !== 'function') throw new DiscordjsTypeError(ErrorCodes.SweepFilterReturn); + if (sweepFn === null) { + return; + } + + if (typeof sweepFn !== 'function') { + throw new DiscordjsTypeError(ErrorCodes.SweepFilterReturn); + } + this[sweepKey](sweepFn); }, opts.interval * 1_000).unref(); } diff --git a/packages/discord.js/src/util/Transformers.js b/packages/discord.js/src/util/Transformers.js index 2b73fa3bb..dfda9297f 100644 --- a/packages/discord.js/src/util/Transformers.js +++ b/packages/discord.js/src/util/Transformers.js @@ -10,10 +10,22 @@ const snakeCase = require('lodash.snakecase'); * @returns {*} */ function toSnakeCase(obj) { - if (typeof obj !== 'object' || !obj) return obj; - if (obj instanceof Date) return obj; - if (isJSONEncodable(obj)) return toSnakeCase(obj.toJSON()); - if (Array.isArray(obj)) return obj.map(toSnakeCase); + if (typeof obj !== 'object' || !obj) { + return obj; + } + + if (obj instanceof Date) { + return obj; + } + + if (isJSONEncodable(obj)) { + return toSnakeCase(obj.toJSON()); + } + + if (Array.isArray(obj)) { + return obj.map(toSnakeCase); + } + return Object.fromEntries(Object.entries(obj).map(([key, value]) => [snakeCase(key), toSnakeCase(value)])); } @@ -100,7 +112,9 @@ function _transformAPIIncidentsData(data) { * @ignore */ function _transformCollectibles(collectibles) { - if (!collectibles.nameplate) return { nameplate: null }; + if (!collectibles.nameplate) { + return { nameplate: null }; + } return { nameplate: { diff --git a/packages/discord.js/src/util/Util.js b/packages/discord.js/src/util/Util.js index ba28771b7..72b52ae8e 100644 --- a/packages/discord.js/src/util/Util.js +++ b/packages/discord.js/src/util/Util.js @@ -19,7 +19,9 @@ const isObject = data => typeof data === 'object' && data !== null; * @returns {Object} */ function flatten(obj, ...props) { - if (!isObject(obj)) return obj; + if (!isObject(obj)) { + return obj; + } const objProps = Object.keys(obj) .filter(key => !key.startsWith('_')) @@ -31,7 +33,10 @@ function flatten(obj, ...props) { // eslint-disable-next-line prefer-const for (let [prop, newProp] of Object.entries(mergedProps)) { - if (!newProp) continue; + if (!newProp) { + continue; + } + newProp = newProp === true ? prop : newProp; const element = obj[prop]; @@ -40,19 +45,33 @@ function flatten(obj, ...props) { const hasToJSON = elemIsObj && typeof element.toJSON === 'function'; // If it's a Collection, make the array of keys - if (element instanceof Collection) out[newProp] = Array.from(element.keys()); + if (element instanceof Collection) { + out[newProp] = Array.from(element.keys()); + } // If the valueOf is a Collection, use its array of keys - else if (valueOf instanceof Collection) out[newProp] = Array.from(valueOf.keys()); + else if (valueOf instanceof Collection) { + out[newProp] = Array.from(valueOf.keys()); + } // If it's an array, call toJSON function on each element if present, otherwise flatten each element - else if (Array.isArray(element)) out[newProp] = element.map(elm => elm.toJSON?.() ?? flatten(elm)); + else if (Array.isArray(element)) { + out[newProp] = element.map(elm => elm.toJSON?.() ?? flatten(elm)); + } // If it's an object with a primitive `valueOf`, use that value - else if (typeof valueOf !== 'object') out[newProp] = valueOf; + else if (typeof valueOf !== 'object') { + out[newProp] = valueOf; + } // If it's an object with a toJSON function, use the return value of it - else if (hasToJSON) out[newProp] = element.toJSON(); + else if (hasToJSON) { + out[newProp] = element.toJSON(); + } // If element is an object, use the flattened version of it - else if (typeof element === 'object') out[newProp] = flatten(element); + else if (typeof element === 'object') { + out[newProp] = flatten(element); + } // If it's a primitive - else if (!elemIsObj) out[newProp] = element; + else if (!elemIsObj) { + out[newProp] = element; + } } return out; @@ -72,13 +91,19 @@ function flatten(obj, ...props) { * @returns {Promise} The recommended number of shards */ async function fetchRecommendedShardCount(token, { guildsPerShard = 1_000, multipleOf = 1 } = {}) { - if (!token) throw new DiscordjsError(ErrorCodes.TokenMissing); + if (!token) { + throw new DiscordjsError(ErrorCodes.TokenMissing); + } + const response = await fetch(RouteBases.api + Routes.gatewayBot(), { method: 'GET', headers: { Authorization: `Bot ${token.replace(/^bot\s*/i, '')}` }, }); if (!response.ok) { - if (response.status === 401) throw new DiscordjsError(ErrorCodes.TokenInvalid); + if (response.status === 401) { + throw new DiscordjsError(ErrorCodes.TokenInvalid); + } + throw response; } @@ -106,7 +131,10 @@ async function fetchRecommendedShardCount(token, { guildsPerShard = 1_000, multi */ function parseEmoji(text) { const decodedText = text.includes('%') ? decodeURIComponent(text) : text; - if (!decodedText.includes(':')) return { animated: false, name: decodedText, id: undefined }; + if (!decodedText.includes(':')) { + return { animated: false, name: decodedText, id: undefined }; + } + const match = /a):)?(?\w{2,32}):(?\d{17,19})?>?/.exec(decodedText); return match && { animated: Boolean(match.groups.animated), name: match.groups.name, id: match.groups.id }; } @@ -125,10 +153,19 @@ function parseEmoji(text) { * @returns {?(PartialEmoji|PartialEmojiOnlyId)} Supplying a snowflake yields `PartialEmojiOnlyId`. */ function resolvePartialEmoji(emoji) { - if (!emoji) return null; - if (typeof emoji === 'string') return /^\d{17,19}$/.test(emoji) ? { id: emoji } : parseEmoji(emoji); + if (!emoji) { + return null; + } + + if (typeof emoji === 'string') { + return /^\d{17,19}$/.test(emoji) ? { id: emoji } : parseEmoji(emoji); + } + const { id, name, animated } = emoji; - if (!id && !name) return null; + if (!id && !name) { + return null; + } + return { id, name, animated: Boolean(animated) }; } @@ -268,8 +305,14 @@ function verifyString( errorMessage = `Expected a string, got ${data} instead.`, allowEmpty = true, ) { - if (typeof data !== 'string') throw new error(errorMessage); - if (!allowEmpty && data.length === 0) throw new error(errorMessage); + if (typeof data !== 'string') { + throw new error(errorMessage); + } + + if (!allowEmpty && data.length === 0) { + throw new error(errorMessage); + } + return data; } @@ -324,9 +367,18 @@ function resolveColor(color) { let resolvedColor; if (typeof color === 'string') { - if (color === 'Random') return Math.floor(Math.random() * (0xffffff + 1)); - if (color === 'Default') return 0; - if (/^#?[\da-f]{6}$/i.test(color)) return Number.parseInt(color.replace('#', ''), 16); + if (color === 'Random') { + return Math.floor(Math.random() * (0xffffff + 1)); + } + + if (color === 'Default') { + return 0; + } + + if (/^#?[\da-f]{6}$/i.test(color)) { + return Number.parseInt(color.replace('#', ''), 16); + } + resolvedColor = Colors[color]; } else if (Array.isArray(color)) { resolvedColor = (color[0] << 16) + (color[1] << 8) + color[2]; @@ -424,9 +476,13 @@ function cleanContent(str, channel) { return str.replaceAll( /<(?:(?@[!&]?|#)|(?:\/(?[-_\p{L}\p{N}\p{sc=Deva}\p{sc=Thai} ]+):)|(?:a?:(?[\w]+):))(?\d{17,19})>/gu, (match, type, commandName, emojiName, id) => { - if (commandName) return `/${commandName}`; + if (commandName) { + return `/${commandName}`; + } - if (emojiName) return `:${emojiName}:`; + if (emojiName) { + return `:${emojiName}:`; + } switch (type) { case '@': @@ -441,7 +497,10 @@ function cleanContent(str, channel) { } case '@&': { - if (channel.type === ChannelType.DM) return match; + if (channel.type === ChannelType.DM) { + return match; + } + const role = channel.guild.roles.cache.get(id); return role ? `@${role.name}` : match; } @@ -563,9 +622,15 @@ function transformResolved( * @returns {?Snowflake} The resolved SKU id, or `null` if the resolvable was invalid */ function resolveSKUId(resolvable) { - if (typeof resolvable === 'string') return resolvable; + if (typeof resolvable === 'string') { + return resolvable; + } + // eslint-disable-next-line no-use-before-define - if (resolvable instanceof SKU) return resolvable.id; + if (resolvable instanceof SKU) { + return resolvable.id; + } + return null; } diff --git a/packages/discord.js/typings/index.test-d.ts b/packages/discord.js/typings/index.test-d.ts index d9621e31b..5efe2e8d5 100644 --- a/packages/discord.js/typings/index.test-d.ts +++ b/packages/discord.js/typings/index.test-d.ts @@ -364,7 +364,9 @@ client.on('interactionCreate', async interaction => { expectType(interaction.channelId); } - if (interaction.type !== InteractionType.ApplicationCommand) return; + if (interaction.type !== InteractionType.ApplicationCommand) { + return; + } const actionRow = new ActionRowBuilder({ type: ComponentType.ActionRow, @@ -810,7 +812,10 @@ client.on('messageReactionRemove', ({ client: oldClient }, { client: newClient } client.on('messageReactionRemoveAll', async (message, reactions) => { console.log(`messageReactionRemoveAll - id: ${message.id} (${message.id.length})`); - if (message.partial) message = await message.fetch(); + if (message.partial) { + message = await message.fetch(); + } + console.log(`messageReactionRemoveAll - content: ${message.content}`); expectType>(message.client); expectType>(reactions.first()!.client); @@ -1357,7 +1362,9 @@ client.on('threadMembersUpdate', (addedMembers, removedMembers, thread) => { expectType>(removedMembers); expectType(thread); const left = removedMembers.first(); - if (!left) return; + if (!left) { + return; + } if (left.partial) { expectType(left); @@ -1395,7 +1402,9 @@ client.on('webhooksUpdate', ({ client }) => expectType>(client)); client.on('guildCreate', async g => { expectType>(g.client); const channel = g.channels.cache.random(); - if (!channel) return; + if (!channel) { + return; + } if (channel.type === ChannelType.GuildText) { const row: ActionRowData = { @@ -1920,11 +1929,18 @@ declare const threadMemberManager: ThreadMemberManager; declare const typing: Typing; expectType(typing.user); -if (typing.user.partial) expectType(typing.user.username); -if (!typing.user.partial) expectType(typing.user.tag); +if (typing.user.partial) { + expectType(typing.user.username); +} + +if (!typing.user.partial) { + expectType(typing.user.tag); +} expectType(typing.channel); -if (typing.channel.partial) expectType(typing.channel.lastMessageId); +if (typing.channel.partial) { + expectType(typing.channel.lastMessageId); +} expectType(typing.member); expectType(typing.guild); diff --git a/packages/docgen/src/types/item.ts b/packages/docgen/src/types/item.ts index b58fe83c5..b877921cc 100644 --- a/packages/docgen/src/types/item.ts +++ b/packages/docgen/src/types/item.ts @@ -23,9 +23,18 @@ export class DocumentedItem { private detailedName() { const data = this.data as unknown as Item | undefined; - if (!data) return this.constructor.name; - if (data.id) return `${data.id} (${this.constructor.name})`; - if (data.name) return `${data.name} (${this.constructor.name})`; + if (!data) { + return this.constructor.name; + } + + if (data.id) { + return `${data.id} (${this.constructor.name})`; + } + + if (data.name) { + return `${data.name} (${this.constructor.name})`; + } + return this.constructor.name; } } diff --git a/packages/formatters/__tests__/escapers.test.ts b/packages/formatters/__tests__/escapers.test.ts index 280dc4d1a..3840bdeb6 100644 --- a/packages/formatters/__tests__/escapers.test.ts +++ b/packages/formatters/__tests__/escapers.test.ts @@ -85,7 +85,9 @@ describe('Markdown escapers', () => { }); test('url', () => { - for (const url of testURLs) expect(escapeItalic(url)).toBe(url); + for (const url of testURLs) { + expect(escapeItalic(url)).toBe(url); + } }); }); @@ -108,7 +110,9 @@ describe('Markdown escapers', () => { }); test('url', () => { - for (const url of testURLs) expect(escapeUnderline(url)).toBe(url); + for (const url of testURLs) { + expect(escapeUnderline(url)).toBe(url); + } }); }); diff --git a/packages/formatters/src/escapers.ts b/packages/formatters/src/escapers.ts index bceaf484f..fa83a9d99 100644 --- a/packages/formatters/src/escapers.ts +++ b/packages/formatters/src/escapers.ts @@ -130,7 +130,10 @@ export function escapeMarkdown(text: string, options: EscapeMarkdownOptions = {} return text .split('```') .map((subString, index, array) => { - if (index % 2 && index !== array.length - 1) return subString; + if (index % 2 && index !== array.length - 1) { + return subString; + } + return escapeMarkdown(subString, { inlineCode, bold, @@ -153,7 +156,10 @@ export function escapeMarkdown(text: string, options: EscapeMarkdownOptions = {} return text .split(/(?<=^|[^`])`(?=[^`]|$)/g) .map((subString, index, array) => { - if (index % 2 && index !== array.length - 1) return subString; + if (index % 2 && index !== array.length - 1) { + return subString; + } + return escapeMarkdown(subString, { codeBlock, bold, @@ -172,18 +178,54 @@ export function escapeMarkdown(text: string, options: EscapeMarkdownOptions = {} } let res = text; - if (escape) res = escapeEscape(res); - if (inlineCode) res = escapeInlineCode(res); - if (codeBlock) res = escapeCodeBlock(res); - if (italic) res = escapeItalic(res); - if (bold) res = escapeBold(res); - if (underline) res = escapeUnderline(res); - if (strikethrough) res = escapeStrikethrough(res); - if (spoiler) res = escapeSpoiler(res); - if (heading) res = escapeHeading(res); - if (bulletedList) res = escapeBulletedList(res); - if (numberedList) res = escapeNumberedList(res); - if (maskedLink) res = escapeMaskedLink(res); + if (escape) { + res = escapeEscape(res); + } + + if (inlineCode) { + res = escapeInlineCode(res); + } + + if (codeBlock) { + res = escapeCodeBlock(res); + } + + if (italic) { + res = escapeItalic(res); + } + + if (bold) { + res = escapeBold(res); + } + + if (underline) { + res = escapeUnderline(res); + } + + if (strikethrough) { + res = escapeStrikethrough(res); + } + + if (spoiler) { + res = escapeSpoiler(res); + } + + if (heading) { + res = escapeHeading(res); + } + + if (bulletedList) { + res = escapeBulletedList(res); + } + + if (numberedList) { + res = escapeNumberedList(res); + } + + if (maskedLink) { + res = escapeMaskedLink(res); + } + return res; } @@ -213,12 +255,18 @@ export function escapeInlineCode(text: string): string { export function escapeItalic(text: string): string { let idx = 0; const newText = text.replaceAll(/(?<=^|[^*])\*([^*]|\*\*|$)/g, (_, match) => { - if (match === '**') return ++idx % 2 ? `\\*${match}` : `${match}\\*`; + if (match === '**') { + return ++idx % 2 ? `\\*${match}` : `${match}\\*`; + } + return `\\*${match}`; }); idx = 0; return newText.replaceAll(/(?<=^|[^_])(?)([^_]|__|$)/g, (_, match) => { - if (match === '__') return ++idx % 2 ? `\\_${match}` : `${match}\\_`; + if (match === '__') { + return ++idx % 2 ? `\\_${match}` : `${match}\\_`; + } + return `\\_${match}`; }); } @@ -231,7 +279,10 @@ export function escapeItalic(text: string): string { export function escapeBold(text: string): string { let idx = 0; return text.replaceAll(/\*\*(\*)?/g, (_, match) => { - if (match) return ++idx % 2 ? `${match}\\*\\*` : `\\*\\*${match}`; + if (match) { + return ++idx % 2 ? `${match}\\*\\*` : `\\*\\*${match}`; + } + return '\\*\\*'; }); } @@ -244,7 +295,10 @@ export function escapeBold(text: string): string { export function escapeUnderline(text: string): string { let idx = 0; return text.replaceAll(/(?)/g, (_, match) => { - if (match) return ++idx % 2 ? `${match}\\_\\_` : `\\_\\_${match}`; + if (match) { + return ++idx % 2 ? `${match}\\_\\_` : `\\_\\_${match}`; + } + return '\\_\\_'; }); } diff --git a/packages/rest/__tests__/utils.test.ts b/packages/rest/__tests__/utils.test.ts index 344be6775..db25cb553 100644 --- a/packages/rest/__tests__/utils.test.ts +++ b/packages/rest/__tests__/utils.test.ts @@ -93,8 +93,14 @@ describe('makeURLSearchParams', () => { describe('option normalization functions', () => { describe('rate limit offset', () => { const func: GetRateLimitOffsetFunction = (route) => { - if (route === '/negative') return -150; - if (route === '/high') return 150; + if (route === '/negative') { + return -150; + } + + if (route === '/high') { + return 150; + } + return 50; }; @@ -116,11 +122,26 @@ describe('option normalization functions', () => { content: 'yo', }; const func: GetRetryBackoffFunction = (_route, statusCode, retryCount) => { - if (statusCode === null) return 0; - if (statusCode === 502) return 50; - if (retryCount === 0) return 0; - if (retryCount === 1) return 150; - if (retryCount === 2) return 500; + if (statusCode === null) { + return 0; + } + + if (statusCode === 502) { + return 50; + } + + if (retryCount === 0) { + return 0; + } + + if (retryCount === 1) { + return 150; + } + + if (retryCount === 2) { + return 500; + } + return null; }; @@ -161,8 +182,14 @@ describe('option normalization functions', () => { return 1_000; } - if (route === '/negative') return -150; - if (route === '/high') return 150; + if (route === '/negative') { + return -150; + } + + if (route === '/high') { + return 150; + } + return 50; }; diff --git a/packages/rest/src/lib/REST.ts b/packages/rest/src/lib/REST.ts index a39565577..327bffd8d 100644 --- a/packages/rest/src/lib/REST.ts +++ b/packages/rest/src/lib/REST.ts @@ -104,7 +104,9 @@ export class REST extends AsyncEventEmitter { // Begin sweeping hash based on lifetimes this.hashes.sweep((val, key) => { // `-1` indicates a global hash - if (val.lastAccess === -1) return false; + if (val.lastAccess === -1) { + return false; + } // Check if lifetime has been exceeded const shouldSweep = Math.floor(currentDate - val.lastAccess) > this.options.hashLifetime; diff --git a/packages/rest/src/lib/handlers/BurstHandler.ts b/packages/rest/src/lib/handlers/BurstHandler.ts index 70ad1f732..46e4a6862 100644 --- a/packages/rest/src/lib/handlers/BurstHandler.ts +++ b/packages/rest/src/lib/handlers/BurstHandler.ts @@ -91,7 +91,9 @@ export class BurstHandler implements IHandler { // Amount of time in milliseconds until we should retry if rate limited (globally or otherwise) const offset = normalizeRateLimitOffset(this.manager.options.offset, routeId.bucketRoute); - if (retry) retryAfter = Number(retry) * 1_000 + offset; + if (retry) { + retryAfter = Number(retry) * 1_000 + offset; + } // Count the invalid requests if (status === 401 || status === 403 || status === 429) { diff --git a/packages/rest/src/lib/handlers/SequentialHandler.ts b/packages/rest/src/lib/handlers/SequentialHandler.ts index c6eeeda81..db0968f19 100644 --- a/packages/rest/src/lib/handlers/SequentialHandler.ts +++ b/packages/rest/src/lib/handlers/SequentialHandler.ts @@ -298,7 +298,9 @@ export class SequentialHandler implements IHandler { this.reset = reset ? Number(reset) * 1_000 + Date.now() + offset : Date.now(); // Amount of time in milliseconds until we should retry if rate limited (globally or otherwise) - if (retry) retryAfter = Number(retry) * 1_000 + offset; + if (retry) { + retryAfter = Number(retry) * 1_000 + offset; + } // Handle buckets via the hash header retroactively if (hash && hash !== this.hash) { diff --git a/packages/rest/src/lib/handlers/Shared.ts b/packages/rest/src/lib/handlers/Shared.ts index 2b186f23d..b0b1f111d 100644 --- a/packages/rest/src/lib/handlers/Shared.ts +++ b/packages/rest/src/lib/handlers/Shared.ts @@ -73,15 +73,21 @@ export async function makeNetworkRequest( // If the user signal was aborted, abort the controller, else abort the local signal. // The reason why we don't re-use the user's signal, is because users may use the same signal for multiple // requests, and we do not want to cause unexpected side-effects. - if (requestData.signal.aborted) controller.abort(); - else requestData.signal.addEventListener('abort', () => controller.abort()); + if (requestData.signal.aborted) { + controller.abort(); + } else { + requestData.signal.addEventListener('abort', () => controller.abort()); + } } let res: ResponseLike; try { res = await manager.options.makeRequest(url, { ...options, signal: controller.signal }); } catch (error: unknown) { - if (!(error instanceof Error)) throw error; + if (!(error instanceof Error)) { + throw error; + } + // Retry the specified number of times if needed if (shouldRetry(error) && retries !== manager.options.retries) { const backoff = normalizeRetryBackoff( diff --git a/packages/rest/src/lib/utils/utils.ts b/packages/rest/src/lib/utils/utils.ts index 30292d5f7..22a104e0a 100644 --- a/packages/rest/src/lib/utils/utils.ts +++ b/packages/rest/src/lib/utils/utils.ts @@ -20,13 +20,19 @@ function serializeSearchParam(value: unknown): string | null { case 'boolean': return value.toString(); case 'object': - if (value === null) return null; + if (value === null) { + return null; + } + if (value instanceof Date) { return Number.isNaN(value.getTime()) ? null : value.toISOString(); } - // eslint-disable-next-line @typescript-eslint/no-base-to-string - if (typeof value.toString === 'function' && value.toString !== Object.prototype.toString) return value.toString(); + if (typeof value.toString === 'function' && value.toString !== Object.prototype.toString) { + // eslint-disable-next-line @typescript-eslint/no-base-to-string + return value.toString(); + } + return null; default: return null; @@ -42,11 +48,15 @@ function serializeSearchParam(value: unknown): string | null { */ export function makeURLSearchParams(options?: Readonly) { const params = new URLSearchParams(); - if (!options) return params; + if (!options) { + return params; + } for (const [key, value] of Object.entries(options)) { const serialized = serializeSearchParam(value); - if (serialized !== null) params.append(key, serialized); + if (serialized !== null) { + params.append(key, serialized); + } } return params; @@ -78,9 +88,15 @@ export function hasSublimit(bucketRoute: string, body?: unknown, method?: string // Currently known sublimits: // Editing channel `name` or `topic` if (bucketRoute === '/channels/:id') { - if (typeof body !== 'object' || body === null) return false; + if (typeof body !== 'object' || body === null) { + return false; + } + // This should never be a POST body, but just in case - if (method !== RequestMethod.Patch) return false; + if (method !== RequestMethod.Patch) { + return false; + } + const castedBody = body as RESTPatchAPIChannelJSONBody; return ['name', 'topic'].some((key) => Reflect.has(castedBody, key)); } @@ -97,7 +113,10 @@ export function hasSublimit(bucketRoute: string, body?: unknown, method?: string */ export function shouldRetry(error: Error | NodeJS.ErrnoException) { // Retry for possible timed out requests - if (error.name === 'AbortError') return true; + if (error.name === 'AbortError') { + return true; + } + // Downlevel ECONNRESET to retry as it may be recoverable return ('code' in error && error.code === 'ECONNRESET') || error.message.includes('ECONNRESET'); } @@ -109,7 +128,9 @@ export function shouldRetry(error: Error | NodeJS.ErrnoException) { */ export async function onRateLimit(manager: REST, rateLimitData: RateLimitData) { const { options } = manager; - if (!options.rejectOnRateLimit) return; + if (!options.rejectOnRateLimit) { + return; + } const shouldThrow = typeof options.rejectOnRateLimit === 'function' diff --git a/packages/scripts/package.json b/packages/scripts/package.json index 8cab0439c..95618e478 100644 --- a/packages/scripts/package.json +++ b/packages/scripts/package.json @@ -5,7 +5,7 @@ "description": "A set of scripts that we use for our workflows", "private": true, "scripts": { - "build": "tsc --noEmit --lib ESNext,DOM && tsup", + "build": "tsc --skipLibCheck --noEmit --lib ESNext,DOM && tsup", "lint": "prettier --check . && cross-env TIMING=1 eslint --format=pretty src turbo/generators/config.ts", "format": "prettier --write . && cross-env TIMING=1 eslint --fix --format=pretty src turbo/generators/config.ts", "fmt": "pnpm run format" diff --git a/packages/scripts/src/generateSplitDocumentation.ts b/packages/scripts/src/generateSplitDocumentation.ts index ffdf1e65c..3835beac4 100644 --- a/packages/scripts/src/generateSplitDocumentation.ts +++ b/packages/scripts/src/generateSplitDocumentation.ts @@ -137,7 +137,7 @@ function resolveCanonicalReference( 'packageName' in canonicalReference.source && canonicalReference.symbol?.componentPath && canonicalReference.symbol.meaning - ) + ) { return { package: canonicalReference.source.packageName, unscopedPackage: canonicalReference.source.unscopedPackageName, @@ -154,7 +154,7 @@ function resolveCanonicalReference( // eslint-disable-next-line unicorn/better-regex version: apiPackage?.dependencies?.[canonicalReference.source.packageName]?.replace(/[~^]/, ''), }; - else if ( + } else if ( 'memberReferences' in canonicalReference && canonicalReference.memberReferences.length && canonicalReference.memberReferences[0]?.memberIdentifier && @@ -504,7 +504,10 @@ function resolveFileUrl(item: ApiDeclaredItem) { const [, pkg] = fileUrl.split('/node_modules/'); const parts = pkg?.split('/')[1]?.split('@'); const unscoped = parts?.[0]?.length; - if (!unscoped) parts?.shift(); + if (!unscoped) { + parts?.shift(); + } + const pkgName = parts?.shift(); const version = parts?.shift()?.split('_')?.[0]; @@ -512,8 +515,9 @@ function resolveFileUrl(item: ApiDeclaredItem) { // https://github.com/discordjs/discord.js/tree/main/node_modules/.pnpm/@discordjs+ws@1.1.1_bufferutil@4.0.8_utf-8-validate@6.0.4/node_modules/@discordjs/ws/dist/index.d.ts#L... if (!unscoped && pkgName?.startsWith('discordjs+')) { let currentItem = item; - while (currentItem.parent && currentItem.parent.kind !== ApiItemKind.EntryPoint) + while (currentItem.parent && currentItem.parent.kind !== ApiItemKind.EntryPoint) { currentItem = currentItem.parent as ApiDeclaredItem; + } return { sourceURL: `/docs/packages/${pkgName.replace('discordjs+', '')}/${version}/${currentItem.displayName}:${currentItem.kind}`, @@ -523,8 +527,9 @@ function resolveFileUrl(item: ApiDeclaredItem) { // https://github.com/discordjs/discord.js/tree/main/node_modules/.pnpm/discord-api-types@0.37.97/node_modules/discord-api-types/payloads/v10/gateway.d.ts#L240 if (pkgName === 'discord-api-types') { let currentItem = item; - while (currentItem.parent && currentItem.parent.kind !== ApiItemKind.EntryPoint) + while (currentItem.parent && currentItem.parent.kind !== ApiItemKind.EntryPoint) { currentItem = currentItem.parent as ApiDeclaredItem; + } return { sourceURL: `/docs/packages/${pkgName}/${version}/${(currentItem.parent as ApiEntryPoint).importPath}/${currentItem.displayName}:${currentItem.kind}`, @@ -537,8 +542,9 @@ function resolveFileUrl(item: ApiDeclaredItem) { // https://github.com/discordjs/discord.js/tree/main/packages/builders/dist/index.d.ts let currentItem = item; - while (currentItem.parent && currentItem.parent.kind !== ApiItemKind.EntryPoint) + while (currentItem.parent && currentItem.parent.kind !== ApiItemKind.EntryPoint) { currentItem = currentItem.parent as ApiDeclaredItem; + } return { sourceURL: `/docs/packages/${pkgName}/${version}/${currentItem.displayName}:${currentItem.kind}`, diff --git a/packages/scripts/turbo/generators/config.ts b/packages/scripts/turbo/generators/config.ts index 055dfde19..0541113d6 100644 --- a/packages/scripts/turbo/generators/config.ts +++ b/packages/scripts/turbo/generators/config.ts @@ -9,7 +9,7 @@ interface LabelerData { function sortYAMLObject(yaml: Record) { const sortedYAML: typeof yaml = {}; - for (const key of Object.keys(yaml).sort((a, b) => a.localeCompare(b))) sortedYAML[key] = yaml[key]!; + for (const key of Object.keys(yaml).sort((a, b) => a.localeCompare(b))) {sortedYAML[key] = yaml[key]!;} return sortedYAML; } diff --git a/packages/structures/src/Mixin.ts b/packages/structures/src/Mixin.ts index 8f637a5a9..31660681b 100644 --- a/packages/structures/src/Mixin.ts +++ b/packages/structures/src/Mixin.ts @@ -80,8 +80,10 @@ export function Mixin>( // Special case for optimize function, we want to combine these if (prop === OptimizeDataPropertyName) { - if (typeof descriptor.value !== 'function') + if (typeof descriptor.value !== 'function') { throw new RangeError(`Expected ${prop} to be a function, received ${typeof descriptor.value} instead.`); + } + dataOptimizations.push(descriptor.value); continue; } diff --git a/packages/structures/src/bitfields/BitField.ts b/packages/structures/src/bitfields/BitField.ts index e7e0138c4..fe9ebbe31 100644 --- a/packages/structures/src/bitfields/BitField.ts +++ b/packages/structures/src/bitfields/BitField.ts @@ -107,7 +107,10 @@ export abstract class BitField { total |= this.constructor.resolve(bit); } - if (Object.isFrozen(this)) return new this.constructor(this.bitField | total); + if (Object.isFrozen(this)) { + return new this.constructor(this.bitField | total); + } + this.bitField |= total; return this; } @@ -124,7 +127,10 @@ export abstract class BitField { total |= this.constructor.resolve(bit); } - if (Object.isFrozen(this)) return new this.constructor(this.bitField & ~total); + if (Object.isFrozen(this)) { + return new this.constructor(this.bitField & ~total); + } + this.bitField &= ~total; return this; } @@ -138,7 +144,9 @@ export abstract class BitField { public serialize(...hasParams: readonly unknown[]) { const serialized: Partial> = {}; for (const [flag, bit] of Object.entries(this.constructor.Flags)) { - if (Number.isNaN(Number(flag))) serialized[flag as keyof Flags] = this.has(bit as bigint | number, ...hasParams); + if (Number.isNaN(Number(flag))) { + serialized[flag as keyof Flags] = this.has(bit as bigint | number, ...hasParams); + } } return serialized; @@ -174,7 +182,9 @@ export abstract class BitField { public *[Symbol.iterator](...hasParams: unknown[]) { for (const bitName of Object.keys(this.constructor.Flags)) { - if (Number.isNaN(Number(bitName)) && this.has(bitName as Flags, ...hasParams)) yield bitName as Flags; + if (Number.isNaN(Number(bitName)) && this.has(bitName as Flags, ...hasParams)) { + yield bitName as Flags; + } } } @@ -186,16 +196,30 @@ export abstract class BitField { */ public static resolve(bit: BitFieldResolvable): bigint { const DefaultBit = this.DefaultBit; - if (typeof bit === 'bigint' && bit >= DefaultBit) return bit; - if (typeof bit === 'number' && BigInt(bit) >= DefaultBit) return BigInt(bit); - if (bit instanceof BitField) return bit.bitField; + if (typeof bit === 'bigint' && bit >= DefaultBit) { + return bit; + } + + if (typeof bit === 'number' && BigInt(bit) >= DefaultBit) { + return BigInt(bit); + } + + if (bit instanceof BitField) { + return bit.bitField; + } + if (Array.isArray(bit)) { return bit.map((bit_) => this.resolve(bit_)).reduce((prev, bit_) => prev | bit_, DefaultBit); } if (typeof bit === 'string') { - if (!Number.isNaN(Number(bit))) return BigInt(bit); - if (bit in this.Flags) return this.Flags[bit as keyof typeof this.Flags]; + if (!Number.isNaN(Number(bit))) { + return BigInt(bit); + } + + if (bit in this.Flags) { + return this.Flags[bit as keyof typeof this.Flags]; + } } throw new Error(`BitFieldInvalid: ${JSON.stringify(bit)}`); diff --git a/packages/structures/src/users/User.ts b/packages/structures/src/users/User.ts index 49aa22faa..c07be6a89 100644 --- a/packages/structures/src/users/User.ts +++ b/packages/structures/src/users/User.ts @@ -174,7 +174,10 @@ export class User extends Structure { // Run through a few packet cycles for (let index = 1; index <= 5; index++) { expect(player.state.status).toEqual(AudioPlayerStatus.Playing); - if (player.state.status !== AudioPlayerStatus.Playing) throw new Error('Error'); + if (player.state.status !== AudioPlayerStatus.Playing) { + throw new Error('Error'); + } + expect(player.state.playbackDuration).toStrictEqual((index - 1) * 20); expect(player.state.missedFrames).toEqual(index - 1); player['_stepDispatch'](); diff --git a/packages/voice/__tests__/demuxProbe.test.ts b/packages/voice/__tests__/demuxProbe.test.ts index cec2107c5..f3d7d8dd3 100644 --- a/packages/voice/__tests__/demuxProbe.test.ts +++ b/packages/voice/__tests__/demuxProbe.test.ts @@ -79,7 +79,9 @@ describe('demuxProbe', () => { test('Detects WebM', async () => { const stream = Readable.from(gen(10), { objectMode: false }); webmWrite.mockImplementation(function mock(data: Buffer) { - if (data[0] === 5) this.emit('head', validHead); + if (data[0] === 5) { + this.emit('head', validHead); + } } as any); const probe = await demuxProbe(stream); expect(probe.type).toEqual(StreamType.WebmOpus); @@ -89,7 +91,9 @@ describe('demuxProbe', () => { test('Detects Ogg', async () => { const stream = Readable.from(gen(10), { objectMode: false }); oggWrite.mockImplementation(function mock(data: Buffer) { - if (data[0] === 5) this.emit('head', validHead); + if (data[0] === 5) { + this.emit('head', validHead); + } } as any); const probe = await demuxProbe(stream); expect(probe.type).toEqual(StreamType.OggOpus); @@ -99,7 +103,9 @@ describe('demuxProbe', () => { test('Rejects invalid OpusHead', async () => { const stream = Readable.from(gen(10), { objectMode: false }); oggWrite.mockImplementation(function mock(data: Buffer) { - if (data[0] === 5) this.emit('head', invalidHead); + if (data[0] === 5) { + this.emit('head', invalidHead); + } } as any); const probe = await demuxProbe(stream); expect(probe.type).toEqual(StreamType.Arbitrary); diff --git a/packages/voice/src/DataStore.ts b/packages/voice/src/DataStore.ts index 7a525fe16..ffb0db6b2 100644 --- a/packages/voice/src/DataStore.ts +++ b/packages/voice/src/DataStore.ts @@ -35,7 +35,10 @@ groups.set('default', new Map()); function getOrCreateGroup(group: string) { const existing = groups.get(group); - if (existing) return existing; + if (existing) { + return existing; + } + const map = new Map(); groups.set(group, map); return map; @@ -114,7 +117,9 @@ const audioPlayers: AudioPlayer[] = []; * the next audio frame. */ function audioCycleStep() { - if (nextTime === -1) return; + if (nextTime === -1) { + return; + } nextTime += FRAME_LENGTH; const available = audioPlayers.filter((player) => player.checkPlayable()); @@ -165,7 +170,10 @@ export function hasAudioPlayer(target: AudioPlayer) { * @param player - The player to track */ export function addAudioPlayer(player: AudioPlayer) { - if (hasAudioPlayer(player)) return player; + if (hasAudioPlayer(player)) { + return player; + } + audioPlayers.push(player); if (audioPlayers.length === 1) { nextTime = Date.now(); @@ -180,10 +188,15 @@ export function addAudioPlayer(player: AudioPlayer) { */ export function deleteAudioPlayer(player: AudioPlayer) { const index = audioPlayers.indexOf(player); - if (index === -1) return; + if (index === -1) { + return; + } + audioPlayers.splice(index, 1); if (audioPlayers.length === 0) { nextTime = -1; - if (audioCycleInterval !== undefined) clearTimeout(audioCycleInterval); + if (audioCycleInterval !== undefined) { + clearTimeout(audioCycleInterval); + } } } diff --git a/packages/voice/src/VoiceConnection.ts b/packages/voice/src/VoiceConnection.ts index 33f275dfc..4986f3fdc 100644 --- a/packages/voice/src/VoiceConnection.ts +++ b/packages/voice/src/VoiceConnection.ts @@ -312,14 +312,18 @@ export class VoiceConnection extends EventEmitter { oldNetworking.destroy(); } - if (newNetworking) this.updateReceiveBindings(newNetworking.state, oldNetworking?.state); + if (newNetworking) { + this.updateReceiveBindings(newNetworking.state, oldNetworking?.state); + } } if (newState.status === VoiceConnectionStatus.Ready) { this.rejoinAttempts = 0; } else if (newState.status === VoiceConnectionStatus.Destroyed) { for (const stream of this.receiver.subscriptions.values()) { - if (!stream.destroyed) stream.destroy(); + if (!stream.destroyed) { + stream.destroy(); + } } } @@ -368,9 +372,17 @@ export class VoiceConnection extends EventEmitter { private addStatePacket(packet: GatewayVoiceStateUpdateDispatchData) { this.packets.state = packet; - if (packet.self_deaf !== undefined) this.joinConfig.selfDeaf = packet.self_deaf; - if (packet.self_mute !== undefined) this.joinConfig.selfMute = packet.self_mute; - if (packet.channel_id) this.joinConfig.channelId = packet.channel_id; + if (packet.self_deaf !== undefined) { + this.joinConfig.selfDeaf = packet.self_deaf; + } + + if (packet.self_mute !== undefined) { + this.joinConfig.selfMute = packet.self_mute; + } + + if (packet.channel_id) { + this.joinConfig.channelId = packet.channel_id; + } /* the channel_id being null doesn't necessarily mean it was intended for the client to leave the voice channel as it may have disconnected due to network failure. This will be gracefully handled once the voice websocket @@ -417,7 +429,9 @@ export class VoiceConnection extends EventEmitter { */ public configureNetworking() { const { server, state } = this.packets; - if (!server || !state || this.state.status === VoiceConnectionStatus.Destroyed || !server.endpoint) return; + if (!server || !state || this.state.status === VoiceConnectionStatus.Destroyed || !server.endpoint) { + return; + } const networking = new Networking( { @@ -460,7 +474,10 @@ export class VoiceConnection extends EventEmitter { * @param code - The close code */ private onNetworkingClose(code: number) { - if (this.state.status === VoiceConnectionStatus.Destroyed) return; + if (this.state.status === VoiceConnectionStatus.Destroyed) { + return; + } + // If networking closes, try to connect to the voice channel again. if (code === 4_014) { // Disconnected - networking is already destroyed here @@ -494,9 +511,13 @@ export class VoiceConnection extends EventEmitter { */ private onNetworkingStateChange(oldState: NetworkingState, newState: NetworkingState) { this.updateReceiveBindings(newState, oldState); - if (oldState.code === newState.code) return; - if (this.state.status !== VoiceConnectionStatus.Connecting && this.state.status !== VoiceConnectionStatus.Ready) + if (oldState.code === newState.code) { return; + } + + if (this.state.status !== VoiceConnectionStatus.Connecting && this.state.status !== VoiceConnectionStatus.Ready) { + return; + } if (newState.code === NetworkingStatusCode.Ready) { this.state = { @@ -545,7 +566,10 @@ export class VoiceConnection extends EventEmitter { */ public prepareAudioPacket(buffer: Buffer) { const state = this.state; - if (state.status !== VoiceConnectionStatus.Ready) return; + if (state.status !== VoiceConnectionStatus.Ready) { + return; + } + return state.networking.prepareAudioPacket(buffer); } @@ -554,7 +578,10 @@ export class VoiceConnection extends EventEmitter { */ public dispatchAudio() { const state = this.state; - if (state.status !== VoiceConnectionStatus.Ready) return; + if (state.status !== VoiceConnectionStatus.Ready) { + return; + } + return state.networking.dispatchAudio(); } @@ -565,7 +592,10 @@ export class VoiceConnection extends EventEmitter { */ public playOpusPacket(buffer: Buffer) { const state = this.state; - if (state.status !== VoiceConnectionStatus.Ready) return; + if (state.status !== VoiceConnectionStatus.Ready) { + return; + } + state.networking.prepareAudioPacket(buffer); return state.networking.dispatchAudio(); } @@ -644,7 +674,10 @@ export class VoiceConnection extends EventEmitter { const notReady = this.state.status !== VoiceConnectionStatus.Ready; - if (notReady) this.rejoinAttempts++; + if (notReady) { + this.rejoinAttempts++; + } + Object.assign(this.joinConfig, joinConfig); if (this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) { if (notReady) { @@ -673,7 +706,10 @@ export class VoiceConnection extends EventEmitter { * @param enabled - Whether or not to show as speaking */ public setSpeaking(enabled: boolean) { - if (this.state.status !== VoiceConnectionStatus.Ready) return false; + if (this.state.status !== VoiceConnectionStatus.Ready) { + return false; + } + // eslint-disable-next-line @typescript-eslint/no-confusing-void-expression return this.state.networking.setSpeaking(enabled); } @@ -685,7 +721,9 @@ export class VoiceConnection extends EventEmitter { * @returns The created subscription */ public subscribe(player: AudioPlayer) { - if (this.state.status === VoiceConnectionStatus.Destroyed) return; + if (this.state.status === VoiceConnectionStatus.Destroyed) { + return; + } // eslint-disable-next-line @typescript-eslint/dot-notation const subscription = player['subscribe'](this); diff --git a/packages/voice/src/audio/AudioPlayer.ts b/packages/voice/src/audio/AudioPlayer.ts index bfa23af74..47dfe2af0 100644 --- a/packages/voice/src/audio/AudioPlayer.ts +++ b/packages/voice/src/audio/AudioPlayer.ts @@ -458,7 +458,10 @@ export class AudioPlayer extends EventEmitter { * @returns `true` if the player was successfully paused, otherwise `false` */ public pause(interpolateSilence = true) { - if (this.state.status !== AudioPlayerStatus.Playing) return false; + if (this.state.status !== AudioPlayerStatus.Playing) { + return false; + } + this.state = { ...this.state, status: AudioPlayerStatus.Paused, @@ -473,7 +476,10 @@ export class AudioPlayer extends EventEmitter { * @returns `true` if the player was successfully unpaused, otherwise `false` */ public unpause() { - if (this.state.status !== AudioPlayerStatus.Paused) return false; + if (this.state.status !== AudioPlayerStatus.Paused) { + return false; + } + this.state = { ...this.state, status: AudioPlayerStatus.Playing, @@ -490,7 +496,10 @@ export class AudioPlayer extends EventEmitter { * @returns `true` if the player will come to a stop, otherwise `false` */ public stop(force = false) { - if (this.state.status === AudioPlayerStatus.Idle) return false; + if (this.state.status === AudioPlayerStatus.Idle) { + return false; + } + if (force || this.state.resource.silencePaddingFrames === 0) { this.state = { status: AudioPlayerStatus.Idle, @@ -509,7 +518,9 @@ export class AudioPlayer extends EventEmitter { */ public checkPlayable() { const state = this._state; - if (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) return false; + if (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) { + return false; + } // If the stream has been destroyed or is no longer readable, then transition to the Idle state. if (!state.resource.readable) { @@ -531,7 +542,9 @@ export class AudioPlayer extends EventEmitter { const state = this._state; // Guard against the Idle state - if (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) return; + if (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) { + return; + } // Dispatch any audio packets that were prepared in the previous cycle for (const connection of this.playable) { @@ -549,7 +562,9 @@ export class AudioPlayer extends EventEmitter { const state = this._state; // Guard against the Idle state - if (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) return; + if (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) { + return; + } // List of connections that can receive the packet const playable = this.playable; diff --git a/packages/voice/src/audio/AudioResource.ts b/packages/voice/src/audio/AudioResource.ts index 1fc9f60a3..3327e8569 100644 --- a/packages/voice/src/audio/AudioResource.ts +++ b/packages/voice/src/audio/AudioResource.ts @@ -123,10 +123,16 @@ export class AudioResource { * while there are silence padding frames left to play. */ public get readable() { - if (this.silenceRemaining === 0) return false; + if (this.silenceRemaining === 0) { + return false; + } + const real = this.playStream.readable; if (!real) { - if (this.silenceRemaining === -1) this.silenceRemaining = this.silencePaddingFrames; + if (this.silenceRemaining === -1) { + this.silenceRemaining = this.silencePaddingFrames; + } + return this.silenceRemaining !== 0; } @@ -274,7 +280,10 @@ export function createAudioResource( const transformerPipeline = findPipeline(inputType, needsInlineVolume ? VOLUME_CONSTRAINT : NO_CONSTRAINT); if (transformerPipeline.length === 0) { - if (typeof input === 'string') throw new Error(`Invalid pipeline constructed for string resource '${input}'`); + if (typeof input === 'string') { + throw new TypeError(`Invalid pipeline constructed for string resource '${input}'`); + } + // No adjustments required return new AudioResource( [], @@ -285,7 +294,9 @@ export function createAudioResource( } const streams = transformerPipeline.map((edge) => edge.transformer(input)); - if (typeof input !== 'string') streams.unshift(input); + if (typeof input !== 'string') { + streams.unshift(input); + } return new AudioResource( transformerPipeline, diff --git a/packages/voice/src/audio/TransformerGraph.ts b/packages/voice/src/audio/TransformerGraph.ts index 4fe8d6838..70ec9efa2 100644 --- a/packages/voice/src/audio/TransformerGraph.ts +++ b/packages/voice/src/audio/TransformerGraph.ts @@ -110,7 +110,10 @@ let NODES: Map | null = null; */ export function getNode(type: StreamType) { const node = (NODES ??= initializeNodes()).get(type); - if (!node) throw new Error(`Node type '${type}' does not exist!`); + if (!node) { + throw new Error(`Node type '${type}' does not exist!`); + } + return node; } @@ -243,7 +246,10 @@ function findPath( let currentBest: Step | undefined; for (const edge of from.edges) { - if (currentBest && edge.cost > currentBest.cost) continue; + if (currentBest && edge.cost > currentBest.cost) { + continue; + } + const next = findPath(edge.to, constraints, goal, [...path, edge], depth - 1); const cost = edge.cost + next.cost; if (!currentBest || cost < currentBest.cost) { diff --git a/packages/voice/src/networking/DAVESession.ts b/packages/voice/src/networking/DAVESession.ts index 0e3a3de65..b0779dfc9 100644 --- a/packages/voice/src/networking/DAVESession.ts +++ b/packages/voice/src/networking/DAVESession.ts @@ -135,11 +135,12 @@ export class DAVESession extends EventEmitter { public session: SessionMethods | undefined; public constructor(protocolVersion: number, userId: string, channelId: string, options: DAVESessionOptions) { - if (Davey === null) + if (Davey === null) { throw new Error( `Cannot utilize the DAVE protocol as the @snazzah/davey package has not been installed. - Use the generateDependencyReport() function for more information.\n`, ); + } super(); @@ -166,7 +167,10 @@ export class DAVESession extends EventEmitter { * @throws Will throw if there is not an active session or the user id provided is invalid or not in the session. */ public async getVerificationCode(userId: string): Promise { - if (!this.session) throw new Error('Session not available'); + if (!this.session) { + throw new Error('Session not available'); + } + return this.session.getVerificationCode(userId); } @@ -197,7 +201,10 @@ export class DAVESession extends EventEmitter { * @param externalSender - The external sender */ public setExternalSender(externalSender: Buffer) { - if (!this.session) throw new Error('No session available'); + if (!this.session) { + throw new Error('No session available'); + } + this.session.setExternalSender(externalSender); this.emit('debug', 'Set MLS external sender'); } @@ -216,7 +223,10 @@ export class DAVESession extends EventEmitter { if (data.transition_id === 0) { this.executeTransition(data.transition_id); } else { - if (data.protocol_version === 0) this.session?.setPassthroughMode(true, TRANSITION_EXPIRY_PENDING_DOWNGRADE); + if (data.protocol_version === 0) { + this.session?.setPassthroughMode(true, TRANSITION_EXPIRY_PENDING_DOWNGRADE); + } + return true; } @@ -285,7 +295,10 @@ export class DAVESession extends EventEmitter { * @param transitionId - The transition id to invalidate */ public recoverFromInvalidTransition(transitionId: number) { - if (this.reinitializing) return; + if (this.reinitializing) { + return; + } + this.emit('debug', `Invalidating transition ${transitionId}`); this.reinitializing = true; this.consecutiveFailures = 0; @@ -301,7 +314,10 @@ export class DAVESession extends EventEmitter { * @returns The payload to send back to the voice server, if there is one */ public processProposals(payload: Buffer, connectedClients: Set): Buffer | undefined { - if (!this.session) throw new Error('No session available'); + if (!this.session) { + throw new Error('No session available'); + } + const optype = payload.readUInt8(0) as 0 | 1; const { commit, welcome } = this.session.processProposals( optype, @@ -309,7 +325,10 @@ export class DAVESession extends EventEmitter { Array.from(connectedClients), ); this.emit('debug', 'MLS proposals processed'); - if (!commit) return; + if (!commit) { + return; + } + return welcome ? Buffer.concat([commit, welcome]) : commit; } @@ -320,7 +339,10 @@ export class DAVESession extends EventEmitter { * @returns The transaction id and whether it was successful */ public processCommit(payload: Buffer): TransitionResult { - if (!this.session) throw new Error('No session available'); + if (!this.session) { + throw new Error('No session available'); + } + const transitionId = payload.readUInt16BE(0); try { this.session.processCommit(payload.subarray(2)); @@ -347,7 +369,10 @@ export class DAVESession extends EventEmitter { * @returns The transaction id and whether it was successful */ public processWelcome(payload: Buffer): TransitionResult { - if (!this.session) throw new Error('No session available'); + if (!this.session) { + throw new Error('No session available'); + } + const transitionId = payload.readUInt16BE(0); try { this.session.processWelcome(payload.subarray(2)); @@ -373,7 +398,10 @@ export class DAVESession extends EventEmitter { * @param packet - The packet to encrypt */ public encrypt(packet: Buffer) { - if (this.protocolVersion === 0 || !this.session?.ready || packet.equals(SILENCE_FRAME)) return packet; + if (this.protocolVersion === 0 || !this.session?.ready || packet.equals(SILENCE_FRAME)) { + return packet; + } + return this.session.encryptOpus(packet); } @@ -386,7 +414,10 @@ export class DAVESession extends EventEmitter { */ public decrypt(packet: Buffer, userId: string) { const canDecrypt = this.session?.ready && (this.protocolVersion !== 0 || this.session?.canPassthrough(userId)); - if (packet.equals(SILENCE_FRAME) || !canDecrypt || !this.session) return packet; + if (packet.equals(SILENCE_FRAME) || !canDecrypt || !this.session) { + return packet; + } + try { const buffer = this.session.decrypt(userId, Davey.MediaType.AUDIO, packet); this.consecutiveFailures = 0; @@ -396,8 +427,11 @@ export class DAVESession extends EventEmitter { this.consecutiveFailures++; this.emit('debug', `Failed to decrypt a packet (${this.consecutiveFailures} consecutive fails)`); if (this.consecutiveFailures > this.failureTolerance) { - if (this.lastTransitionId) this.recoverFromInvalidTransition(this.lastTransitionId); - else throw error; + if (this.lastTransitionId) { + this.recoverFromInvalidTransition(this.lastTransitionId); + } else { + throw error; + } } } else if (this.reinitializing) { this.emit('debug', 'Failed to decrypt a packet (reinitializing session)'); diff --git a/packages/voice/src/networking/Networking.ts b/packages/voice/src/networking/Networking.ts index 5c1ff6e8f..71627583c 100644 --- a/packages/voice/src/networking/Networking.ts +++ b/packages/voice/src/networking/Networking.ts @@ -487,7 +487,10 @@ export class Networking extends EventEmitter { .performIPDiscovery(ssrc) // eslint-disable-next-line promise/prefer-await-to-then .then((localConfig) => { - if (this.state.code !== NetworkingStatusCode.UdpHandshaking) return; + if (this.state.code !== NetworkingStatusCode.UdpHandshaking) { + return; + } + this.state.ws.sendPacket({ op: VoiceOpcodes.SelectProtocol, d: { @@ -551,9 +554,11 @@ export class Networking extends EventEmitter { this.state.code === NetworkingStatusCode.Resuming) ) { const { connectionData } = this.state; - if (packet.op === VoiceOpcodes.ClientsConnect) - for (const id of packet.d.user_ids) connectionData.connectedClients.add(id); - else { + if (packet.op === VoiceOpcodes.ClientsConnect) { + for (const id of packet.d.user_ids) { + connectionData.connectedClients.add(id); + } + } else { connectionData.connectedClients.delete(packet.d.user_id); } } else if ( @@ -562,18 +567,24 @@ export class Networking extends EventEmitter { ) { if (packet.op === VoiceOpcodes.DavePrepareTransition) { const sendReady = this.state.dave.prepareTransition(packet.d); - if (sendReady) + if (sendReady) { this.state.ws.sendPacket({ op: VoiceOpcodes.DaveTransitionReady, d: { transition_id: packet.d.transition_id }, }); + } + if (packet.d.transition_id === 0) { this.emit('transitioned', 0); } } else if (packet.op === VoiceOpcodes.DaveExecuteTransition) { const transitioned = this.state.dave.executeTransition(packet.d.transition_id); - if (transitioned) this.emit('transitioned', packet.d.transition_id); - } else if (packet.op === VoiceOpcodes.DavePrepareEpoch) this.state.dave.prepareEpoch(packet.d); + if (transitioned) { + this.emit('transitioned', packet.d.transition_id); + } + } else if (packet.op === VoiceOpcodes.DavePrepareEpoch) { + this.state.dave.prepareEpoch(packet.d); + } } } @@ -588,26 +599,32 @@ export class Networking extends EventEmitter { this.state.dave.setExternalSender(message.payload); } else if (message.op === VoiceOpcodes.DaveMlsProposals) { const payload = this.state.dave.processProposals(message.payload, this.state.connectionData.connectedClients); - if (payload) this.state.ws.sendBinaryMessage(VoiceOpcodes.DaveMlsCommitWelcome, payload); + if (payload) { + this.state.ws.sendBinaryMessage(VoiceOpcodes.DaveMlsCommitWelcome, payload); + } } else if (message.op === VoiceOpcodes.DaveMlsAnnounceCommitTransition) { const { transitionId, success } = this.state.dave.processCommit(message.payload); if (success) { - if (transitionId === 0) this.emit('transitioned', transitionId); - else + if (transitionId === 0) { + this.emit('transitioned', transitionId); + } else { this.state.ws.sendPacket({ op: VoiceOpcodes.DaveTransitionReady, d: { transition_id: transitionId }, }); + } } } else if (message.op === VoiceOpcodes.DaveMlsWelcome) { const { transitionId, success } = this.state.dave.processWelcome(message.payload); if (success) { - if (transitionId === 0) this.emit('transitioned', transitionId); - else + if (transitionId === 0) { + this.emit('transitioned', transitionId); + } else { this.state.ws.sendPacket({ op: VoiceOpcodes.DaveTransitionReady, d: { transition_id: transitionId }, }); + } } } } @@ -619,8 +636,9 @@ export class Networking extends EventEmitter { * @param keyPackage - The new key package */ private onDaveKeyPackage(keyPackage: Buffer) { - if (this.state.code === NetworkingStatusCode.SelectingProtocol || this.state.code === NetworkingStatusCode.Ready) + if (this.state.code === NetworkingStatusCode.SelectingProtocol || this.state.code === NetworkingStatusCode.Ready) { this.state.ws.sendBinaryMessage(VoiceOpcodes.DaveMlsKeyPackage, keyPackage); + } } /** @@ -629,11 +647,12 @@ export class Networking extends EventEmitter { * @param transitionId - The transition to invalidate */ private onDaveInvalidateTransition(transitionId: number) { - if (this.state.code === NetworkingStatusCode.SelectingProtocol || this.state.code === NetworkingStatusCode.Ready) + if (this.state.code === NetworkingStatusCode.SelectingProtocol || this.state.code === NetworkingStatusCode.Ready) { this.state.ws.sendPacket({ op: VoiceOpcodes.DaveMlsInvalidCommitWelcome, d: { transition_id: transitionId }, }); + } } /** @@ -675,7 +694,10 @@ export class Networking extends EventEmitter { */ public prepareAudioPacket(opusPacket: Buffer) { const state = this.state; - if (state.code !== NetworkingStatusCode.Ready) return; + if (state.code !== NetworkingStatusCode.Ready) { + return; + } + state.preparedPacket = this.createAudioPacket(opusPacket, state.connectionData, state.dave); return state.preparedPacket; } @@ -686,7 +708,10 @@ export class Networking extends EventEmitter { */ public dispatchAudio() { const state = this.state; - if (state.code !== NetworkingStatusCode.Ready) return false; + if (state.code !== NetworkingStatusCode.Ready) { + return false; + } + if (state.preparedPacket !== undefined) { this.playAudioPacket(state.preparedPacket); state.preparedPacket = undefined; @@ -703,13 +728,22 @@ export class Networking extends EventEmitter { */ private playAudioPacket(audioPacket: Buffer) { const state = this.state; - if (state.code !== NetworkingStatusCode.Ready) return; + if (state.code !== NetworkingStatusCode.Ready) { + return; + } + const { connectionData } = state; connectionData.packetsPlayed++; connectionData.sequence++; connectionData.timestamp += TIMESTAMP_INC; - if (connectionData.sequence >= 2 ** 16) connectionData.sequence = 0; - if (connectionData.timestamp >= 2 ** 32) connectionData.timestamp = 0; + if (connectionData.sequence >= 2 ** 16) { + connectionData.sequence = 0; + } + + if (connectionData.timestamp >= 2 ** 32) { + connectionData.timestamp = 0; + } + this.setSpeaking(true); state.udp.send(audioPacket); } @@ -722,8 +756,14 @@ export class Networking extends EventEmitter { */ public setSpeaking(speaking: boolean) { const state = this.state; - if (state.code !== NetworkingStatusCode.Ready) return; - if (state.connectionData.speaking === speaking) return; + if (state.code !== NetworkingStatusCode.Ready) { + return; + } + + if (state.connectionData.speaking === speaking) { + return; + } + state.connectionData.speaking = speaking; state.ws.sendPacket({ op: VoiceOpcodes.Speaking, @@ -777,7 +817,10 @@ export class Networking extends EventEmitter { // Both supported encryption methods want the nonce to be an incremental integer connectionData.nonce++; - if (connectionData.nonce > MAX_NONCE_SIZE) connectionData.nonce = 0; + if (connectionData.nonce > MAX_NONCE_SIZE) { + connectionData.nonce = 0; + } + connectionData.nonceBuffer.writeUInt32BE(connectionData.nonce, 0); // 4 extra bytes of padding on the end of the encrypted packet diff --git a/packages/voice/src/networking/VoiceUDPSocket.ts b/packages/voice/src/networking/VoiceUDPSocket.ts index 84bc40f17..b495954c0 100644 --- a/packages/voice/src/networking/VoiceUDPSocket.ts +++ b/packages/voice/src/networking/VoiceUDPSocket.ts @@ -152,7 +152,10 @@ export class VoiceUDPSocket extends EventEmitter { return new Promise((resolve, reject) => { const listener = (message: Buffer) => { try { - if (message.readUInt16BE(0) !== 2) return; + if (message.readUInt16BE(0) !== 2) { + return; + } + const packet = parseLocalPacket(message); this.socket.off('message', listener); resolve(packet); diff --git a/packages/voice/src/networking/VoiceWebSocket.ts b/packages/voice/src/networking/VoiceWebSocket.ts index 8996177b1..ba7177ebd 100644 --- a/packages/voice/src/networking/VoiceWebSocket.ts +++ b/packages/voice/src/networking/VoiceWebSocket.ts @@ -220,7 +220,10 @@ export class VoiceWebSocket extends EventEmitter { * @param ms - The interval in milliseconds. If negative, the interval will be unset */ public setHeartbeatInterval(ms: number) { - if (this.heartbeatInterval !== undefined) clearInterval(this.heartbeatInterval); + if (this.heartbeatInterval !== undefined) { + clearInterval(this.heartbeatInterval); + } + if (ms > 0) { this.heartbeatInterval = setInterval(() => { if (this.lastHeartbeatSend !== 0 && this.missedHeartbeats >= 3) { diff --git a/packages/voice/src/receive/SSRCMap.ts b/packages/voice/src/receive/SSRCMap.ts index 7ca5cb6bb..4279441e1 100644 --- a/packages/voice/src/receive/SSRCMap.ts +++ b/packages/voice/src/receive/SSRCMap.ts @@ -55,7 +55,10 @@ export class SSRCMap extends EventEmitter { }; this.map.set(data.audioSSRC, newValue); - if (!existing) this.emit('create', newValue); + if (!existing) { + this.emit('create', newValue); + } + this.emit('update', existing, newValue); } diff --git a/packages/voice/src/receive/VoiceReceiver.ts b/packages/voice/src/receive/VoiceReceiver.ts index 90e4015cb..4969f802b 100644 --- a/packages/voice/src/receive/VoiceReceiver.ts +++ b/packages/voice/src/receive/VoiceReceiver.ts @@ -84,7 +84,9 @@ export class VoiceReceiver { let headerSize = 12; const first = buffer.readUint8(); - if ((first >> 4) & 0x01) headerSize += 4; + if ((first >> 4) & 0x01) { + headerSize += 4; + } // The unencrypted RTP header contains 12 bytes, HEADER_EXTENSION and the extension size const header = buffer.subarray(0, headerSize); @@ -135,7 +137,9 @@ export class VoiceReceiver { */ private parsePacket(buffer: Buffer, mode: string, nonce: Buffer, secretKey: Uint8Array, userId: string) { let packet: Buffer = this.decrypt(buffer, mode, nonce, secretKey); - if (!packet) throw new Error('Failed to parse packet'); + if (!packet) { + throw new Error('Failed to parse packet'); + } // Strip decrypted RTP Header Extension if present // The header is only indicated in the original data, so compare with buffer first @@ -151,7 +155,9 @@ export class VoiceReceiver { this.voiceConnection.state.networking.state.code === NetworkingStatusCode.Resuming) ) { const daveSession = this.voiceConnection.state.networking.state.dave; - if (daveSession) packet = daveSession.decrypt(packet, userId)!; + if (daveSession) { + packet = daveSession.decrypt(packet, userId)!; + } } return packet; @@ -164,16 +170,23 @@ export class VoiceReceiver { * @internal */ public onUdpMessage(msg: Buffer) { - if (msg.length <= 8) return; + if (msg.length <= 8) { + return; + } + const ssrc = msg.readUInt32BE(8); const userData = this.ssrcMap.get(ssrc); - if (!userData) return; + if (!userData) { + return; + } this.speaking.onPacket(userData.userId); const stream = this.subscriptions.get(userData.userId); - if (!stream) return; + if (!stream) { + return; + } if (this.connectionData.encryptionMode && this.connectionData.nonceBuffer && this.connectionData.secretKey) { try { @@ -184,7 +197,9 @@ export class VoiceReceiver { this.connectionData.secretKey, userData.userId, ); - if (packet) stream.push(packet); + if (packet) { + stream.push(packet); + } } catch (error) { stream.destroy(error as Error); } @@ -199,7 +214,9 @@ export class VoiceReceiver { */ public subscribe(userId: string, options?: Partial) { const existing = this.subscriptions.get(userId); - if (existing) return existing; + if (existing) { + return existing; + } const stream = new AudioReceiveStream({ ...createDefaultAudioReceiveStreamOptions(), diff --git a/packages/voice/src/util/generateDependencyReport.ts b/packages/voice/src/util/generateDependencyReport.ts index ae49d708d..1bce82c4e 100644 --- a/packages/voice/src/util/generateDependencyReport.ts +++ b/packages/voice/src/util/generateDependencyReport.ts @@ -16,11 +16,17 @@ function findPackageJSON( packageName: string, depth: number, ): { name: string; version: string } | undefined { - if (depth === 0) return undefined; + if (depth === 0) { + return undefined; + } + const attemptedPath = resolve(dir, './package.json'); try { const pkg = require(attemptedPath); - if (pkg.name !== packageName) throw new Error('package.json does not match'); + if (pkg.name !== packageName) { + throw new Error('package.json does not match'); + } + return pkg; } catch { return findPackageJSON(resolve(dir, '..'), packageName, depth - 1);