@biggy1337/discord-sbjs 1.3.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (373) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +147 -0
  3. package/package.json +80 -0
  4. package/src/WebSocket.js +39 -0
  5. package/src/client/BaseClient.js +110 -0
  6. package/src/client/Client.js +1076 -0
  7. package/src/client/WebhookClient.js +61 -0
  8. package/src/client/actions/Action.js +133 -0
  9. package/src/client/actions/ActionsManager.js +80 -0
  10. package/src/client/actions/ApplicationCommandPermissionsUpdate.js +34 -0
  11. package/src/client/actions/AutoModerationActionExecution.js +27 -0
  12. package/src/client/actions/AutoModerationRuleCreate.js +28 -0
  13. package/src/client/actions/AutoModerationRuleDelete.js +32 -0
  14. package/src/client/actions/AutoModerationRuleUpdate.js +30 -0
  15. package/src/client/actions/ChannelCreate.js +23 -0
  16. package/src/client/actions/ChannelDelete.js +39 -0
  17. package/src/client/actions/ChannelUpdate.js +43 -0
  18. package/src/client/actions/GuildAuditLogEntryCreate.js +29 -0
  19. package/src/client/actions/GuildBanAdd.js +20 -0
  20. package/src/client/actions/GuildBanRemove.js +25 -0
  21. package/src/client/actions/GuildChannelsPositionUpdate.js +21 -0
  22. package/src/client/actions/GuildDelete.js +65 -0
  23. package/src/client/actions/GuildEmojiCreate.js +20 -0
  24. package/src/client/actions/GuildEmojiDelete.js +21 -0
  25. package/src/client/actions/GuildEmojiUpdate.js +20 -0
  26. package/src/client/actions/GuildEmojisUpdate.js +34 -0
  27. package/src/client/actions/GuildIntegrationsUpdate.js +19 -0
  28. package/src/client/actions/GuildMemberRemove.js +33 -0
  29. package/src/client/actions/GuildMemberUpdate.js +44 -0
  30. package/src/client/actions/GuildRoleCreate.js +25 -0
  31. package/src/client/actions/GuildRoleDelete.js +31 -0
  32. package/src/client/actions/GuildRoleUpdate.js +39 -0
  33. package/src/client/actions/GuildRolesPositionUpdate.js +21 -0
  34. package/src/client/actions/GuildScheduledEventCreate.js +27 -0
  35. package/src/client/actions/GuildScheduledEventDelete.js +31 -0
  36. package/src/client/actions/GuildScheduledEventUpdate.js +30 -0
  37. package/src/client/actions/GuildScheduledEventUserAdd.js +32 -0
  38. package/src/client/actions/GuildScheduledEventUserRemove.js +32 -0
  39. package/src/client/actions/GuildStickerCreate.js +20 -0
  40. package/src/client/actions/GuildStickerDelete.js +21 -0
  41. package/src/client/actions/GuildStickerUpdate.js +20 -0
  42. package/src/client/actions/GuildStickersUpdate.js +34 -0
  43. package/src/client/actions/GuildUpdate.js +33 -0
  44. package/src/client/actions/InviteCreate.js +28 -0
  45. package/src/client/actions/InviteDelete.js +30 -0
  46. package/src/client/actions/MessageCreate.js +50 -0
  47. package/src/client/actions/MessageDelete.js +34 -0
  48. package/src/client/actions/MessageDeleteBulk.js +43 -0
  49. package/src/client/actions/MessagePollVoteAdd.js +33 -0
  50. package/src/client/actions/MessagePollVoteRemove.js +33 -0
  51. package/src/client/actions/MessageReactionAdd.js +71 -0
  52. package/src/client/actions/MessageReactionRemove.js +39 -0
  53. package/src/client/actions/MessageReactionRemoveAll.js +36 -0
  54. package/src/client/actions/MessageReactionRemoveEmoji.js +30 -0
  55. package/src/client/actions/MessageUpdate.js +28 -0
  56. package/src/client/actions/PresenceUpdate.js +55 -0
  57. package/src/client/actions/StageInstanceCreate.js +28 -0
  58. package/src/client/actions/StageInstanceDelete.js +33 -0
  59. package/src/client/actions/StageInstanceUpdate.js +30 -0
  60. package/src/client/actions/ThreadCreate.js +24 -0
  61. package/src/client/actions/ThreadDelete.js +32 -0
  62. package/src/client/actions/ThreadListSync.js +60 -0
  63. package/src/client/actions/ThreadMemberUpdate.js +30 -0
  64. package/src/client/actions/ThreadMembersUpdate.js +38 -0
  65. package/src/client/actions/TypingStart.js +31 -0
  66. package/src/client/actions/UserUpdate.js +35 -0
  67. package/src/client/actions/VoiceStateUpdate.js +63 -0
  68. package/src/client/actions/WebhooksUpdate.js +20 -0
  69. package/src/client/voice/ClientVoiceManager.js +162 -0
  70. package/src/client/voice/StreamEventRouter.js +60 -0
  71. package/src/client/voice/VoiceConnection.js +1173 -0
  72. package/src/client/voice/dispatcher/AnnexBDispatcher.js +120 -0
  73. package/src/client/voice/dispatcher/AudioDispatcher.js +145 -0
  74. package/src/client/voice/dispatcher/BaseDispatcher.js +459 -0
  75. package/src/client/voice/dispatcher/VPxDispatcher.js +54 -0
  76. package/src/client/voice/dispatcher/VideoDispatcher.js +68 -0
  77. package/src/client/voice/networking/VoiceUDPClient.js +187 -0
  78. package/src/client/voice/networking/VoiceWebSocket.js +347 -0
  79. package/src/client/voice/player/MediaPlayer.js +321 -0
  80. package/src/client/voice/player/processing/AnnexBNalSplitter.js +244 -0
  81. package/src/client/voice/player/processing/IvfSplitter.js +106 -0
  82. package/src/client/voice/player/processing/PCMInsertSilence.js +37 -0
  83. package/src/client/voice/receiver/PacketHandler.js +260 -0
  84. package/src/client/voice/receiver/Receiver.js +96 -0
  85. package/src/client/voice/receiver/Recorder.js +191 -0
  86. package/src/client/voice/util/Function.js +116 -0
  87. package/src/client/voice/util/PlayInterface.js +122 -0
  88. package/src/client/voice/util/Secretbox.js +64 -0
  89. package/src/client/voice/util/Silence.js +16 -0
  90. package/src/client/voice/util/Socket.js +62 -0
  91. package/src/client/voice/util/VolumeInterface.js +104 -0
  92. package/src/client/websocket/DispatchTable.js +7 -0
  93. package/src/client/websocket/GatewaySendScheduler.js +122 -0
  94. package/src/client/websocket/WebSocketManager.js +439 -0
  95. package/src/client/websocket/WebSocketShard.js +1085 -0
  96. package/src/client/websocket/handlers/APPLICATION_COMMAND_CREATE.js +18 -0
  97. package/src/client/websocket/handlers/APPLICATION_COMMAND_DELETE.js +20 -0
  98. package/src/client/websocket/handlers/APPLICATION_COMMAND_PERMISSIONS_UPDATE.js +5 -0
  99. package/src/client/websocket/handlers/APPLICATION_COMMAND_UPDATE.js +20 -0
  100. package/src/client/websocket/handlers/AUTO_MODERATION_ACTION_EXECUTION.js +5 -0
  101. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_CREATE.js +5 -0
  102. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_DELETE.js +5 -0
  103. package/src/client/websocket/handlers/AUTO_MODERATION_RULE_UPDATE.js +5 -0
  104. package/src/client/websocket/handlers/CALL_CREATE.js +14 -0
  105. package/src/client/websocket/handlers/CALL_DELETE.js +11 -0
  106. package/src/client/websocket/handlers/CALL_UPDATE.js +11 -0
  107. package/src/client/websocket/handlers/CHANNEL_CREATE.js +5 -0
  108. package/src/client/websocket/handlers/CHANNEL_DELETE.js +5 -0
  109. package/src/client/websocket/handlers/CHANNEL_PINS_UPDATE.js +22 -0
  110. package/src/client/websocket/handlers/CHANNEL_RECIPIENT_ADD.js +19 -0
  111. package/src/client/websocket/handlers/CHANNEL_RECIPIENT_REMOVE.js +16 -0
  112. package/src/client/websocket/handlers/CHANNEL_UPDATE.js +16 -0
  113. package/src/client/websocket/handlers/GUILD_AUDIT_LOG_ENTRY_CREATE.js +5 -0
  114. package/src/client/websocket/handlers/GUILD_BAN_ADD.js +5 -0
  115. package/src/client/websocket/handlers/GUILD_BAN_REMOVE.js +5 -0
  116. package/src/client/websocket/handlers/GUILD_CREATE.js +51 -0
  117. package/src/client/websocket/handlers/GUILD_DELETE.js +5 -0
  118. package/src/client/websocket/handlers/GUILD_EMOJIS_UPDATE.js +5 -0
  119. package/src/client/websocket/handlers/GUILD_INTEGRATIONS_UPDATE.js +5 -0
  120. package/src/client/websocket/handlers/GUILD_MEMBERS_CHUNK.js +45 -0
  121. package/src/client/websocket/handlers/GUILD_MEMBER_ADD.js +20 -0
  122. package/src/client/websocket/handlers/GUILD_MEMBER_REMOVE.js +5 -0
  123. package/src/client/websocket/handlers/GUILD_MEMBER_UPDATE.js +5 -0
  124. package/src/client/websocket/handlers/GUILD_ROLE_CREATE.js +5 -0
  125. package/src/client/websocket/handlers/GUILD_ROLE_DELETE.js +5 -0
  126. package/src/client/websocket/handlers/GUILD_ROLE_UPDATE.js +5 -0
  127. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_CREATE.js +5 -0
  128. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_DELETE.js +5 -0
  129. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_UPDATE.js +5 -0
  130. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_USER_ADD.js +5 -0
  131. package/src/client/websocket/handlers/GUILD_SCHEDULED_EVENT_USER_REMOVE.js +5 -0
  132. package/src/client/websocket/handlers/GUILD_STICKERS_UPDATE.js +5 -0
  133. package/src/client/websocket/handlers/GUILD_UPDATE.js +5 -0
  134. package/src/client/websocket/handlers/INTERACTION_MODAL_CREATE.js +12 -0
  135. package/src/client/websocket/handlers/INVITE_CREATE.js +5 -0
  136. package/src/client/websocket/handlers/INVITE_DELETE.js +5 -0
  137. package/src/client/websocket/handlers/MESSAGE_CREATE.js +5 -0
  138. package/src/client/websocket/handlers/MESSAGE_DELETE.js +5 -0
  139. package/src/client/websocket/handlers/MESSAGE_DELETE_BULK.js +5 -0
  140. package/src/client/websocket/handlers/MESSAGE_POLL_VOTE_ADD.js +5 -0
  141. package/src/client/websocket/handlers/MESSAGE_POLL_VOTE_REMOVE.js +5 -0
  142. package/src/client/websocket/handlers/MESSAGE_REACTION_ADD.js +5 -0
  143. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE.js +5 -0
  144. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_ALL.js +5 -0
  145. package/src/client/websocket/handlers/MESSAGE_REACTION_REMOVE_EMOJI.js +5 -0
  146. package/src/client/websocket/handlers/MESSAGE_UPDATE.js +16 -0
  147. package/src/client/websocket/handlers/PRESENCE_UPDATE.js +5 -0
  148. package/src/client/websocket/handlers/READY.js +156 -0
  149. package/src/client/websocket/handlers/RELATIONSHIP_ADD.js +19 -0
  150. package/src/client/websocket/handlers/RELATIONSHIP_REMOVE.js +17 -0
  151. package/src/client/websocket/handlers/RELATIONSHIP_UPDATE.js +41 -0
  152. package/src/client/websocket/handlers/RESUMED.js +14 -0
  153. package/src/client/websocket/handlers/STAGE_INSTANCE_CREATE.js +5 -0
  154. package/src/client/websocket/handlers/STAGE_INSTANCE_DELETE.js +5 -0
  155. package/src/client/websocket/handlers/STAGE_INSTANCE_UPDATE.js +5 -0
  156. package/src/client/websocket/handlers/THREAD_CREATE.js +5 -0
  157. package/src/client/websocket/handlers/THREAD_DELETE.js +5 -0
  158. package/src/client/websocket/handlers/THREAD_LIST_SYNC.js +5 -0
  159. package/src/client/websocket/handlers/THREAD_MEMBERS_UPDATE.js +5 -0
  160. package/src/client/websocket/handlers/THREAD_MEMBER_UPDATE.js +5 -0
  161. package/src/client/websocket/handlers/THREAD_UPDATE.js +16 -0
  162. package/src/client/websocket/handlers/TYPING_START.js +5 -0
  163. package/src/client/websocket/handlers/USER_GUILD_SETTINGS_UPDATE.js +6 -0
  164. package/src/client/websocket/handlers/USER_NOTE_UPDATE.js +5 -0
  165. package/src/client/websocket/handlers/USER_REQUIRED_ACTION_UPDATE.js +82 -0
  166. package/src/client/websocket/handlers/USER_SETTINGS_UPDATE.js +5 -0
  167. package/src/client/websocket/handlers/USER_UPDATE.js +5 -0
  168. package/src/client/websocket/handlers/VOICE_CHANNEL_EFFECT_SEND.js +16 -0
  169. package/src/client/websocket/handlers/VOICE_CHANNEL_STATUS_UPDATE.js +12 -0
  170. package/src/client/websocket/handlers/VOICE_SERVER_UPDATE.js +12 -0
  171. package/src/client/websocket/handlers/VOICE_STATE_UPDATE.js +5 -0
  172. package/src/client/websocket/handlers/WEBHOOKS_UPDATE.js +5 -0
  173. package/src/client/websocket/handlers/index.js +84 -0
  174. package/src/errors/DJSError.js +61 -0
  175. package/src/errors/Messages.js +218 -0
  176. package/src/errors/index.js +4 -0
  177. package/src/index.js +172 -0
  178. package/src/managers/ApplicationCommandManager.js +264 -0
  179. package/src/managers/ApplicationCommandPermissionsManager.js +417 -0
  180. package/src/managers/AutoModerationRuleManager.js +296 -0
  181. package/src/managers/BaseGuildEmojiManager.js +80 -0
  182. package/src/managers/BaseManager.js +19 -0
  183. package/src/managers/BillingManager.js +66 -0
  184. package/src/managers/CachedManager.js +72 -0
  185. package/src/managers/ChannelManager.js +148 -0
  186. package/src/managers/ClientUserSettingManager.js +372 -0
  187. package/src/managers/DataManager.js +61 -0
  188. package/src/managers/DeveloperManager.js +265 -0
  189. package/src/managers/GuildBanManager.js +252 -0
  190. package/src/managers/GuildChannelManager.js +488 -0
  191. package/src/managers/GuildEmojiManager.js +171 -0
  192. package/src/managers/GuildEmojiRoleManager.js +118 -0
  193. package/src/managers/GuildForumThreadManager.js +108 -0
  194. package/src/managers/GuildInviteManager.js +213 -0
  195. package/src/managers/GuildManager.js +401 -0
  196. package/src/managers/GuildMemberManager.js +608 -0
  197. package/src/managers/GuildMemberRoleManager.js +195 -0
  198. package/src/managers/GuildScheduledEventManager.js +314 -0
  199. package/src/managers/GuildSettingManager.js +155 -0
  200. package/src/managers/GuildStickerManager.js +179 -0
  201. package/src/managers/GuildTextThreadManager.js +98 -0
  202. package/src/managers/InteractionManager.js +39 -0
  203. package/src/managers/MessageManager.js +457 -0
  204. package/src/managers/PermissionOverwriteManager.js +169 -0
  205. package/src/managers/PresenceManager.js +71 -0
  206. package/src/managers/QuestManager.js +391 -0
  207. package/src/managers/ReactionManager.js +67 -0
  208. package/src/managers/ReactionUserManager.js +73 -0
  209. package/src/managers/RelationshipManager.js +341 -0
  210. package/src/managers/RoleManager.js +448 -0
  211. package/src/managers/SessionManager.js +66 -0
  212. package/src/managers/StageInstanceManager.js +162 -0
  213. package/src/managers/ThreadManager.js +175 -0
  214. package/src/managers/ThreadMemberManager.js +186 -0
  215. package/src/managers/UserManager.js +274 -0
  216. package/src/managers/UserNoteManager.js +53 -0
  217. package/src/managers/VoiceStateManager.js +59 -0
  218. package/src/rest/APIRequest.js +198 -0
  219. package/src/rest/APIRouter.js +94 -0
  220. package/src/rest/DiscordAPIError.js +120 -0
  221. package/src/rest/HTTPError.js +62 -0
  222. package/src/rest/RESTManager.js +203 -0
  223. package/src/rest/RateLimitCoordinator.js +156 -0
  224. package/src/rest/RateLimitError.js +55 -0
  225. package/src/rest/RequestHandler.js +552 -0
  226. package/src/sharding/Shard.js +444 -0
  227. package/src/sharding/ShardClientUtil.js +279 -0
  228. package/src/sharding/ShardingManager.js +319 -0
  229. package/src/structures/AnonymousGuild.js +98 -0
  230. package/src/structures/ApplicationCommand.js +593 -0
  231. package/src/structures/ApplicationRoleConnectionMetadata.js +48 -0
  232. package/src/structures/AutoModerationActionExecution.js +89 -0
  233. package/src/structures/AutoModerationRule.js +294 -0
  234. package/src/structures/AutocompleteInteraction.js +107 -0
  235. package/src/structures/Base.js +43 -0
  236. package/src/structures/BaseCommandInteraction.js +211 -0
  237. package/src/structures/BaseGuild.js +124 -0
  238. package/src/structures/BaseGuildEmoji.js +56 -0
  239. package/src/structures/BaseGuildTextChannel.js +191 -0
  240. package/src/structures/BaseGuildVoiceChannel.js +241 -0
  241. package/src/structures/BaseMessageComponent.js +181 -0
  242. package/src/structures/ButtonInteraction.js +11 -0
  243. package/src/structures/CallState.js +63 -0
  244. package/src/structures/CategoryChannel.js +85 -0
  245. package/src/structures/Channel.js +284 -0
  246. package/src/structures/ClientPresence.js +77 -0
  247. package/src/structures/ClientUser.js +706 -0
  248. package/src/structures/CommandInteraction.js +41 -0
  249. package/src/structures/CommandInteractionOptionResolver.js +276 -0
  250. package/src/structures/ContainerComponent.js +68 -0
  251. package/src/structures/ContextMenuInteraction.js +65 -0
  252. package/src/structures/DMChannel.js +222 -0
  253. package/src/structures/DirectoryChannel.js +20 -0
  254. package/src/structures/Emoji.js +148 -0
  255. package/src/structures/FileComponent.js +49 -0
  256. package/src/structures/ForumChannel.js +31 -0
  257. package/src/structures/GroupDMChannel.js +415 -0
  258. package/src/structures/Guild.js +1804 -0
  259. package/src/structures/GuildAuditLogs.js +746 -0
  260. package/src/structures/GuildBan.js +59 -0
  261. package/src/structures/GuildBoost.js +108 -0
  262. package/src/structures/GuildChannel.js +470 -0
  263. package/src/structures/GuildEmoji.js +161 -0
  264. package/src/structures/GuildMember.js +636 -0
  265. package/src/structures/GuildPreview.js +191 -0
  266. package/src/structures/GuildPreviewEmoji.js +27 -0
  267. package/src/structures/GuildScheduledEvent.js +536 -0
  268. package/src/structures/GuildTemplate.js +236 -0
  269. package/src/structures/Integration.js +188 -0
  270. package/src/structures/IntegrationApplication.js +96 -0
  271. package/src/structures/Interaction.js +290 -0
  272. package/src/structures/InteractionCollector.js +248 -0
  273. package/src/structures/InteractionWebhook.js +43 -0
  274. package/src/structures/Invite.js +358 -0
  275. package/src/structures/InviteGuild.js +23 -0
  276. package/src/structures/InviteStageInstance.js +86 -0
  277. package/src/structures/MediaChannel.js +11 -0
  278. package/src/structures/MediaGalleryComponent.js +41 -0
  279. package/src/structures/MediaGalleryItem.js +47 -0
  280. package/src/structures/Message.js +1272 -0
  281. package/src/structures/MessageActionRow.js +105 -0
  282. package/src/structures/MessageAttachment.js +216 -0
  283. package/src/structures/MessageButton.js +166 -0
  284. package/src/structures/MessageCollector.js +146 -0
  285. package/src/structures/MessageComponentInteraction.js +120 -0
  286. package/src/structures/MessageContextMenuInteraction.js +20 -0
  287. package/src/structures/MessageEmbed.js +596 -0
  288. package/src/structures/MessageMentions.js +273 -0
  289. package/src/structures/MessagePayload.js +354 -0
  290. package/src/structures/MessageReaction.js +181 -0
  291. package/src/structures/MessageSelectMenu.js +141 -0
  292. package/src/structures/Modal.js +161 -0
  293. package/src/structures/ModalSubmitFieldsResolver.js +53 -0
  294. package/src/structures/ModalSubmitInteraction.js +119 -0
  295. package/src/structures/NewsChannel.js +32 -0
  296. package/src/structures/OAuth2Guild.js +28 -0
  297. package/src/structures/PermissionOverwrites.js +198 -0
  298. package/src/structures/Poll.js +108 -0
  299. package/src/structures/PollAnswer.js +88 -0
  300. package/src/structures/Presence.js +1165 -0
  301. package/src/structures/ReactionCollector.js +229 -0
  302. package/src/structures/ReactionEmoji.js +31 -0
  303. package/src/structures/Role.js +590 -0
  304. package/src/structures/SectionComponent.js +48 -0
  305. package/src/structures/SelectMenuInteraction.js +21 -0
  306. package/src/structures/SeparatorComponent.js +48 -0
  307. package/src/structures/Session.js +81 -0
  308. package/src/structures/StageChannel.js +104 -0
  309. package/src/structures/StageInstance.js +208 -0
  310. package/src/structures/Sticker.js +310 -0
  311. package/src/structures/StickerPack.js +95 -0
  312. package/src/structures/StoreChannel.js +56 -0
  313. package/src/structures/Team.js +118 -0
  314. package/src/structures/TeamMember.js +80 -0
  315. package/src/structures/TextChannel.js +33 -0
  316. package/src/structures/TextDisplayComponent.js +40 -0
  317. package/src/structures/TextInputComponent.js +132 -0
  318. package/src/structures/ThreadChannel.js +605 -0
  319. package/src/structures/ThreadMember.js +105 -0
  320. package/src/structures/ThreadOnlyChannel.js +249 -0
  321. package/src/structures/ThumbnailComponent.js +57 -0
  322. package/src/structures/Typing.js +74 -0
  323. package/src/structures/UnfurledMediaItem.js +29 -0
  324. package/src/structures/User.js +992 -0
  325. package/src/structures/UserContextMenuInteraction.js +29 -0
  326. package/src/structures/VoiceChannel.js +110 -0
  327. package/src/structures/VoiceChannelEffect.js +69 -0
  328. package/src/structures/VoiceRegion.js +53 -0
  329. package/src/structures/VoiceState.js +354 -0
  330. package/src/structures/WebEmbed.js +373 -0
  331. package/src/structures/Webhook.js +478 -0
  332. package/src/structures/WelcomeChannel.js +60 -0
  333. package/src/structures/WelcomeScreen.js +48 -0
  334. package/src/structures/Widget.js +87 -0
  335. package/src/structures/WidgetMember.js +100 -0
  336. package/src/structures/interfaces/Application.js +953 -0
  337. package/src/structures/interfaces/Collector.js +301 -0
  338. package/src/structures/interfaces/InteractionResponses.js +313 -0
  339. package/src/structures/interfaces/TextBasedChannel.js +821 -0
  340. package/src/util/APITypes.js +59 -0
  341. package/src/util/ActivityFlags.js +44 -0
  342. package/src/util/ApplicationFlags.js +76 -0
  343. package/src/util/AttachmentFlags.js +38 -0
  344. package/src/util/BitField.js +170 -0
  345. package/src/util/ChannelFlags.js +45 -0
  346. package/src/util/Constants.js +1953 -0
  347. package/src/util/DataResolver.js +162 -0
  348. package/src/util/FastQueue.js +93 -0
  349. package/src/util/FetchUtil.js +77 -0
  350. package/src/util/Formatters.js +228 -0
  351. package/src/util/GuildMemberFlags.js +43 -0
  352. package/src/util/Intents.js +74 -0
  353. package/src/util/InviteFlags.js +34 -0
  354. package/src/util/LimitedCollection.js +131 -0
  355. package/src/util/ListenerUtil.js +12 -0
  356. package/src/util/MessageFlags.js +63 -0
  357. package/src/util/Options.js +431 -0
  358. package/src/util/Permissions.js +202 -0
  359. package/src/util/PremiumUsageFlags.js +31 -0
  360. package/src/util/PurchasedFlags.js +33 -0
  361. package/src/util/RemoteAuth.js +425 -0
  362. package/src/util/RoleFlags.js +37 -0
  363. package/src/util/SnowflakeUtil.js +92 -0
  364. package/src/util/Speaking.js +33 -0
  365. package/src/util/Sweepers.js +493 -0
  366. package/src/util/SystemChannelFlags.js +55 -0
  367. package/src/util/ThreadMemberFlags.js +30 -0
  368. package/src/util/UserFlags.js +104 -0
  369. package/src/util/Util.js +1144 -0
  370. package/typings/enums.d.ts +437 -0
  371. package/typings/index.d.ts +8857 -0
  372. package/typings/index.test-d.ts +0 -0
  373. package/typings/rawDataTypes.d.ts +403 -0
@@ -0,0 +1,1144 @@
1
+ 'use strict';
2
+
3
+ const { Buffer } = require('node:buffer');
4
+ const { Agent } = require('node:http');
5
+ const { parse } = require('node:path');
6
+ const process = require('node:process');
7
+ const { setTimeout } = require('node:timers');
8
+ const { Collection } = require('@discordjs/collection');
9
+ const { Colors, Events } = require('./Constants');
10
+ const { getNativeFetch } = require('./FetchUtil');
11
+ const { Error: DiscordError, RangeError, TypeError } = require('../errors');
12
+ const has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
13
+ const isObject = d => typeof d === 'object' && d !== null;
14
+ const isWebReadableStream = value => value && typeof value.getReader === 'function';
15
+ const isNodeReadableStream = value => value && typeof value.pipe === 'function';
16
+
17
+ const fetch = getNativeFetch();
18
+
19
+ let deprecationEmittedForSplitMessage = false;
20
+ let deprecationEmittedForRemoveMentions = false;
21
+ let deprecationEmittedForResolveAutoArchiveMaxLimit = false;
22
+
23
+ const TextSortableGroupTypes = ['GUILD_TEXT', 'GUILD_ANNOUCMENT', 'GUILD_FORUM'];
24
+ const VoiceSortableGroupTypes = ['GUILD_VOICE', 'GUILD_STAGE_VOICE'];
25
+ const CategorySortableGroupTypes = ['GUILD_CATEGORY'];
26
+
27
+ const payloadTypes = [
28
+ {
29
+ name: 'opus',
30
+ type: 'audio',
31
+ priority: 1000,
32
+ payload_type: 120,
33
+ },
34
+ {
35
+ name: 'AV1',
36
+ type: 'video',
37
+ priority: 1000,
38
+ payload_type: 101,
39
+ rtx_payload_type: 102,
40
+ encode: false,
41
+ decode: false,
42
+ },
43
+ {
44
+ name: 'H265',
45
+ type: 'video',
46
+ priority: 2000,
47
+ payload_type: 103,
48
+ rtx_payload_type: 104,
49
+ encode: false,
50
+ decode: false,
51
+ },
52
+ {
53
+ name: 'H264',
54
+ type: 'video',
55
+ priority: 3000,
56
+ payload_type: 105,
57
+ rtx_payload_type: 106,
58
+ encode: true,
59
+ decode: true,
60
+ },
61
+ {
62
+ name: 'VP8',
63
+ type: 'video',
64
+ priority: 4000,
65
+ payload_type: 107,
66
+ rtx_payload_type: 108,
67
+ encode: true,
68
+ decode: false,
69
+ },
70
+ {
71
+ name: 'VP9',
72
+ type: 'video',
73
+ priority: 5000,
74
+ payload_type: 109,
75
+ rtx_payload_type: 110,
76
+ encode: false,
77
+ decode: false,
78
+ },
79
+ ];
80
+
81
+ const readWebReadableStream = async readableStream => {
82
+ const reader = readableStream.getReader();
83
+ const chunks = [];
84
+ let done = false;
85
+ while (!done) {
86
+ // eslint-disable-next-line no-await-in-loop
87
+ const readResult = await reader.read();
88
+ done = readResult.done;
89
+ if (done) break;
90
+ const { value } = readResult;
91
+ chunks.push(Buffer.from(value));
92
+ }
93
+ return Buffer.concat(chunks);
94
+ };
95
+
96
+ const readNodeReadableStream = async readableStream => {
97
+ const chunks = [];
98
+ for await (const chunk of readableStream) {
99
+ if (Buffer.isBuffer(chunk)) {
100
+ chunks.push(chunk);
101
+ continue;
102
+ }
103
+ if (chunk instanceof ArrayBuffer) {
104
+ chunks.push(Buffer.from(chunk));
105
+ continue;
106
+ }
107
+ if (ArrayBuffer.isView(chunk)) {
108
+ chunks.push(Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength));
109
+ continue;
110
+ }
111
+ chunks.push(Buffer.from(chunk));
112
+ }
113
+ return Buffer.concat(chunks);
114
+ };
115
+
116
+ /**
117
+ * Contains various general-purpose utility methods.
118
+ */
119
+ class Util extends null {
120
+ /**
121
+ * Flatten an object. Any properties that are collections will get converted to an array of keys.
122
+ * @param {Object} obj The object to flatten.
123
+ * @param {...Object<string, boolean|string>} [props] Specific properties to include/exclude.
124
+ * @returns {Object}
125
+ */
126
+ static flatten(obj, ...props) {
127
+ if (!isObject(obj)) return obj;
128
+
129
+ const objProps = Object.keys(obj)
130
+ .filter(k => !k.startsWith('_'))
131
+ .map(k => ({ [k]: true }));
132
+
133
+ props = objProps.length ? Object.assign(...objProps, ...props) : Object.assign({}, ...props);
134
+
135
+ const out = {};
136
+
137
+ for (let [prop, newProp] of Object.entries(props)) {
138
+ if (!newProp) continue;
139
+ newProp = newProp === true ? prop : newProp;
140
+
141
+ const element = obj[prop];
142
+ const elemIsObj = isObject(element);
143
+ const valueOf = elemIsObj && typeof element.valueOf === 'function' ? element.valueOf() : null;
144
+ const hasToJSON = elemIsObj && typeof element.toJSON === 'function';
145
+
146
+ // If it's a Collection, make the array of keys
147
+ if (element instanceof Collection) out[newProp] = Array.from(element.keys());
148
+ // If the valueOf is a Collection, use its array of keys
149
+ else if (valueOf instanceof Collection) out[newProp] = Array.from(valueOf.keys());
150
+ // If it's an array, call toJSON function on each element if present, otherwise flatten each element
151
+ else if (Array.isArray(element)) out[newProp] = element.map(e => e.toJSON?.() ?? Util.flatten(e));
152
+ // If it's an object with a primitive `valueOf`, use that value
153
+ else if (typeof valueOf !== 'object') out[newProp] = valueOf;
154
+ // If it's an object with a toJSON function, use the return value of it
155
+ else if (hasToJSON) out[newProp] = element.toJSON();
156
+ // If element is an object, use the flattened version of it
157
+ else if (typeof element === 'object') out[newProp] = Util.flatten(element);
158
+ // If it's a primitive
159
+ else if (!elemIsObj) out[newProp] = element;
160
+ }
161
+
162
+ return out;
163
+ }
164
+
165
+ /**
166
+ * Options for splitting a message.
167
+ * @typedef {Object} SplitOptions
168
+ * @property {number} [maxLength=2000] Maximum character length per message piece
169
+ * @property {string|string[]|RegExp|RegExp[]} [char='\n'] Character(s) or Regex(es) to split the message with,
170
+ * an array can be used to split multiple times
171
+ * @property {string} [prepend=''] Text to prepend to every piece except the first
172
+ * @property {string} [append=''] Text to append to every piece except the last
173
+ */
174
+
175
+ /**
176
+ * Splits a string into multiple chunks at a designated character that do not exceed a specific length.
177
+ * @param {string} text Content to split
178
+ * @param {SplitOptions} [options] Options controlling the behavior of the split
179
+ * @deprecated This will be removed in the next major version.
180
+ * @returns {string[]}
181
+ */
182
+ static splitMessage(text, { maxLength = 2_000, char = '\n', prepend = '', append = '' } = {}) {
183
+ if (!deprecationEmittedForSplitMessage) {
184
+ process.emitWarning(
185
+ 'The Util.splitMessage method is deprecated and will be removed in the next major version.',
186
+ 'DeprecationWarning',
187
+ );
188
+
189
+ deprecationEmittedForSplitMessage = true;
190
+ }
191
+
192
+ text = Util.verifyString(text);
193
+ if (text.length <= maxLength) return [text];
194
+ let splitText = [text];
195
+ if (Array.isArray(char)) {
196
+ while (char.length > 0 && splitText.some(elem => elem.length > maxLength)) {
197
+ const currentChar = char.shift();
198
+ if (currentChar instanceof RegExp) {
199
+ splitText = splitText.flatMap(chunk => chunk.match(currentChar));
200
+ } else {
201
+ splitText = splitText.flatMap(chunk => chunk.split(currentChar));
202
+ }
203
+ }
204
+ } else {
205
+ splitText = text.split(char);
206
+ }
207
+ if (splitText.some(elem => elem.length > maxLength)) throw new RangeError('SPLIT_MAX_LEN');
208
+ const messages = [];
209
+ let msg = '';
210
+ for (const chunk of splitText) {
211
+ if (msg && (msg + char + chunk + append).length > maxLength) {
212
+ messages.push(msg + append);
213
+ msg = prepend;
214
+ }
215
+ msg += (msg && msg !== prepend ? char : '') + chunk;
216
+ }
217
+ return messages.concat(msg).filter(m => m);
218
+ }
219
+
220
+ /**
221
+ * Options used to escape markdown.
222
+ * @typedef {Object} EscapeMarkdownOptions
223
+ * @property {boolean} [codeBlock=true] Whether to escape code blocks
224
+ * @property {boolean} [inlineCode=true] Whether to escape inline code
225
+ * @property {boolean} [bold=true] Whether to escape bolds
226
+ * @property {boolean} [italic=true] Whether to escape italics
227
+ * @property {boolean} [underline=true] Whether to escape underlines
228
+ * @property {boolean} [strikethrough=true] Whether to escape strikethroughs
229
+ * @property {boolean} [spoiler=true] Whether to escape spoilers
230
+ * @property {boolean} [codeBlockContent=true] Whether to escape text inside code blocks
231
+ * @property {boolean} [inlineCodeContent=true] Whether to escape text inside inline code
232
+ * @property {boolean} [escape=true] Whether to escape escape characters
233
+ * @property {boolean} [heading=false] Whether to escape headings
234
+ * @property {boolean} [bulletedList=false] Whether to escape bulleted lists
235
+ * @property {boolean} [numberedList=false] Whether to escape numbered lists
236
+ * @property {boolean} [maskedLink=false] Whether to escape masked links
237
+ */
238
+
239
+ /**
240
+ * Escapes any Discord-flavour markdown in a string.
241
+ * @param {string} text Content to escape
242
+ * @param {EscapeMarkdownOptions} [options={}] Options for escaping the markdown
243
+ * @returns {string}
244
+ */
245
+ static escapeMarkdown(
246
+ text,
247
+ {
248
+ codeBlock = true,
249
+ inlineCode = true,
250
+ bold = true,
251
+ italic = true,
252
+ underline = true,
253
+ strikethrough = true,
254
+ spoiler = true,
255
+ codeBlockContent = true,
256
+ inlineCodeContent = true,
257
+ escape = true,
258
+ heading = false,
259
+ bulletedList = false,
260
+ numberedList = false,
261
+ maskedLink = false,
262
+ } = {},
263
+ ) {
264
+ if (!codeBlockContent) {
265
+ return text
266
+ .split('```')
267
+ .map((subString, index, array) => {
268
+ if (index % 2 && index !== array.length - 1) return subString;
269
+ return Util.escapeMarkdown(subString, {
270
+ inlineCode,
271
+ bold,
272
+ italic,
273
+ underline,
274
+ strikethrough,
275
+ spoiler,
276
+ inlineCodeContent,
277
+ escape,
278
+ heading,
279
+ bulletedList,
280
+ numberedList,
281
+ maskedLink,
282
+ });
283
+ })
284
+ .join(codeBlock ? '\\`\\`\\`' : '```');
285
+ }
286
+ if (!inlineCodeContent) {
287
+ return text
288
+ .split(/(?<=^|[^`])`(?=[^`]|$)/g)
289
+ .map((subString, index, array) => {
290
+ if (index % 2 && index !== array.length - 1) return subString;
291
+ return Util.escapeMarkdown(subString, {
292
+ codeBlock,
293
+ bold,
294
+ italic,
295
+ underline,
296
+ strikethrough,
297
+ spoiler,
298
+ escape,
299
+ heading,
300
+ bulletedList,
301
+ numberedList,
302
+ maskedLink,
303
+ });
304
+ })
305
+ .join(inlineCode ? '\\`' : '`');
306
+ }
307
+ if (escape) text = Util.escapeEscape(text);
308
+ if (inlineCode) text = Util.escapeInlineCode(text);
309
+ if (codeBlock) text = Util.escapeCodeBlock(text);
310
+ if (italic) text = Util.escapeItalic(text);
311
+ if (bold) text = Util.escapeBold(text);
312
+ if (underline) text = Util.escapeUnderline(text);
313
+ if (strikethrough) text = Util.escapeStrikethrough(text);
314
+ if (spoiler) text = Util.escapeSpoiler(text);
315
+ if (heading) text = Util.escapeHeading(text);
316
+ if (bulletedList) text = Util.escapeBulletedList(text);
317
+ if (numberedList) text = Util.escapeNumberedList(text);
318
+ if (maskedLink) text = Util.escapeMaskedLink(text);
319
+ return text;
320
+ }
321
+
322
+ /**
323
+ * Escapes code block markdown in a string.
324
+ * @param {string} text Content to escape
325
+ * @returns {string}
326
+ */
327
+ static escapeCodeBlock(text) {
328
+ return text.replaceAll('```', '\\`\\`\\`');
329
+ }
330
+
331
+ /**
332
+ * Escapes inline code markdown in a string.
333
+ * @param {string} text Content to escape
334
+ * @returns {string}
335
+ */
336
+ static escapeInlineCode(text) {
337
+ return text.replace(/(?<=^|[^`])``?(?=[^`]|$)/g, match => (match.length === 2 ? '\\`\\`' : '\\`'));
338
+ }
339
+
340
+ /**
341
+ * Escapes italic markdown in a string.
342
+ * @param {string} text Content to escape
343
+ * @returns {string}
344
+ */
345
+ static escapeItalic(text) {
346
+ let i = 0;
347
+ text = text.replace(/(?<=^|[^*])\*([^*]|\*\*|$)/g, (_, match) => {
348
+ if (match === '**') return ++i % 2 ? `\\*${match}` : `${match}\\*`;
349
+ return `\\*${match}`;
350
+ });
351
+ i = 0;
352
+ return text.replace(/(?<=^|[^_])_([^_]|__|$)/g, (_, match) => {
353
+ if (match === '__') return ++i % 2 ? `\\_${match}` : `${match}\\_`;
354
+ return `\\_${match}`;
355
+ });
356
+ }
357
+
358
+ /**
359
+ * Escapes bold markdown in a string.
360
+ * @param {string} text Content to escape
361
+ * @returns {string}
362
+ */
363
+ static escapeBold(text) {
364
+ let i = 0;
365
+ return text.replace(/\*\*(\*)?/g, (_, match) => {
366
+ if (match) return ++i % 2 ? `${match}\\*\\*` : `\\*\\*${match}`;
367
+ return '\\*\\*';
368
+ });
369
+ }
370
+
371
+ /**
372
+ * Escapes underline markdown in a string.
373
+ * @param {string} text Content to escape
374
+ * @returns {string}
375
+ */
376
+ static escapeUnderline(text) {
377
+ let i = 0;
378
+ return text.replace(/__(_)?/g, (_, match) => {
379
+ if (match) return ++i % 2 ? `${match}\\_\\_` : `\\_\\_${match}`;
380
+ return '\\_\\_';
381
+ });
382
+ }
383
+
384
+ /**
385
+ * Escapes strikethrough markdown in a string.
386
+ * @param {string} text Content to escape
387
+ * @returns {string}
388
+ */
389
+ static escapeStrikethrough(text) {
390
+ return text.replaceAll('~~', '\\~\\~');
391
+ }
392
+
393
+ /**
394
+ * Escapes spoiler markdown in a string.
395
+ * @param {string} text Content to escape
396
+ * @returns {string}
397
+ */
398
+ static escapeSpoiler(text) {
399
+ return text.replaceAll('||', '\\|\\|');
400
+ }
401
+
402
+ /**
403
+ * Escapes escape characters in a string.
404
+ * @param {string} text Content to escape
405
+ * @returns {string}
406
+ */
407
+ static escapeEscape(text) {
408
+ return text.replaceAll('\\', '\\\\');
409
+ }
410
+
411
+ /**
412
+ * Escapes heading characters in a string.
413
+ * @param {string} text Content to escape
414
+ * @returns {string}
415
+ */
416
+ static escapeHeading(text) {
417
+ return text.replaceAll(/^( {0,2}[*-] +)?(#{1,3} )/gm, '$1\\$2');
418
+ }
419
+
420
+ /**
421
+ * Escapes bulleted list characters in a string.
422
+ * @param {string} text Content to escape
423
+ * @returns {string}
424
+ */
425
+ static escapeBulletedList(text) {
426
+ return text.replaceAll(/^( *)[*-]( +)/gm, '$1\\-$2');
427
+ }
428
+
429
+ /**
430
+ * Escapes numbered list characters in a string.
431
+ * @param {string} text Content to escape
432
+ * @returns {string}
433
+ */
434
+ static escapeNumberedList(text) {
435
+ return text.replaceAll(/^( *\d+)\./gm, '$1\\.');
436
+ }
437
+
438
+ /**
439
+ * Escapes masked link characters in a string.
440
+ * @param {string} text Content to escape
441
+ * @returns {string}
442
+ */
443
+ static escapeMaskedLink(text) {
444
+ return text.replaceAll(/\[.+\]\(.+\)/gm, '\\$&');
445
+ }
446
+
447
+ /**
448
+ * @typedef {Object} FetchRecommendedShardsOptions
449
+ * @property {number} [guildsPerShard=1000] Number of guilds assigned per shard
450
+ * @property {number} [multipleOf=1] The multiple the shard count should round up to. (16 for large bot sharding)
451
+ */
452
+
453
+ static fetchRecommendedShards() {
454
+ throw new DiscordError('INVALID_USER_API');
455
+ }
456
+
457
+ /**
458
+ * Parses emoji info out of a string. The string must be one of:
459
+ * * A UTF-8 emoji (no id)
460
+ * * A URL-encoded UTF-8 emoji (no id)
461
+ * * A Discord custom emoji (`<:name:id>` or `<a:name:id>`)
462
+ * @param {string} text Emoji string to parse
463
+ * @returns {APIEmoji} Object with `animated`, `name`, and `id` properties
464
+ * @private
465
+ */
466
+ static parseEmoji(text) {
467
+ if (text.includes('%')) text = decodeURIComponent(text);
468
+ if (!text.includes(':')) return { animated: false, name: text, id: null };
469
+ const match = text.match(/<?(?:(a):)?(\w{2,32}):(\d{17,19})?>?/);
470
+ return match && { animated: Boolean(match[1]), name: match[2], id: match[3] ?? null };
471
+ }
472
+
473
+ /**
474
+ * Resolves a partial emoji object from an {@link EmojiIdentifierResolvable}, without checking a Client.
475
+ * @param {EmojiIdentifierResolvable} emoji Emoji identifier to resolve
476
+ * @returns {?RawEmoji}
477
+ * @private
478
+ */
479
+ static resolvePartialEmoji(emoji) {
480
+ if (!emoji) return null;
481
+ if (typeof emoji === 'string') return /^\d{17,19}$/.test(emoji) ? { id: emoji } : Util.parseEmoji(emoji);
482
+ const { id, name, animated } = emoji;
483
+ if (!id && !name) return null;
484
+ return { id, name, animated: Boolean(animated) };
485
+ }
486
+
487
+ /**
488
+ * Shallow-copies an object with its class/prototype intact.
489
+ * @param {Object} obj Object to clone
490
+ * @returns {Object}
491
+ * @private
492
+ */
493
+ static cloneObject(obj) {
494
+ return Object.assign(Object.create(obj), obj);
495
+ }
496
+
497
+ /**
498
+ * Sets default properties on an object that aren't already specified.
499
+ * @param {Object} def Default properties
500
+ * @param {Object} given Object to assign defaults to
501
+ * @returns {Object}
502
+ * @private
503
+ */
504
+ static mergeDefault(def, given) {
505
+ if (!given) return def;
506
+ for (const key in def) {
507
+ if (!has(given, key) || given[key] === undefined) {
508
+ given[key] = def[key];
509
+ } else if (given[key] === Object(given[key])) {
510
+ given[key] = Util.mergeDefault(def[key], given[key]);
511
+ }
512
+ }
513
+
514
+ return given;
515
+ }
516
+
517
+ /**
518
+ * Options used to make an error object.
519
+ * @typedef {Object} MakeErrorOptions
520
+ * @property {string} name Error type
521
+ * @property {string} message Message for the error
522
+ * @property {string} stack Stack for the error
523
+ */
524
+
525
+ /**
526
+ * Makes an Error from a plain info object.
527
+ * @param {MakeErrorOptions} obj Error info
528
+ * @returns {Error}
529
+ * @private
530
+ */
531
+ static makeError(obj) {
532
+ const err = new Error(obj.message);
533
+ err.name = obj.name;
534
+ err.stack = obj.stack;
535
+ return err;
536
+ }
537
+
538
+ /**
539
+ * Makes a plain error info object from an Error.
540
+ * @param {Error} err Error to get info from
541
+ * @returns {MakeErrorOptions}
542
+ * @private
543
+ */
544
+ static makePlainError(err) {
545
+ return {
546
+ name: err.name,
547
+ message: err.message,
548
+ stack: err.stack,
549
+ };
550
+ }
551
+
552
+ /**
553
+ * Moves an element in an array *in place*.
554
+ * @param {Array<*>} array Array to modify
555
+ * @param {*} element Element to move
556
+ * @param {number} newIndex Index or offset to move the element to
557
+ * @param {boolean} [offset=false] Move the element by an offset amount rather than to a set index
558
+ * @returns {number}
559
+ * @private
560
+ */
561
+ static moveElementInArray(array, element, newIndex, offset = false) {
562
+ const index = array.indexOf(element);
563
+ newIndex = (offset ? index : 0) + newIndex;
564
+ if (newIndex > -1 && newIndex < array.length) {
565
+ const removedElement = array.splice(index, 1)[0];
566
+ array.splice(newIndex, 0, removedElement);
567
+ }
568
+ return array.indexOf(element);
569
+ }
570
+
571
+ /**
572
+ * Verifies the provided data is a string, otherwise throws provided error.
573
+ * @param {string} data The string resolvable to resolve
574
+ * @param {Function} [error] The Error constructor to instantiate. Defaults to Error
575
+ * @param {string} [errorMessage] The error message to throw with. Defaults to "Expected string, got <data> instead."
576
+ * @param {boolean} [allowEmpty=true] Whether an empty string should be allowed
577
+ * @returns {string}
578
+ */
579
+ static verifyString(
580
+ data,
581
+ error = Error,
582
+ errorMessage = `Expected a string, got ${data} instead.`,
583
+ allowEmpty = true,
584
+ ) {
585
+ if (typeof data !== 'string') throw new error(errorMessage);
586
+ if (!allowEmpty && data.length === 0) throw new error(errorMessage);
587
+ return data;
588
+ }
589
+
590
+ /**
591
+ * Can be a number, hex string, a {@link Color}, or an RGB array like:
592
+ * ```js
593
+ * [255, 0, 255] // purple
594
+ * ```
595
+ * @typedef {string|Color|number|number[]} ColorResolvable
596
+ */
597
+
598
+ /**
599
+ * Resolves a ColorResolvable into a color number.
600
+ * @param {ColorResolvable} color Color to resolve
601
+ * @returns {number} A color
602
+ */
603
+ static resolveColor(color) {
604
+ if (typeof color === 'string') {
605
+ if (color === 'RANDOM') return Math.floor(Math.random() * (0xffffff + 1));
606
+ if (color === 'DEFAULT') return 0;
607
+ color = Colors[color] ?? parseInt(color.replace('#', ''), 16);
608
+ } else if (Array.isArray(color)) {
609
+ color = (color[0] << 16) + (color[1] << 8) + color[2];
610
+ }
611
+
612
+ if (color < 0 || color > 0xffffff) throw new RangeError('COLOR_RANGE');
613
+ else if (Number.isNaN(color)) throw new TypeError('COLOR_CONVERT');
614
+
615
+ return color;
616
+ }
617
+
618
+ /**
619
+ * Sorts by Discord's position and id.
620
+ * @param {Collection} collection Collection of objects to sort
621
+ * @returns {Collection}
622
+ */
623
+ static discordSort(collection) {
624
+ const isGuildChannel = collection.first() instanceof GuildChannel;
625
+ return collection.toSorted(
626
+ isGuildChannel
627
+ ? (a, b) => a.rawPosition - b.rawPosition || Number(BigInt(a.id) - BigInt(b.id))
628
+ : (a, b) => a.rawPosition - b.rawPosition || Number(BigInt(b.id) - BigInt(a.id)),
629
+ );
630
+ }
631
+
632
+ /**
633
+ * Sets the position of a Channel or Role.
634
+ * @param {Channel|Role} item Object to set the position of
635
+ * @param {number} position New position for the object
636
+ * @param {boolean} relative Whether `position` is relative to its current position
637
+ * @param {Collection<string, Channel|Role>} sorted A collection of the objects sorted properly
638
+ * @param {APIRouter} route Route to call PATCH on
639
+ * @param {string} [reason] Reason for the change
640
+ * @returns {Promise<Channel[]|Role[]>} Updated item list, with `id` and `position` properties
641
+ * @private
642
+ */
643
+ static async setPosition(item, position, relative, sorted, route, reason) {
644
+ let updatedItems = [...sorted.values()];
645
+ Util.moveElementInArray(updatedItems, item, position, relative);
646
+ updatedItems = updatedItems.map((r, i) => ({ id: r.id, position: i }));
647
+ await route.patch({ data: updatedItems, reason });
648
+ return updatedItems;
649
+ }
650
+
651
+ /**
652
+ * Alternative to Node's `path.basename`, removing query string after the extension if it exists.
653
+ * @param {string} path Path to get the basename of
654
+ * @param {string} [ext] File extension to remove
655
+ * @returns {string} Basename of the path
656
+ * @private
657
+ */
658
+ static basename(path, ext) {
659
+ const res = parse(path);
660
+ return ext && res.ext.startsWith(ext) ? res.name : res.base.split('?')[0];
661
+ }
662
+
663
+ /**
664
+ * Breaks user, role and everyone/here mentions by adding a zero width space after every @ character
665
+ * @param {string} str The string to sanitize
666
+ * @returns {string}
667
+ * @deprecated Use {@link BaseMessageOptions#allowedMentions} instead.
668
+ */
669
+ static removeMentions(str) {
670
+ if (!deprecationEmittedForRemoveMentions) {
671
+ process.emitWarning(
672
+ 'The Util.removeMentions method is deprecated. Use MessageOptions#allowedMentions instead.',
673
+ 'DeprecationWarning',
674
+ );
675
+
676
+ deprecationEmittedForRemoveMentions = true;
677
+ }
678
+
679
+ return Util._removeMentions(str);
680
+ }
681
+
682
+ static _removeMentions(str) {
683
+ return str.replaceAll('@', '@\u200b');
684
+ }
685
+
686
+ /**
687
+ * The content to have all mentions replaced by the equivalent text.
688
+ * <warn>When {@link Util.removeMentions} is removed, this method will no longer sanitize mentions.
689
+ * Use {@link BaseMessageOptions#allowedMentions} instead to prevent mentions when sending a message.</warn>
690
+ * @param {string} str The string to be converted
691
+ * @param {TextBasedChannels} channel The channel the string was sent in
692
+ * @returns {string}
693
+ */
694
+ static cleanContent(str, channel) {
695
+ str = str
696
+ .replace(/<@!?[0-9]+>/g, input => {
697
+ const id = input.replace(/<|!|>|@/g, '');
698
+ if (channel.type === 'DM') {
699
+ const user = channel.client.users.cache.get(id);
700
+ return user ? Util._removeMentions(`@${user.username}`) : input;
701
+ }
702
+
703
+ const member = channel.guild?.members.cache.get(id);
704
+ if (member) {
705
+ return Util._removeMentions(`@${member.displayName}`);
706
+ } else {
707
+ const user = channel.client.users.cache.get(id);
708
+ return user ? Util._removeMentions(`@${user.username}`) : input;
709
+ }
710
+ })
711
+ .replace(/<#[0-9]+>/g, input => {
712
+ const mentionedChannel = channel.client.channels.cache.get(input.replace(/<|#|>/g, ''));
713
+ return mentionedChannel ? `#${mentionedChannel.name}` : input;
714
+ })
715
+ .replace(/<@&[0-9]+>/g, input => {
716
+ if (channel.type === 'DM') return input;
717
+ const role = channel.guild.roles.cache.get(input.replace(/<|@|>|&/g, ''));
718
+ return role ? `@${role.name}` : input;
719
+ });
720
+ return str;
721
+ }
722
+
723
+ /**
724
+ * The content to put in a code block with all code block fences replaced by the equivalent backticks.
725
+ * @param {string} text The string to be converted
726
+ * @returns {string}
727
+ */
728
+ static cleanCodeBlockContent(text) {
729
+ return text.replaceAll('```', '`\u200b``');
730
+ }
731
+
732
+ /**
733
+ * Creates a sweep filter that sweeps archived threads
734
+ * @param {number} [lifetime=14400] How long a thread has to be archived to be valid for sweeping
735
+ * @deprecated When not using with `makeCache` use `Sweepers.archivedThreadSweepFilter` instead
736
+ * @returns {SweepFilter}
737
+ */
738
+ static archivedThreadSweepFilter(lifetime = 14400) {
739
+ const filter = require('./Sweepers').archivedThreadSweepFilter(lifetime);
740
+ filter.isDefault = true;
741
+ return filter;
742
+ }
743
+
744
+ /**
745
+ * Resolves the maximum time a guild's thread channels should automatically archive in case of no recent activity.
746
+ * @param {Guild} guild The guild to resolve this limit from.
747
+ * @deprecated This will be removed in the next major version.
748
+ * @returns {number}
749
+ */
750
+ static resolveAutoArchiveMaxLimit() {
751
+ if (!deprecationEmittedForResolveAutoArchiveMaxLimit) {
752
+ process.emitWarning(
753
+ // eslint-disable-next-line max-len
754
+ "The Util.resolveAutoArchiveMaxLimit method and the 'MAX' option are deprecated and will be removed in the next major version.",
755
+ 'DeprecationWarning',
756
+ );
757
+ deprecationEmittedForResolveAutoArchiveMaxLimit = true;
758
+ }
759
+ return 10080;
760
+ }
761
+
762
+ /**
763
+ * Transforms an API guild forum tag to camel-cased guild forum tag.
764
+ * @param {APIGuildForumTag} tag The tag to transform
765
+ * @returns {GuildForumTag}
766
+ * @ignore
767
+ */
768
+ static transformAPIGuildForumTag(tag) {
769
+ return {
770
+ id: tag.id,
771
+ name: tag.name,
772
+ moderated: tag.moderated,
773
+ emoji:
774
+ tag.emoji_id ?? tag.emoji_name
775
+ ? {
776
+ id: tag.emoji_id,
777
+ name: tag.emoji_name,
778
+ }
779
+ : null,
780
+ };
781
+ }
782
+
783
+ /**
784
+ * Transforms a camel-cased guild forum tag to an API guild forum tag.
785
+ * @param {GuildForumTag} tag The tag to transform
786
+ * @returns {APIGuildForumTag}
787
+ * @ignore
788
+ */
789
+ static transformGuildForumTag(tag) {
790
+ return {
791
+ id: tag.id,
792
+ name: tag.name,
793
+ moderated: tag.moderated,
794
+ emoji_id: tag.emoji?.id ?? null,
795
+ emoji_name: tag.emoji?.name ?? null,
796
+ };
797
+ }
798
+
799
+ /**
800
+ * Transforms an API guild forum default reaction object to a
801
+ * camel-cased guild forum default reaction object.
802
+ * @param {APIGuildForumDefaultReactionEmoji} defaultReaction The default reaction to transform
803
+ * @returns {DefaultReactionEmoji}
804
+ * @ignore
805
+ */
806
+ static transformAPIGuildDefaultReaction(defaultReaction) {
807
+ return {
808
+ id: defaultReaction.emoji_id,
809
+ name: defaultReaction.emoji_name,
810
+ };
811
+ }
812
+
813
+ /**
814
+ * Transforms a camel-cased guild forum default reaction object to an
815
+ * API guild forum default reaction object.
816
+ * @param {DefaultReactionEmoji} defaultReaction The default reaction to transform
817
+ * @returns {APIGuildForumDefaultReactionEmoji}
818
+ * @ignore
819
+ */
820
+ static transformGuildDefaultReaction(defaultReaction) {
821
+ return {
822
+ emoji_id: defaultReaction.id,
823
+ emoji_name: defaultReaction.name,
824
+ };
825
+ }
826
+
827
+ /**
828
+ * Transforms a guild scheduled event recurrence rule object to a snake-cased variant.
829
+ * @param {GuildScheduledEventRecurrenceRuleOptions} recurrenceRule The recurrence rule to transform
830
+ * @returns {APIGuildScheduledEventRecurrenceRule}
831
+ * @ignore
832
+ */
833
+ static transformGuildScheduledEventRecurrenceRule(recurrenceRule) {
834
+ return {
835
+ start: new Date(recurrenceRule.startAt).toISOString(),
836
+ frequency: recurrenceRule.frequency,
837
+ interval: recurrenceRule.interval,
838
+ by_weekday: recurrenceRule.byWeekday,
839
+ by_n_weekday: recurrenceRule.byNWeekday,
840
+ by_month: recurrenceRule.byMonth,
841
+ by_month_day: recurrenceRule.byMonthDay,
842
+ };
843
+ }
844
+
845
+ /**
846
+ * Transforms API incidents data to a camel-cased variant.
847
+ * @param {APIIncidentsData} data The incidents data to transform
848
+ * @returns {IncidentActions}
849
+ * @ignore
850
+ */
851
+ static transformAPIIncidentsData(data) {
852
+ return {
853
+ invitesDisabledUntil: data.invites_disabled_until ? new Date(data.invites_disabled_until) : null,
854
+ dmsDisabledUntil: data.dms_disabled_until ? new Date(data.dms_disabled_until) : null,
855
+ dmSpamDetectedAt: data.dm_spam_detected_at ? new Date(data.dm_spam_detected_at) : null,
856
+ raidDetectedAt: data.raid_detected_at ? new Date(data.raid_detected_at) : null,
857
+ };
858
+ }
859
+
860
+ /**
861
+ * Gets an array of the channel types that can be moved in the channel group. For example, a GuildText channel would
862
+ * return an array containing the types that can be ordered within the text channels (always at the top), and a voice
863
+ * channel would return an array containing the types that can be ordered within the voice channels (always at the
864
+ * bottom).
865
+ * @param {ChannelType} type The type of the channel
866
+ * @returns {ChannelType[]}
867
+ * @ignore
868
+ */
869
+ static getSortableGroupTypes(type) {
870
+ switch (type) {
871
+ case 'GUILD_TEXT':
872
+ case 'GUILD_ANNOUNCEMENT':
873
+ case 'GUILD_FORUM':
874
+ return TextSortableGroupTypes;
875
+ case 'GUILD_VOICE':
876
+ case 'GUILD_STAGE_VOICE':
877
+ return VoiceSortableGroupTypes;
878
+ case 'GUILD_CATEGORY':
879
+ return CategorySortableGroupTypes;
880
+ default:
881
+ return [type];
882
+ }
883
+ }
884
+
885
+ /**
886
+ * Calculates the default avatar index for a given user id.
887
+ * @param {Snowflake} userId - The user id to calculate the default avatar index for
888
+ * @returns {number}
889
+ */
890
+ static calculateUserDefaultAvatarIndex(userId) {
891
+ return Number(BigInt(userId) >> 22n) % 6;
892
+ }
893
+
894
+ static _resolveKnownUploadSize(data) {
895
+ if (Buffer.isBuffer(data)) return data.byteLength;
896
+ if (typeof data === 'string') return Buffer.byteLength(data);
897
+ if (data instanceof ArrayBuffer) return data.byteLength;
898
+ if (ArrayBuffer.isView(data)) return data.byteLength;
899
+ if (typeof Blob !== 'undefined' && data instanceof Blob) return data.size;
900
+ if (typeof data?.size === 'number') return data.size;
901
+ if (typeof data?.byteLength === 'number') return data.byteLength;
902
+ return null;
903
+ }
904
+
905
+ static async _resolveUploadDataAndSize(data) {
906
+ const knownSize = Util._resolveKnownUploadSize(data);
907
+ if (knownSize !== null) return { data, size: knownSize };
908
+
909
+ if (typeof data?.arrayBuffer === 'function') {
910
+ const buffer = Buffer.from(await data.arrayBuffer());
911
+ return { data: buffer, size: buffer.byteLength };
912
+ }
913
+
914
+ if (isWebReadableStream(data)) {
915
+ const buffer = await readWebReadableStream(data);
916
+ return { data: buffer, size: buffer.byteLength };
917
+ }
918
+
919
+ if (isNodeReadableStream(data)) {
920
+ const buffer = await readNodeReadableStream(data);
921
+ return { data: buffer, size: buffer.byteLength };
922
+ }
923
+
924
+ throw new TypeError(
925
+ 'INVALID_TYPE',
926
+ 'file',
927
+ 'Buffer, string, ArrayBuffer, TypedArray, Blob, File, BunFile, or readable stream',
928
+ true,
929
+ );
930
+ }
931
+
932
+ static async getUploadURL(client, channelId, files) {
933
+ if (!files.length) return [];
934
+
935
+ const payloadFiles = [];
936
+ for (const [index, file] of files.entries()) {
937
+ // eslint-disable-next-line no-await-in-loop
938
+ const resolved = await Util._resolveUploadDataAndSize(file.file);
939
+ file.file = resolved.data;
940
+ payloadFiles.push({
941
+ filename: file.name,
942
+ file_size: resolved.size,
943
+ id: `${index}`,
944
+ });
945
+ }
946
+
947
+ const { attachments } = await client.api.channels[channelId].attachments.post({
948
+ data: {
949
+ files: payloadFiles,
950
+ },
951
+ });
952
+ return attachments;
953
+ }
954
+
955
+ static async uploadFile(data, url) {
956
+ const response = await fetch(url, {
957
+ method: 'PUT',
958
+ body: data,
959
+ duplex: 'half', // Node.js v20
960
+ });
961
+ if (!response.ok) throw response;
962
+ return response;
963
+ }
964
+
965
+ /**
966
+ * Lazily evaluates a callback function (yea it's v14 :yay:)
967
+ * @param {Function} cb The callback to lazily evaluate
968
+ * @returns {Function}
969
+ * @example
970
+ * const User = lazy(() => require('./User'));
971
+ * const user = new (User())(client, data);
972
+ */
973
+ static lazy(cb) {
974
+ let defaultValue;
975
+ return () => (defaultValue ??= cb());
976
+ }
977
+
978
+ /**
979
+ * Hacking check object instanceof Proxy-agent
980
+ * @param {Object} object any
981
+ * @returns {boolean}
982
+ */
983
+ static verifyProxyAgent(object) {
984
+ return typeof object == 'object' && object.httpAgent instanceof Agent && object.httpsAgent instanceof Agent;
985
+ }
986
+
987
+ static checkUndiciProxyAgent(data) {
988
+ if (typeof data === 'string') {
989
+ return {
990
+ uri: data,
991
+ };
992
+ }
993
+ if (data instanceof URL) {
994
+ return {
995
+ uri: data.toString(),
996
+ };
997
+ }
998
+ if (typeof data === 'object') {
999
+ if (typeof data.uri === 'string') return data;
1000
+ if (typeof data.url === 'string') {
1001
+ return {
1002
+ uri: data.url,
1003
+ headers: data.headers,
1004
+ };
1005
+ }
1006
+ }
1007
+ return false;
1008
+ }
1009
+
1010
+ static createPromiseInteraction(client, nonce, timeoutMs = 5_000, isHandlerDeferUpdate = false, parent) {
1011
+ return new Promise((resolve, reject) => {
1012
+ let dataFromInteractionSuccess;
1013
+ let dataFromNormalEvent;
1014
+ let finished = false;
1015
+ const removeListeners = () => {
1016
+ client.removeListener(Events.MESSAGE_CREATE, handler);
1017
+ client.removeListener(Events.INTERACTION_MODAL_CREATE, handler);
1018
+ if (isHandlerDeferUpdate) client.removeListener(Events.UNHANDLED_PACKET, handler);
1019
+ };
1020
+
1021
+ const finalize = data => {
1022
+ if (finished) return;
1023
+ finished = true;
1024
+ clearTimeout(timeout);
1025
+ removeListeners();
1026
+ client.decrementMaxListeners();
1027
+ resolve(data);
1028
+ };
1029
+
1030
+ const fail = () => {
1031
+ if (finished) return;
1032
+ finished = true;
1033
+ removeListeners();
1034
+ client.decrementMaxListeners();
1035
+ reject(new DiscordError('INTERACTION_FAILED'));
1036
+ };
1037
+ const handler = data => {
1038
+ // UnhandledPacket
1039
+ if (isHandlerDeferUpdate && data.d?.nonce == nonce && data.t == 'INTERACTION_SUCCESS') {
1040
+ // Interaction#deferUpdate
1041
+ removeListeners();
1042
+ dataFromInteractionSuccess = parent;
1043
+ }
1044
+ if (data.nonce !== nonce) return;
1045
+ dataFromNormalEvent = data;
1046
+ finalize(data);
1047
+ };
1048
+ const timeout = setTimeout(() => {
1049
+ if (dataFromInteractionSuccess || dataFromNormalEvent) {
1050
+ finalize(dataFromNormalEvent || dataFromInteractionSuccess);
1051
+ return;
1052
+ }
1053
+ fail();
1054
+ }, timeoutMs).unref();
1055
+ client.incrementMaxListeners();
1056
+ client.on(Events.MESSAGE_CREATE, handler);
1057
+ client.on(Events.INTERACTION_MODAL_CREATE, handler);
1058
+ if (isHandlerDeferUpdate) client.on(Events.UNHANDLED_PACKET, handler);
1059
+ });
1060
+ }
1061
+
1062
+ static clearNullOrUndefinedObject(object) {
1063
+ const data = {};
1064
+ const keys = Object.keys(object);
1065
+
1066
+ for (const key of keys) {
1067
+ const value = object[key];
1068
+ if (value === undefined || value === null || (Array.isArray(value) && value.length === 0)) {
1069
+ continue;
1070
+ } else if (!Array.isArray(value) && typeof value === 'object') {
1071
+ const cleanedValue = Util.clearNullOrUndefinedObject(value);
1072
+ if (cleanedValue !== undefined) {
1073
+ data[key] = cleanedValue;
1074
+ }
1075
+ } else {
1076
+ data[key] = value;
1077
+ }
1078
+ }
1079
+
1080
+ return Object.keys(data).length > 0 ? data : undefined;
1081
+ }
1082
+
1083
+ static getAllPayloadType() {
1084
+ return payloadTypes;
1085
+ }
1086
+
1087
+ /**
1088
+ * Get the payload type of the codec
1089
+ * @param {'opus' | 'H264' | 'H265' | 'VP8' | 'VP9' | 'AV1'} codecName - Codec name
1090
+ * @returns {number}
1091
+ */
1092
+ static getPayloadType(codecName) {
1093
+ return payloadTypes.find(p => p.name === codecName).payload_type;
1094
+ }
1095
+
1096
+ static getSDPCodecName(portUdpH264, portUdpH265, portUdpOpus) {
1097
+ const payloadTypeH264 = Util.getPayloadType('H264');
1098
+ const payloadTypeH265 = Util.getPayloadType('H265');
1099
+ const payloadTypeOpus = Util.getPayloadType('opus');
1100
+ let sdpData = `v=0
1101
+ o=- 0 0 IN IP4 0.0.0.0
1102
+ s=-
1103
+ c=IN IP4 0.0.0.0
1104
+ t=0 0
1105
+ a=tool:libavformat 61.1.100
1106
+ m=video ${portUdpH264} RTP/AVP ${payloadTypeH264}
1107
+ c=IN IP4 127.0.0.1
1108
+ b=AS:1000
1109
+ a=rtpmap:${payloadTypeH264} H264/90000
1110
+ a=fmtp:${payloadTypeH264} profile-level-id=42e01f;sprop-parameter-sets=Z0IAH6tAoAt2AtwEBAaQeJEV,aM4JyA==;packetization-mode=1
1111
+ ${
1112
+ portUdpH265
1113
+ ? `m=video ${portUdpH265} RTP/AVP ${payloadTypeH265}
1114
+ c=IN IP4 127.0.0.1
1115
+ b=AS:1000
1116
+ a=rtpmap:${payloadTypeH265} H265/90000`
1117
+ : ''
1118
+ }
1119
+ m=audio ${portUdpOpus} RTP/AVP ${payloadTypeOpus}
1120
+ c=IN IP4 127.0.0.1
1121
+ b=AS:96
1122
+ a=rtpmap:${payloadTypeOpus} opus/48000/2
1123
+ a=fmtp:${payloadTypeOpus} minptime=10;useinbandfec=1
1124
+ a=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level
1125
+ a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time
1126
+ a=extmap:3 http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01
1127
+ a=extmap:4 urn:ietf:params:rtp-hdrext:sdes:mid
1128
+ a=extmap:5 http://www.webrtc.org/experiments/rtp-hdrext/playout-delay
1129
+ a=extmap:6 http://www.webrtc.org/experiments/rtp-hdrext/video-content-type
1130
+ a=extmap:7 http://www.webrtc.org/experiments/rtp-hdrext/video-timing
1131
+ a=extmap:8 http://www.webrtc.org/experiments/rtp-hdrext/color-space
1132
+ a=extmap:10 urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id
1133
+ a=extmap:11 urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id
1134
+ a=extmap:13 urn:3gpp:video-orientation
1135
+ a=extmap:14 urn:ietf:params:rtp-hdrext:toffset
1136
+ `;
1137
+ return sdpData;
1138
+ }
1139
+ }
1140
+
1141
+ module.exports = Util;
1142
+
1143
+ // Fixes Circular
1144
+ const GuildChannel = require('../structures/GuildChannel');