diff --git a/.gitignore b/.gitignore index cf92c76..44c00d5 100644 --- a/.gitignore +++ b/.gitignore @@ -2,4 +2,5 @@ secrets* deploycommands.json data/existingGames/*.json data/gameApplications/*.json -data/archivedGames/*.json \ No newline at end of file +data/archivedGames/*.json +node_modules/* \ No newline at end of file diff --git a/commands/init.js b/commands/init.js index 26df44d..e03a1e7 100644 --- a/commands/init.js +++ b/commands/init.js @@ -4,17 +4,29 @@ module.exports = { //command definition for discord API data: new SlashCommandBuilder() .setName('init') - .setDescription('what could this be?'), + .setDescription('what could this be?') + .addStringOption(option => + option + .setName("type") + .setDescription("gaming")), //the funciton to be run - async execute(interaction){ - if(interaction.user.id != '122065561428426755'){ - await interaction.reply({content: "Permission Denied", ephemeral: true}); + async execute(interaction) { + if (interaction.user.id != '122065561428426755') { + await interaction.reply({ content: "Permission Denied", ephemeral: true }); return; } - await initGmAndReportForm(interaction); - interaction.reply({content:"Done", ephemeral:"true"}) + const choice = interaction.options.getString("type"); + switch (choice) { + case "music": + await initMusicButtons(interaction); + break; + default: + await initGmAndReportForm(interaction); + break; + } + await interaction.reply({ content: "Done", ephemeral: "true" }) } } @@ -27,14 +39,115 @@ async function initGmAndReportForm(interaction) { const actionRow = new ActionRowBuilder() .addComponents( new ButtonBuilder() - .setCustomId("pushGmForm") - .setLabel("GM Form") - .setStyle(ButtonStyle.Primary), + .setCustomId("pushGmForm") + .setLabel("GM Form") + .setStyle(ButtonStyle.Primary), new ButtonBuilder() - .setCustomId("pushReportForm") - .setLabel("Report Form") - .setStyle(ButtonStyle.Danger) + .setCustomId("pushReportForm") + .setLabel("Report Form") + .setStyle(ButtonStyle.Danger) ); await interaction.channel.send({ embeds: [embed], components: [actionRow] }); +} + +async function initMusicButtons(interaction) { + //row 1 + //join(green), leave(red), + + const row1 = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId("join") + .setEmoji('πŸ“»') + .setLabel("Join") + .setStyle(ButtonStyle.Success), + new ButtonBuilder() + .setCustomId("leave") + .setEmoji('πŸ‘‹') + .setLabel("Leave") + .setStyle(ButtonStyle.Danger), + /* + new ButtonBuilder() + .setCustomId("squelch") + .setEmoji('πŸ”•') + .setLabel("Disable Replies") + .setStyle(ButtonStyle.Secondary) + */ + ); + + //row 2 + //enqueue(modal??), clear, queue, nowplaying + const row2 = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId("enqueueModal") + //.setEmoji('') + .setLabel("Add Song") + .setStyle(ButtonStyle.Primary), + new ButtonBuilder() + .setCustomId("clearQueue") + //.setEmoji('') + .setLabel("Clear Queue") + .setStyle(ButtonStyle.Danger), + new ButtonBuilder() + .setCustomId("showQueue") + //.setEmoji('') + .setLabel("Show Queue") + .setStyle(ButtonStyle.Secondary), + new ButtonBuilder() + .setCustomId("nowPlaying") + //.setEmoji('') + .setLabel("Now Playing") + .setStyle(ButtonStyle.Secondary) + ); + + //row 3 + //loop, loopOne, shuffle + const row3 = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId("loop") + .setEmoji('πŸ”') + //.setLabel("") + .setStyle(ButtonStyle.Primary), + new ButtonBuilder() + .setCustomId("loopOne") + .setEmoji('πŸ”‚') + //.setLabel("") + .setStyle(ButtonStyle.Primary), + new ButtonBuilder() + .setCustomId("shuffleQueue") + .setEmoji('πŸ”€') + //.setLabel("") + .setStyle(ButtonStyle.Secondary) + ); + + //row 4 + //resume, pause, skip, + const row4 = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId("resumePlayback") + .setEmoji('▢️') + //.setLabel("") + .setStyle(ButtonStyle.Primary), + new ButtonBuilder() + .setCustomId("pause") + .setEmoji('⏸️') + //.setLabel("") + .setStyle(ButtonStyle.Primary), + new ButtonBuilder() + .setCustomId("skip") + .setEmoji('⏭️') + //.setLabel("") + .setStyle(ButtonStyle.Secondary), + ); + + //send rows as messages + const channel = interaction.channel; + await channel.send({ components: [row1] }); + await channel.send({ components: [row2] }); + await channel.send({ components: [row3] }); + await channel.send({ components: [row4] }); } \ No newline at end of file diff --git a/commands/music commands/clear.js b/commands/music commands/clear.js new file mode 100644 index 0000000..b176a16 --- /dev/null +++ b/commands/music commands/clear.js @@ -0,0 +1,16 @@ +const { SlashCommandBuilder } = require('discord.js'); + +module.exports = { + data: new SlashCommandBuilder() + .setName("clear") + .setDescription("Clears the playlist.") + .addBooleanOption(option => + option + .setName("clearcurrentlyplaying") + .setDescription("Should the current song also be removed and skipped?") + .setRequired(false)), + + async execute(interaction) { + await interaction.client.functions.get("clearQueue").execute(interaction); + } +} \ No newline at end of file diff --git a/commands/music commands/enqueue.js b/commands/music commands/enqueue.js new file mode 100644 index 0000000..56154a4 --- /dev/null +++ b/commands/music commands/enqueue.js @@ -0,0 +1,17 @@ +const { SlashCommandBuilder } = require('discord.js'); + +module.exports = { + data: new SlashCommandBuilder() + .setName("enqueue") + .setDescription("Adds a song to the playlist.") + .addStringOption(option => + option + .setName("query") + .setDescription("Enter a Youtube video or playlist URL, or enter a search query.") + .setRequired(true) + ), + + async execute(interaction) { + await interaction.client.functions.get("enqueue").execute(interaction); + } +} \ No newline at end of file diff --git a/commands/music commands/join.js b/commands/music commands/join.js new file mode 100644 index 0000000..68e0d13 --- /dev/null +++ b/commands/music commands/join.js @@ -0,0 +1,12 @@ +const { SlashCommandBuilder } = require('discord.js') + +module.exports = { + //command definition for discord API + data: new SlashCommandBuilder() + .setName('join') + .setDescription('Assigns a loudspeaker to your channel.'), + + async execute(interaction) { + await interaction.client.functions.get("join").execute(interaction); + } +} \ No newline at end of file diff --git a/commands/music commands/leave.js b/commands/music commands/leave.js new file mode 100644 index 0000000..9c924dd --- /dev/null +++ b/commands/music commands/leave.js @@ -0,0 +1,11 @@ +const { SlashCommandBuilder } = require('discord.js'); + +module.exports = { + data: new SlashCommandBuilder() + .setName("leave") + .setDescription("Disconnects a loudspeaker from your channel."), + + async execute(interaction) { + await interaction.client.functions.get("leave").execute(interaction); + } +} \ No newline at end of file diff --git a/commands/music commands/loop.js b/commands/music commands/loop.js new file mode 100644 index 0000000..9bfef02 --- /dev/null +++ b/commands/music commands/loop.js @@ -0,0 +1,15 @@ +const { SlashCommandBuilder } = require('discord.js'); + +module.exports = { + data: new SlashCommandBuilder() + .setName("loop") + .setDescription("Sets the playlist on a loop. If not given a choice, on/off will be toggled.") + .addBooleanOption(option => + option + .setName('on') + .setDescription("True turns loop on, False turns loop off.")), + + async execute(interaction) { + await interaction.client.functions.get("loop").execute(interaction); + } +} \ No newline at end of file diff --git a/commands/music commands/nowplaying.js b/commands/music commands/nowplaying.js new file mode 100644 index 0000000..045fe3e --- /dev/null +++ b/commands/music commands/nowplaying.js @@ -0,0 +1,11 @@ +const { SlashCommandBuilder } = require('discord.js'); + +module.exports = { + data: new SlashCommandBuilder() + .setName("nowplaying") + .setDescription("Displays the current song."), + + async execute(interaction) { + await interaction.client.functions.get("nowPlaying").execute(interaction); + } +} \ No newline at end of file diff --git a/commands/music commands/pause.js b/commands/music commands/pause.js new file mode 100644 index 0000000..383dd9d --- /dev/null +++ b/commands/music commands/pause.js @@ -0,0 +1,11 @@ +const { SlashCommandBuilder } = require('discord.js'); + +module.exports = { + data: new SlashCommandBuilder() + .setName("pause") + .setDescription("Pauses playback."), + + async execute(interaction) { + await interaction.client.functions.get("pause").execute(interaction); + } +} \ No newline at end of file diff --git a/commands/music commands/play.js b/commands/music commands/play.js new file mode 100644 index 0000000..555c83b --- /dev/null +++ b/commands/music commands/play.js @@ -0,0 +1,52 @@ +const { SlashCommandBuilder } = require('discord.js') + +module.exports = { + data: new SlashCommandBuilder() + .setName("play") + .setDescription("Plays a Youtube video or playlist given a URL or search query.") + .addStringOption(option => + option + .setName("query") + .setDescription("Enter a Youtube video or playlist URL, or enter a search query.") + .setRequired(false) + ), + + /** + * This function should: + * Assign a new vacant loudspeaker to the user's channel if there isn't one already already assigned and have it join the channel. + * If there is no queue, create a new one. + * Parse whether the query is a video link, playlist link, or search term and enqueue the found video(s). + * If there is no query, unpause the playback (call resume.js). + * If there is a query and the queue was previously empty, start playback. + */ + async execute(interaction) { + if (!interaction.member.voice.channel) { + await interaction.reply({ content: "You need to be in a voice channel to use music commands.", ephemeral: true }); + return; + } + + await interaction.deferReply({ephemeral: true}); + + const result = await interaction.client.functions.get("connectLoudspeaker").execute(interaction); + let response = ""; + //respond to the user + switch (result.status) { + case "no vacancies": + response = "Unfortunately there are no vacant loudspeakers at this time.\n"; + break; + case "already assigned": + response = ""; + break; + case "new assignment": + response = "Assigned a loudspeaker to your channel.\n" + break; + } + + response += await interaction.client.functions.get("enqueue").execute(interaction) + "\n"; + + //TODO: resume/start playback + response += await interaction.client.functions.get("resumePlayback").execute(interaction); + + await interaction.editReply(response); + } +} \ No newline at end of file diff --git a/commands/music commands/queue.js b/commands/music commands/queue.js new file mode 100644 index 0000000..33c85d9 --- /dev/null +++ b/commands/music commands/queue.js @@ -0,0 +1,11 @@ +const { SlashCommandBuilder } = require('discord.js'); + +module.exports = { + data: new SlashCommandBuilder() + .setName("queue") + .setDescription("Shows the queue."), + + async execute(interaction) { + await interaction.client.functions.get("showQueue").execute(interaction); + } +} \ No newline at end of file diff --git a/commands/music commands/resume.js b/commands/music commands/resume.js new file mode 100644 index 0000000..1f7a51d --- /dev/null +++ b/commands/music commands/resume.js @@ -0,0 +1,11 @@ +const { SlashCommandBuilder } = require('discord.js'); + +module.exports = { + data: new SlashCommandBuilder() + .setName("resume") + .setDescription("Resumes playback."), + + async execute(interaction) { + await interaction.client.functions.get("resumePlayback").execute(interaction); + } +} \ No newline at end of file diff --git a/commands/music commands/shuffle.js b/commands/music commands/shuffle.js new file mode 100644 index 0000000..1dfa831 --- /dev/null +++ b/commands/music commands/shuffle.js @@ -0,0 +1,11 @@ +const { SlashCommandBuilder } = require('discord.js'); + +module.exports = { + data: new SlashCommandBuilder() + .setName("shuffle") + .setDescription("Shuffles the playlist."), + + async execute(interaction) { + await interaction.client.functions.get("shuffleQueue").execute(interaction); + } +} \ No newline at end of file diff --git a/commands/music commands/skip.js b/commands/music commands/skip.js new file mode 100644 index 0000000..5c54865 --- /dev/null +++ b/commands/music commands/skip.js @@ -0,0 +1,15 @@ +const { SlashCommandBuilder } = require('discord.js'); + +module.exports = { + data: new SlashCommandBuilder() + .setName("skip") + .setDescription("Skips current song.") + .addBooleanOption(option => + option + .setName('pause') + .setDescription("(Default is false/no) Should the next song be paused?")), + + async execute(interaction) { + await interaction.client.functions.get("skip").execute(interaction); + } +} \ No newline at end of file diff --git a/deploycommands.js b/deploycommands.js index e2bbc8e..740a7c6 100644 --- a/deploycommands.js +++ b/deploycommands.js @@ -1,14 +1,18 @@ const { REST, Routes } = require('discord.js'); const { clientid, productionGuildId, token } = require('./secrets.json'); const fs = require('node:fs'); +const path = require('node:path'); + const commands = []; // Grab all the command files from the commands folder -const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); +//const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js')); +const commandFiles = []; +getAllNestedFiles('./commands', commandFiles); // Grab the SlashCommandBuilder#toJSON() output of each command's data for deployment for (const file of commandFiles) { - const command = require(`./commands/${file}`); + const command = require(`./${file}`); console.log(`requiring ${file}`); commands.push(command.data.toJSON()); } @@ -33,4 +37,16 @@ const rest = new REST({ version: '10' }).setToken(token); // And of course, make sure you catch and log any errors! console.error(error); } -})(); \ No newline at end of file +})(); + +function getAllNestedFiles(rootDirectory, fileList){ + fs.readdirSync(rootDirectory).forEach(File => { + const filePath = path.join(rootDirectory, File); + if(fs.statSync(filePath).isDirectory()){ + return getAllNestedFiles(filePath, fileList); + } + else{ + return fileList.push(filePath); + } + }); +} \ No newline at end of file diff --git a/events/autoDestroyLoudspeaker.js b/events/autoDestroyLoudspeaker.js new file mode 100644 index 0000000..1ebac17 --- /dev/null +++ b/events/autoDestroyLoudspeaker.js @@ -0,0 +1,30 @@ +const { Events } = require('discord.js'); +const { client } = require('../index'); +const { productionGuildId } = require('../secrets.json'); + +module.exports = { + name: Events.VoiceStateUpdate, + /** + * This function will respond to people leaving VCs, seeing if there's a loudspeaker in there. + * If there is nobody else in that channel, the loudspeaker will be destroyed. + * @param {*} oldState + * @param {*} newState + * @returns + */ + async execute(oldState, newState) { + //oldState is a VoiceState object + + if (oldState.guild.id != productionGuildId || !oldState.channel) + return; + + const channel = oldState.channel; + const assignLoudspeakerResult = await client.functions.get("assignLoudspeaker").execute(channel.id, client.loudspeakers); + + //don't do anything if there's no loudspeaker in there or if there are still people other than the bot in there + if (assignLoudspeakerResult.status != "already assigned" || channel.members.size != 1) + return; + + const loudspeakerClient = client.loudspeakers.get(assignLoudspeakerResult.loudspeakerId); + client.functions.get("destroyLoudspeaker").execute(loudspeakerClient); + } +} \ No newline at end of file diff --git a/index.js b/index.js index a3212b3..bb022cc 100644 --- a/index.js +++ b/index.js @@ -3,14 +3,24 @@ const fs = require('node:fs'); const path = require('node:path'); // Require the necessary discord.js classes const { Client, Collection, Events, GatewayIntentBits } = require('discord.js'); -const { token } = require('./secrets.json'); +const { token, loudspeakerTokens } = require('./secrets.json'); -// Create a new client instance -const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.DirectMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildMessages] }); +// Create a new client instance for CAROLINE +const client = new Client({ + intents: [GatewayIntentBits.Guilds, + GatewayIntentBits.GuildMembers, + GatewayIntentBits.DirectMessages, + GatewayIntentBits.MessageContent, + GatewayIntentBits.GuildMessages, + GatewayIntentBits.GuildVoiceStates] +}); // Log in to Discord with your client's token client.login(token); -module.exports = {client}; +module.exports = { client }; + +//create instances for loudspeakers +const loudspeakerClients = loginLoudspeakerClients(); //commands collection client.commands = new Collection(); @@ -18,16 +28,19 @@ client.commands = new Collection(); //load all commands and add them to the collection const commandsPath = path.join(__dirname, 'commands'); //read all files in the commands folder and return an array -const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); +//const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js')); +const commandFiles = []; +getAllNestedFiles(commandsPath, commandFiles); //put commands in the collection for (const file of commandFiles) { - const filePath = path.join(commandsPath, file); - const command = require(filePath); + //const filePath = file; + //const filePath = path.join(commandsPath, file); + const command = require(file); // Set a new item in the Collection with the key as the command name and the value as the exported module if ('data' in command && 'execute' in command) { client.commands.set(command.data.name, command); } else { - console.log(`[WARNING] The command at ${filePath} is missing a required "data" or "execute" property.`); + console.log(`[WARNING] The command at ${file} is missing a required "data" or "execute" property.`); } } @@ -50,13 +63,12 @@ client.functions = new Collection(); const functionsPath = path.join(__dirname, 'lib'); //const functionFiles = fs.readdirSync(functionsPath).filter(file => file.endsWith('.js')); const functionFiles = []; -getAllNestedFiles(functionsPath); -console.log(`found files ${functionFiles}`); -for(const file of functionFiles){ +getAllNestedFiles(functionsPath, functionFiles); +for (const file of functionFiles) { //const filePath = path.join(functionsPath, file); - console.log(`including ${file}`); + //console.log(`including ${file}`); const customFunction = require(file); - if('name' in customFunction && 'execute' in customFunction) + if ('name' in customFunction && 'execute' in customFunction) client.functions.set(customFunction.name, customFunction); else console.log(`The custom function ${file} is missing a name or executable.`); @@ -65,15 +77,45 @@ for(const file of functionFiles){ //initialize cooldown collection for rate limiting, the rest is handled in interactioncreate.js client.cooldowns = new Collection(); -function getAllNestedFiles(rootDirectory){ +//compile the collection of loudspeaker clients +loudspeakerClients.then((loudspeakerClients) => { + client.loudspeakers = new Collection(); + for (const loudspeaker of loudspeakerClients) { + client.loudspeakers.set(loudspeaker.user.id, loudspeaker); + loudspeaker.parentClient = client; + } + console.log(`${loudspeakerClients.length} Loudspeakers ready`); +}, + (error) => console.error(`Error while logging in loudspeakers:\n${error.stack}`)); + +//functions below + +function getAllNestedFiles(rootDirectory, fileList) { fs.readdirSync(rootDirectory).forEach(File => { const filePath = path.join(rootDirectory, File); - if(fs.statSync(filePath).isDirectory()){ - return getAllNestedFiles(filePath); + if (fs.statSync(filePath).isDirectory()) { + return getAllNestedFiles(filePath, fileList); } - else{ - return functionFiles.push(filePath); + else { + return fileList.push(filePath); + } + }); +} + +async function loginLoudspeakerClients() { + return new Promise(async (resolve) => { + const loudspeakerClients = []; + for (const token of loudspeakerTokens) { + const loudspeakerClient = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildVoiceStates] }); + try { + await loudspeakerClient.login(token); + console.log(`Logged in loudspeaker ${loudspeakerClient.user.tag}`); + loudspeakerClients.push(loudspeakerClient); + } + catch (e) { + console.error(`Couldn't login a loudspeaker:\n${e.stack}`); + } } + resolve(loudspeakerClients); }); - return functionFiles; } \ No newline at end of file diff --git a/lib/musicFunctions/assignLoudspeaker.js b/lib/musicFunctions/assignLoudspeaker.js new file mode 100644 index 0000000..78f380e --- /dev/null +++ b/lib/musicFunctions/assignLoudspeaker.js @@ -0,0 +1,39 @@ + +module.exports = { + name: "assignLoudspeaker", + async execute(voiceChannelId, loudspeakerMap) { + /** + * This function should: + * Find out whether the user's vc needs a loudspeaker assigned to it. Return {status: "already assigned", loudspeakerid: loudspeakerid} + * If it does, search the client.loudspeakers collection and find one that is unassigned. + * If there are no vacancies, return {status: "no vacancies"} + * Return {status: "new assignment", loudspeakerid} + */ + + //search for both a vacant loudspeaker and a loudspeaker that is already occupying the user's vc + let vacantLoudspeakerList = []; + let vacantLoudspeakerClient; + let channelHasLoudspeakerAlready = false; + loudspeakerMap.each(loudspeakerClient => { + if (!loudspeakerClient.connection) + vacantLoudspeakerList.push(loudspeakerClient); + //vacantLoudspeakerClient = loudspeakerClient; + else if (loudspeakerClient.connection.joinConfig.channelId == voiceChannelId) { + channelHasLoudspeakerAlready = true; + vacantLoudspeakerClient = loudspeakerClient; + return; + } + }); + + if (channelHasLoudspeakerAlready) + return { status: "already assigned", loudspeakerId: vacantLoudspeakerClient.user.id }; + + if (vacantLoudspeakerList.length == 0) + return { status: "no vacancies" }; + + vacantLoudspeakerClient = vacantLoudspeakerList[Math.floor(Math.random() * vacantLoudspeakerList.length)]; + + return { status: "new assignment", loudspeakerId: vacantLoudspeakerClient.user.id }; + } +} + diff --git a/lib/musicFunctions/clearQueue.js b/lib/musicFunctions/clearQueue.js new file mode 100644 index 0000000..a2ebd70 --- /dev/null +++ b/lib/musicFunctions/clearQueue.js @@ -0,0 +1,51 @@ +const latentFunctionPrecheck = require("./latentFunctionPrecheck"); + +module.exports = { + name: "clearQueue", + + /** + * Removes every song from the queue of the assigned loudspeaker except the one that's currently playing. + * If the interaction boolean option says to, it will also remove the first song by skipping it. + * @param {*} interaction + * @returns + */ + async execute(interaction) { + const guardCheckResponse = await latentFunctionPrecheck.execute(interaction); + if (!guardCheckResponse.inVoiceChannel || !guardCheckResponse.loudspeakerClient) + return; + + //collect loudspeaker + const loudspeakerClient = guardCheckResponse.loudspeakerClient; + + //collect command option to skip current song + //ternary for music control button compatibility + const clearCurrentlyPlayingSong = interaction.options ? interaction.options.getBoolean('clearcurrentlyplaying') : undefined; + + //do nothing if the queue is empty + if (loudspeakerClient.queue.length == 0) { + await interaction.followUp("The queue is already empty."); + return; + } + + //do nothing if the queue only has one song and they don't want to clear it + if (loudspeakerClient.queue.length == 1 && !clearCurrentlyPlayingSong){ + await interaction.followUp("There's only one song in the queue and it was not cleared.\nTry using /skip."); + return; + } + + let skipResponse = ""; + if (clearCurrentlyPlayingSong) { + //weird but it works: https://stackoverflow.com/a/1232046 + loudspeakerClient.queue.length = 1; + skipResponse = await interaction.client.functions.get("skip").execute(interaction); + } + else { //don't clear current song + const temp = loudspeakerClient.queue[0]; + loudspeakerClient.queue.length = 0; + loudspeakerClient.queue.push(temp); + } + + await interaction.followUp(`Queue was cleared.\n${skipResponse}`); + return; + } +} \ No newline at end of file diff --git a/lib/musicFunctions/connectLoudspeaker.js b/lib/musicFunctions/connectLoudspeaker.js new file mode 100644 index 0000000..e23cb47 --- /dev/null +++ b/lib/musicFunctions/connectLoudspeaker.js @@ -0,0 +1,124 @@ +const { AudioPlayerStatus } = require('@discordjs/voice'); + +module.exports = { + name: "connectLoudspeaker", + + async execute(interaction) { + const voiceChannelId = interaction.member.voice.channelId; + const loudspeakerList = interaction.client.loudspeakers; + const loudspeakerAssignmentResult = await interaction.client.functions.get("assignLoudspeaker").execute(voiceChannelId, loudspeakerList); + + if (loudspeakerAssignmentResult.status == "new assignment") { + //assign a new loudspeaker and initialize it + const loudspeakerClient = loudspeakerList.get(loudspeakerAssignmentResult.loudspeakerId); + const voiceChannel = await loudspeakerClient.channels.fetch(interaction.member.voice.channel.id); + initLoudspeaker(loudspeakerClient, voiceChannel); + } + + //If there were no vacant loudspeakers or one has already been assigned, do nothing + return loudspeakerAssignmentResult; + } +} + +async function initLoudspeaker(loudspeakerClient, channel) { + //have the bot join the channel https://discordjs.guide/voice/voice-connections.html#cheat-sheet + //IMPORTANT! The client that instantiates the Guild object when + //creating the voice adapter will be the one who joins the channel! + //Source: https://discord.com/channels/222078108977594368/1090014703209693194/1090123144594980934 + //IMPORTANT! The /voice will attempt to reuse connections from the same group, + //so use a different group identifier for every bot! + //Source: https://discord.com/channels/222078108977594368/1114539446629572668/1114558326341120142 + const { joinVoiceChannel, createAudioPlayer, NoSubscriberBehavior } = require('@discordjs/voice'); + loudspeakerClient.connection = joinVoiceChannel({ + channelId: channel.id, + guildId: channel.guild.id, + adapterCreator: channel.guild.voiceAdapterCreator, + group: loudspeakerClient.id + }); + + //I have no idea what this does other than listen to the connection's state change. + //This fixes an issue where the playback would consistently stop around 1 minute but the player would not show any errors or state changes. + //https://github.com/umutxyp/MusicBot/issues/97#issuecomment-1452607414 + //NEVERMIND this was patched; updating djs/voice fixed the issue and this is no longer necessary + /* + loudspeakerClient.connection.on('stateChange', (oldState, newState) => { + const oldNetworking = Reflect.get(oldState, 'networking'); + const newNetworking = Reflect.get(newState, 'networking'); + const networkStateChangeHandler = (oldNetworkState, newNetworkState) => { + const newUdp = Reflect.get(newNetworkState, 'udp'); + clearInterval(newUdp?.keepAliveInterval); + } + oldNetworking?.off('stateChange', networkStateChangeHandler); + newNetworking?.on('stateChange', networkStateChangeHandler); + }); + */ + + //init loudspeaker with empty queue + loudspeakerClient.queue = []; + + //init player + loudspeakerClient.player = createAudioPlayer({ + behaviors: { + noSubscriber: NoSubscriberBehavior.Play, + debug: true + } + }); + + //install event handlers (DEBUGGING) + loudspeakerClient.player.on(AudioPlayerStatus.Paused, () => { + }); + loudspeakerClient.player.on(AudioPlayerStatus.Playing, () => { + //this is set in function music.js where the next song that starts playing may be paused. + if (loudspeakerClient.player.pauseOnNextPlay) { + loudspeakerClient.player.pause(); + loudspeakerClient.player.pauseOnNextPlay = undefined; + } + }); + loudspeakerClient.player.on(AudioPlayerStatus.Idle, () => { + autoplayNextSong(loudspeakerClient); + }); + loudspeakerClient.player.on(AudioPlayerStatus.Buffering, () => { + }); + loudspeakerClient.player.on(AudioPlayerStatus.AutoPaused, () => { + }); + loudspeakerClient.player.on('error', error => { + console.log(`MUSIC - [WARN] ${loudspeakerClient.user.username} encountered an error:\n${error.stack}`); + }); + loudspeakerClient.player.on('stateChange', (oldState, newState) => { + console.log(`MUSIC - [INFO] ${loudspeakerClient.user.username}: ${oldState.status} -> ${newState.status}`); + }); + loudspeakerClient.connection.on('error', error => { + console.log(`MUSIC - [WARN] ${loudspeakerClient.user.username} connection error:\n${error.message}`); + }); +} + +function autoplayNextSong(loudspeakerClient) { + //if the player is about to be or is already destroyed, don't try to play the next song. + if (!loudspeakerClient.player || loudspeakerClient.player.markedForDeletion) + return; + + console.log(`MUSIC - [INFO] ${loudspeakerClient.user.username} autoplaying next song in queue.`); + //remove the song that just finished + let removedItem = loudspeakerClient.queue.length != 0 ? loudspeakerClient.queue.shift() : undefined; + + //if the first song should be looping (ifelse makes loopOne take precedence over just loop) + if (loudspeakerClient.player.loopOne) { + //in some cases (skip when there's only 1 song), loop should not readd the song + if (loudspeakerClient.player.loopNoReadd) + loudspeakerClient.player.loopNoReadd = undefined; + else + loudspeakerClient.queue.unshift(removedItem) + } + //if the queue should be looping, readd the item to the back of the list + else if (loudspeakerClient.player.loop) { + //in some cases (skip when there's only 1 song), loop should not readd the song + if (loudspeakerClient.player.loopNoReadd) + loudspeakerClient.player.loopNoReadd = undefined; + else + loudspeakerClient.queue.push(removedItem); + } + + //start the next song + if (loudspeakerClient.queue.length != 0) + loudspeakerClient.parentClient.functions.get("startNextSong").execute(loudspeakerClient); //using interaction here might lead to some problems +} \ No newline at end of file diff --git a/lib/musicFunctions/destroyLoudspeaker.js b/lib/musicFunctions/destroyLoudspeaker.js new file mode 100644 index 0000000..0d27503 --- /dev/null +++ b/lib/musicFunctions/destroyLoudspeaker.js @@ -0,0 +1,28 @@ + +module.exports = { + name: "destroyLoudspeaker", + /** + * This function should: + * If there is no loudspeaker assigned to the VC, ignore the command + * Disconnect the loudspeaker from the VC + * Clear/delete the queue (not decided on the specification yet) + * Clear the connection status + */ + async execute(loudspeakerClient) { + //notify the autoplayer to not play the next song because the player is about to be deleted. + loudspeakerClient.player.markedForDestroy = true; + //destroy player -> stop playback and avoid memory leaks + //https://discordjs.guide/voice/audio-player.html#deletion + loudspeakerClient.player.stop(); + loudspeakerClient.player = undefined; + //destroying this is actually good because the player is created at connection time + + //destroy connection -> disconnect + loudspeakerClient.connection.destroy(); + loudspeakerClient.connection = undefined; + + //destroy queue + loudspeakerClient.queue.length = 0; + loudspeakerClient.queue = undefined; + } +} \ No newline at end of file diff --git a/lib/musicFunctions/enqueue.js b/lib/musicFunctions/enqueue.js new file mode 100644 index 0000000..0fd18b6 --- /dev/null +++ b/lib/musicFunctions/enqueue.js @@ -0,0 +1,77 @@ +const latentFunctionPrecheck = require("./latentFunctionPrecheck"); + +module.exports = { + name: "enqueue", + + /** + * This function enqueues a query using an interaction's option.getString('query'). + * It WILL reply to the user with an ephemeral response and also return the response. + * Be sure to use interaction.editReply() in the function that called this. + * @param {*} interaction + * @returns + */ + async execute(interaction) { + const guardCheckResponse = await latentFunctionPrecheck.execute(interaction); + if (!guardCheckResponse.inVoiceChannel || !guardCheckResponse.loudspeakerClient) + return; + + //collect loudspeaker + const loudspeakerClient = guardCheckResponse.loudspeakerClient; + + let response = ""; + let query; + + //check if the query is in a modal + if (interaction.fields) { + query = interaction.fields.getTextInputValue("query"); + } + + //if there's no query, don't do anything + /* + If there already is a query, skip this block. + If interaction was a command AND there's nothing supplied in the block, execute this block + */ + if (!query && interaction.options && !interaction.options.getString('query')) { + response = "No query provided. Did not enqueue anything."; + if (!interaction.replied && !interaction.deferred) + await interaction.followUp(response); + return response; + } + + //if query was not already set from a modal field, set it from the command + if (!query) + query = interaction.options.getString('query'); + + //start a response to the user + response = "Pondering your query..."; + if (interaction.replied || interaction.deferred) + await interaction.editReply(response); + else + await interaction.followUp(response); + + //enqueue query + const videosAdded = await interaction.client.functions.get("enqueueQuery").execute(query, loudspeakerClient); + + //respond with all of the video titles enqueued + response = ""; + if (videosAdded.length == 1) + response += `Added [${videosAdded[0].title}](<${videosAdded[0].url}>)`; //<> to remove embed + + else { + response += "Added the following tracks:\n" + let numVideosListed = 0; + for (let video of videosAdded) { + response += `[${video.title}](<${video.url}>)\n`; + numVideosListed++; + //check if character limit is being approached + if (response.length >= 1600) { + response += `...and ${videosAdded.length - numVideosListed} more tracks.` + break; + } + } + } + + await interaction.editReply(response); + return response; + } +} \ No newline at end of file diff --git a/lib/musicFunctions/enqueueModal.js b/lib/musicFunctions/enqueueModal.js new file mode 100644 index 0000000..ccfac25 --- /dev/null +++ b/lib/musicFunctions/enqueueModal.js @@ -0,0 +1,37 @@ +const { ActionRowBuilder, TextInputBuilder, TextInputStyle, ModalBuilder } = require("discord.js"); + +module.exports = { + name: "enqueueModal", + async execute(interaction) { + //custom latent check + if (!interaction.member.voice.channel) { + await interaction.reply({ content: "You need to be in a voice channel to use music commands.", ephemeral: true }); + return; + } + //collect vc id for loudspeaker assignment test + const channelId = interaction.member.voice.channelId; + //don't do anything if there's no loudspeaker assigned + const loudspeakerAssignmentResult = await interaction.client.functions.get("assignLoudspeaker").execute(channelId, interaction.client.loudspeakers); + if (loudspeakerAssignmentResult.status != "already assigned") { + await interaction.reply({ content: "There is no loudspeaker in your channel! Please use /join first.", ephemeral: true }); + return; + } + + //user passed latent check + //init modal + const modal = new ModalBuilder() + .setCustomId('enqueue') + .setTitle('Enqueue a Song, Playlist, or Search Term'); + + //input row + const query = new TextInputBuilder() + .setRequired(true) + .setCustomId('query') + .setLabel("Video URL, Playlist URL, or Search") + .setStyle(TextInputStyle.Short); + const row1 = new ActionRowBuilder().addComponents(query); + + modal.addComponents(row1); + await interaction.showModal(modal); + } +} \ No newline at end of file diff --git a/lib/musicFunctions/enqueueQuery.js b/lib/musicFunctions/enqueueQuery.js new file mode 100644 index 0000000..13c4b96 --- /dev/null +++ b/lib/musicFunctions/enqueueQuery.js @@ -0,0 +1,85 @@ +// https://github.com/fent/node-ytdl-core#readme +const ytdl = require('ytdl-core'); +// https://github.com/TimeForANinja/node-ytsr +const ytsr = require('ytsr'); +// https://github.com/TimeForANinja/node-ytpl +const ytpl = require('ytpl'); + +module.exports = { + name: "enqueueQuery", + + async execute(query, loudspeakerClient) { + //append queries to queue + const videos = await getQuery(query); + Array.prototype.push.apply(loudspeakerClient.queue, videos); + + return videos; + } +} + +async function getQuery(query) { + //result should be a list of {songName, songURL} that will later be turned into ytdl streams when playback happens + const result = []; + + //Function for pushing video objects to the results list + const pushVideoInfo = async (url) => { + //There's a bug that prevents the below line from working in the base repo. + //Use `npm i ytdl-core@npm:@distube/ytdl-core` instead + const videoInfo = await ytdl.getInfo(url); + result.push({ title: videoInfo.videoDetails.title, url: videoInfo.videoDetails.video_url }); + } + + //Testing for playlist URL + let playlistID; + try { + playlistID = await ytpl.getPlaylistID(query); + } + catch (e) { + playlistID = null; + } + + //if query is a video link + if (ytdl.validateURL(query)) { + //console.log("Query was video URL"); + await pushVideoInfo(query); + } + + //if query is a playlist link + else if (playlistID) { + //console.log("Query was playlist URL"); + //playlist response https://github.com/timeforaninja/node-ytpl/blob/master/example/example_output.txt + /* + await ytpl(playlistID).then(async playlistResponse => { + playlistResponse.items.forEach(async item => { + //console.log(`Playlist adding ${item.shortUrl}`); + await pushVideoInfo(item.shortUrl); + }) + }); + */ + //below boomer way adds them 1 at a time and is much slower but ensures they are in order + const response = await ytpl(playlistID); + for (item of response.items) { + await pushVideoInfo(item.shortUrl); + } + } + + //query is not a link, seqrch + else { + //console.log("Query was a search"); + //search response https://github.com/timeforaninja/node-ytsr/blob/master/example/example_search_output.txt + //get the first video in the results and ytdl it + //ytsr is very error-prone, try-catch it. + try { + await ytsr(query).then(async searchResult => { + await pushVideoInfo(searchResult.items.filter(item => item.type == 'video')[0].url); + }); + } + catch(e){ + console.log(`MUSIC - [WARN] ytsr for "${query}" encountered an error:\n${e.stack}`); + } + } + + //result is now a list of {title, url} + //result.forEach(item => console.log(item)); + return result; +} \ No newline at end of file diff --git a/lib/musicFunctions/join.js b/lib/musicFunctions/join.js new file mode 100644 index 0000000..20b4990 --- /dev/null +++ b/lib/musicFunctions/join.js @@ -0,0 +1,40 @@ + +module.exports = { + name: "join", + + async execute(interaction) { + //this function does not use the latent loudspeaker check + if (!interaction.replied) + await interaction.deferReply({ ephemeral: true }); + + let response = ""; + + if (!interaction.member.voice.channel) { + response = "You need to be in a voice channel to use music commands."; + if (!interaction.replied) + await interaction.followUp(response); + return response; + } + + //attempt to connect loudspeaker + const result = await interaction.client.functions.get("connectLoudspeaker").execute(interaction); + + //respond to the user + switch (result.status) { + case "no vacancies": + response = "Unfortunately there are no vacant loudspeakers at this time."; + break; + case "already assigned": + response = "There is already a loudspeaker in your channel."; + break; + case "new assignment": + response = "Assigned a loudspeaker to your channel." + break; + } + + if (!interaction.replied) + await interaction.followUp(response); + + return response; + } +} \ No newline at end of file diff --git a/lib/musicFunctions/latentFunctionPrecheck.js b/lib/musicFunctions/latentFunctionPrecheck.js new file mode 100644 index 0000000..94d1640 --- /dev/null +++ b/lib/musicFunctions/latentFunctionPrecheck.js @@ -0,0 +1,38 @@ + +module.exports = { + /** + * This function WILL DEFER OR REPLY TO THE INTERACTION! + * + * This function should: + * Check if the user is in a VC + * If not, return {inVoiceChannel: false} + * Check if a loudspeaker is in the channel + * If not, return {inVoiceChannel: true, channelId: , loudspeakerClient: null} + * return {inVoiceChannel: true, channelId: , loudspeakerClient: } + * @param {*} interaaction + * @returns + */ + async execute(interaction){ + if(!interaction.replied && !interaction.deferred) + await interaction.deferReply({ephemeral: true}); + + if (!interaction.replied && !interaction.member.voice.channel) { + await interaction.followUp({ content: "You need to be in a voice channel to use music commands.", ephemeral: true }); + return {inVoiceChannel: false}; + } + + //collect vc id for loudspeaker assignment test + const channelId = interaction.member.voice.channelId; + + //don't do anything if there's no loudspeaker assigned + const loudspeakerAssignmentResult = await interaction.client.functions.get("assignLoudspeaker").execute(channelId, interaction.client.loudspeakers); + if (loudspeakerAssignmentResult.status != "already assigned") { + await interaction.followUp({ content: "There is no loudspeaker in your channel! Please use /join first.", ephemeral: true }); + return {inVoiceChannel: true, channelId: channelId, loudspeakerClient: null}; + } + + //collect loudspeaker + const loudspeakerClient = interaction.client.loudspeakers.get(loudspeakerAssignmentResult.loudspeakerId); + return {inVoiceChannel: true, channelId, loudspeakerClient}; + } +} \ No newline at end of file diff --git a/lib/musicFunctions/leave.js b/lib/musicFunctions/leave.js new file mode 100644 index 0000000..d8286e8 --- /dev/null +++ b/lib/musicFunctions/leave.js @@ -0,0 +1,20 @@ +const latentFunctionPrecheck = require("./latentFunctionPrecheck"); + +module.exports = { + name: "leave", + + async execute(interaction) { + const guardCheckResponse = await latentFunctionPrecheck.execute(interaction); + if (!guardCheckResponse.inVoiceChannel || !guardCheckResponse.loudspeakerClient) + return; + + //collect loudspeaker + const loudspeakerClient = guardCheckResponse.loudspeakerClient; + + //disconnect the loudspeaker + await interaction.client.functions.get('destroyLoudspeaker').execute(loudspeakerClient); + + //respond to the user + await interaction.followUp("Loudspeaker disconnected."); + } +} \ No newline at end of file diff --git a/lib/musicFunctions/loop.js b/lib/musicFunctions/loop.js new file mode 100644 index 0000000..5b02b01 --- /dev/null +++ b/lib/musicFunctions/loop.js @@ -0,0 +1,32 @@ +const latentFunctionPrecheck = require("./latentFunctionPrecheck"); + +module.exports = { + name: "loop", + + async execute(interaction) { + const guardCheckResponse = await latentFunctionPrecheck.execute(interaction); + if (!guardCheckResponse.inVoiceChannel || !guardCheckResponse.loudspeakerClient) + return; + + //collect loudspeaker + const loudspeakerClient = guardCheckResponse.loudspeakerClient; + + //if an option is given, set it to that + //ternary is for compatibilitiy with button controls; they won't have int.options + let choice = interaction.options ? interaction.options.getBoolean('on') : undefined; + if (choice) { + //special message if loop was already set to that value + if (choice == loudspeakerClient.player.loop) { + await interaction.followUp(`Loop was already ${choice ? "on" : "off"}.`); + return; + } + loudspeakerClient.player.loop = choice; + } + //otherwise, toggle the loop + else + loudspeakerClient.player.loop = !loudspeakerClient.player.loop; //i'm going to hope that !undefined becomes true + + await interaction.followUp(`Loop turned ${loudspeakerClient.player.loop ? "on" : "off"}.`); + return ; + } +} \ No newline at end of file diff --git a/lib/musicFunctions/loopOne.js b/lib/musicFunctions/loopOne.js new file mode 100644 index 0000000..1c16442 --- /dev/null +++ b/lib/musicFunctions/loopOne.js @@ -0,0 +1,19 @@ +const latentFunctionPrecheck = require("./latentFunctionPrecheck"); + +module.exports = { + name: "loopOne", + + async execute(interaction) { + const guardCheckResponse = await latentFunctionPrecheck.execute(interaction); + if (!guardCheckResponse.inVoiceChannel || !guardCheckResponse.loudspeakerClient) + return; + + //collect loudspeaker + const loudspeakerClient = guardCheckResponse.loudspeakerClient; + + loudspeakerClient.player.loopOne = !loudspeakerClient.player.loopOne; //i'm going to hope that !undefined becomes true + + await interaction.followUp(`Loop one turned ${loudspeakerClient.player.loopOne ? "on" : "off"}.`); + return ; + } +} \ No newline at end of file diff --git a/lib/musicFunctions/nowPlaying.js b/lib/musicFunctions/nowPlaying.js new file mode 100644 index 0000000..75e254a --- /dev/null +++ b/lib/musicFunctions/nowPlaying.js @@ -0,0 +1,23 @@ +const latentFunctionPrecheck = require("./latentFunctionPrecheck"); + +module.exports = { + name: "nowPlaying", + + async execute(interaction) { + const guardCheckResponse = await latentFunctionPrecheck.execute(interaction); + if (!guardCheckResponse.inVoiceChannel || !guardCheckResponse.loudspeakerClient) + return; + + //collect queue + const queue = guardCheckResponse.loudspeakerClient.queue; + + //special message if the queue is empty + if(queue.length == 0){ + await interaction.followUp("Nothing is playing."); + return; + } + + //respond with the first song and its link + await interaction.followUp(`Now playing: [${queue[0].title}](<${queue[0].url}>)`); + } +} \ No newline at end of file diff --git a/lib/musicFunctions/pause.js b/lib/musicFunctions/pause.js new file mode 100644 index 0000000..dc022a1 --- /dev/null +++ b/lib/musicFunctions/pause.js @@ -0,0 +1,29 @@ +const latentFunctionPrecheck = require("./latentFunctionPrecheck"); + +module.exports = { + name: "pause", + + async execute(interaction) { + const guardCheckResponse = await latentFunctionPrecheck.execute(interaction); + if (!guardCheckResponse.inVoiceChannel || !guardCheckResponse.loudspeakerClient) + return; + + //collect loudspeaker + const loudspeakerClient = guardCheckResponse.loudspeakerClient; + + //do nothing if it's already paused or idle + switch (loudspeakerClient.player.state.status) { + case "paused": + case "autopaused": + await interaction.followUp("Already paused."); + break; + case "idle": + await interaction.followUp("Nothing is playing."); + break; + default: + loudspeakerClient.player.pause(); + await interaction.followUp("Playback paused."); + break; + } + } +} \ No newline at end of file diff --git a/lib/musicFunctions/resumePlayback.js b/lib/musicFunctions/resumePlayback.js new file mode 100644 index 0000000..2586a49 --- /dev/null +++ b/lib/musicFunctions/resumePlayback.js @@ -0,0 +1,43 @@ +const latentFunctionPrecheck = require("./latentFunctionPrecheck"); + +module.exports = { + name: "resumePlayback", + + async execute(interaction) { + const guardCheckResponse = await latentFunctionPrecheck.execute(interaction); + if (!guardCheckResponse.inVoiceChannel || !guardCheckResponse.loudspeakerClient) + return; + + //collect loudspeaker + const loudspeakerClient = guardCheckResponse.loudspeakerClient; + + //start a response to the user + let response = ""; + + //don't do anything if the queue is empty + if (loudspeakerClient.queue.length == 0) { + response = "The queue is empty, playback not resumed."; + //if (!interaction.replied && !interaction.deferred) + //await interaction.followUp("The queue is empty, playback not resumed."); + await interaction.editReply("The queue is empty, playback not resumed."); + return response; + } + + switch (loudspeakerClient.player.state.status) { + case "playing": + response = "Already playing."; + break; + case "idle": + interaction.client.functions.get("startNextSong").execute(loudspeakerClient); + response = "Beginning playback."; + break; + case "paused": + loudspeakerClient.player.unpause(); + response = "Playback resumed."; + break; + } + + await interaction.editReply(response); + return response; + } +} \ No newline at end of file diff --git a/lib/musicFunctions/showQueue.js b/lib/musicFunctions/showQueue.js new file mode 100644 index 0000000..d1a5be6 --- /dev/null +++ b/lib/musicFunctions/showQueue.js @@ -0,0 +1,64 @@ +const latentFunctionPrecheck = require("./latentFunctionPrecheck"); +const { ButtonBuilder, ButtonStyle, ActionRowBuilder } = require("discord.js"); + +module.exports = { + name: "showQueue", + + async execute(interaction) { + const guardCheckResponse = await latentFunctionPrecheck.execute(interaction); + if (!guardCheckResponse.inVoiceChannel || !guardCheckResponse.loudspeakerClient) + return; + + //collect queue + const queue = guardCheckResponse.loudspeakerClient.queue; + + //special response if the queue is empty + if (queue.length == 0) { + await interaction.followUp("The queue is empty."); + return; + } + + //collect starting point if there is one + const startingIndex = /\d+/.exec(interaction.customId) ? /\d+/.exec(interaction.customId) : 0; + + //collect result of tostring and compile response + const result = queueToString(queue, startingIndex); + const response = `Queue for your channel:\n${result.text}`; + + //show a button if there are still more to show + let buttonRow; + if(result.lastIndex < queue.length - 1) + buttonRow = buildButtonRow(result.lastIndex); + + await interaction.followUp({content: response, components: buttonRow ? [buttonRow] : []}); + return response; + } +} + +function queueToString(queue, startingIndex) { + //compile items in the queue starting at 0 if a starting point is not given + //we can't show all of them at once because it may exceed the character limit. + let text = ""; + let i; + for (i = startingIndex; i < queue.length; i++) { + if (text.length >= 1800) { + //off by one if this happens after adding the new item + text += `..and ${queue.length - i} more tracks.` + break; + } + text += `${i}. [${queue[i].title}](<${queue[i].url}>)\n`; + } + return { text: text, lastIndex: i }; +} + +function buildButtonRow(lastIndex){ + const row = new ActionRowBuilder() + .addComponents( + new ButtonBuilder() + .setCustomId(`${lastIndex}_showQueue`) + .setLabel("Show More") + .setStyle(ButtonStyle.Primary) + ); + + return row; +} \ No newline at end of file diff --git a/lib/musicFunctions/shuffleQueue.js b/lib/musicFunctions/shuffleQueue.js new file mode 100644 index 0000000..7e14144 --- /dev/null +++ b/lib/musicFunctions/shuffleQueue.js @@ -0,0 +1,41 @@ +const latentFunctionPrecheck = require("./latentFunctionPrecheck"); + +module.exports = { + name: "shuffleQueue", + + async execute(interaction) { + const guardCheckResponse = await latentFunctionPrecheck.execute(interaction); + if (!guardCheckResponse.inVoiceChannel || !guardCheckResponse.loudspeakerClient) + return; + + //collect loudspeaker + const loudspeakerClient = guardCheckResponse.loudspeakerClient; + + //do nothing if there is nothing to shuffle + //not shuffling the first item, so there needs to be at least 3 items + if (loudspeakerClient.queue.length <= 2) { + let response = "There are too few songs in the queue to shuffle."; + await interaction.followUp(response); + return response; + } + + //shuffle all items except the first + //using this algorithm: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle + const queue = loudspeakerClient.queue; + //save and remove the first item + const firstItem = queue.shift(); + //perform shuffle + for (let i = queue.length - 1; i >= 0; i--) { + const rand = Math.floor(Math.random() * i); + const temp = queue[i]; + queue[i] = queue[rand]; + queue[rand] = temp; + } + //replace first item + queue.unshift(firstItem); + + let response = "Queue shuffled."; + await interaction.followUp(response); + return response; + } +} \ No newline at end of file diff --git a/lib/musicFunctions/skip.js b/lib/musicFunctions/skip.js new file mode 100644 index 0000000..57c9369 --- /dev/null +++ b/lib/musicFunctions/skip.js @@ -0,0 +1,54 @@ +const latentFunctionPrecheck = require("./latentFunctionPrecheck"); + +module.exports = { + name: "skip", + + /** + * Skips the current playing song by calling player.stop(). The autoplayer will immediately play the next song in the queue if there is one. + * If the playback is paused, it shoud also immediately pause the playback of the new song. + * @param {*} interaction + * @returns + */ + async execute(interaction) { + const guardCheckResponse = await latentFunctionPrecheck.execute(interaction); + if (!guardCheckResponse.inVoiceChannel || !guardCheckResponse.loudspeakerClient) + return; + + //collect loudspeaker + const loudspeakerClient = guardCheckResponse.loudspeakerClient; + + //start a response to the user + let response = ""; + + //do nothing if the queue is empty + if(loudspeakerClient.queue.length == 0){ + response = "The queue is empty; there is nothing to skip." + await interaction.followUp(response); + return response; + } + + response = "Current song skipped."; + if(loudspeakerClient.queue.length > 1) + response += `\nNow playing [${loudspeakerClient.queue[1].title}](<${loudspeakerClient.queue[1].url}>).`; + + //start playing the song really quick so that stop() sets the player to the idle state, triggering autoplay + loudspeakerClient.player.unpause(); + //if the user wants the next song to be paused, set that now + //if there's no other song in the list, don't bother doing this + //ternary for compatibiltiy with music button controls + const pauseChoice = interaction.options ? interaction.options.getBoolean('pause') : undefined; + if(pauseChoice && loudspeakerClient.queue.length > 1){ + loudspeakerClient.player.pauseOnNextPlay = true; + response += "\nThe next song will be paused."; + } + //edge case: if loop is on, queue has exactly 1 song, and skip is used, the song should not be readded to the queue + if(loudspeakerClient.queue.length == 1 && loudspeakerClient.player.loop) + loudspeakerClient.player.loopNoReadd = true; + + //stop the player which will load the next song + await loudspeakerClient.player.stop(); + + await interaction.followUp(response); + return response; + } +} \ No newline at end of file diff --git a/lib/musicFunctions/startNextSong.js b/lib/musicFunctions/startNextSong.js new file mode 100644 index 0000000..886f93f --- /dev/null +++ b/lib/musicFunctions/startNextSong.js @@ -0,0 +1,40 @@ +// https://github.com/fent/node-ytdl-core#readme +const ytdl = require('ytdl-core'); + +//ytdl causes an error with nodejs v16, use this instead +//https://github.com/microlinkhq/youtube-dl-exec +const youtubedl = require('youtube-dl-exec'); + +const { createAudioResource } = require('@discordjs/voice') + +module.exports = { + name: "startNextSong", + + async execute(loudspeakerClient) { + //the song at the front of the queue should be removed by the caller. + //collect song at queue front + const song = loudspeakerClient.queue[0]; + //download stream + loudspeakerClient.songStream = ytdl(song.url, { filter: "audioonly" }); + /* + loudspeakerClient.songStream = youtubedl(song.url, { + o: '-', + q: '', + f: 'bestaudio[ext=webm+acodec=opus+asr=48000]/bestaudio', + r: '100K', + }, + { + stdio: ['ignore', 'pipe', 'ignore'] + }); + */ + + //https://discordjs.guide/voice/audio-player.html#playing-audio + //play audio + //create audio resource + const resource = createAudioResource(loudspeakerClient.songStream); + //play source + loudspeakerClient.player.play(resource); + //subscribe to player + loudspeakerClient.connection.subscribe(loudspeakerClient.player); + } +} \ No newline at end of file diff --git a/node_modules/.bin/node-which b/node_modules/.bin/node-which new file mode 100644 index 0000000..aece735 --- /dev/null +++ b/node_modules/.bin/node-which @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../which/bin/node-which" "$@" +else + exec node "$basedir/../which/bin/node-which" "$@" +fi diff --git a/node_modules/.bin/node-which.cmd b/node_modules/.bin/node-which.cmd new file mode 100644 index 0000000..8738aed --- /dev/null +++ b/node_modules/.bin/node-which.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\which\bin\node-which" %* diff --git a/node_modules/.bin/node-which.ps1 b/node_modules/.bin/node-which.ps1 new file mode 100644 index 0000000..cfb09e8 --- /dev/null +++ b/node_modules/.bin/node-which.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../which/bin/node-which" $args + } else { + & "$basedir/node$exe" "$basedir/../which/bin/node-which" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../which/bin/node-which" $args + } else { + & "node$exe" "$basedir/../which/bin/node-which" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.bin/semver b/node_modules/.bin/semver new file mode 100644 index 0000000..77443e7 --- /dev/null +++ b/node_modules/.bin/semver @@ -0,0 +1,12 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") + +case `uname` in + *CYGWIN*|*MINGW*|*MSYS*) basedir=`cygpath -w "$basedir"`;; +esac + +if [ -x "$basedir/node" ]; then + exec "$basedir/node" "$basedir/../semver/bin/semver.js" "$@" +else + exec node "$basedir/../semver/bin/semver.js" "$@" +fi diff --git a/node_modules/.bin/semver.cmd b/node_modules/.bin/semver.cmd new file mode 100644 index 0000000..9913fa9 --- /dev/null +++ b/node_modules/.bin/semver.cmd @@ -0,0 +1,17 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" + SET PATHEXT=%PATHEXT:;.JS;=;% +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\semver\bin\semver.js" %* diff --git a/node_modules/.bin/semver.ps1 b/node_modules/.bin/semver.ps1 new file mode 100644 index 0000000..314717a --- /dev/null +++ b/node_modules/.bin/semver.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args + } else { + & "$basedir/node$exe" "$basedir/../semver/bin/semver.js" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../semver/bin/semver.js" $args + } else { + & "node$exe" "$basedir/../semver/bin/semver.js" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json index c6ca8da..b737e71 100644 --- a/node_modules/.package-lock.json +++ b/node_modules/.package-lock.json @@ -1,83 +1,104 @@ { "name": "caroline", "version": "1.0.0", - "lockfileVersion": 2, + "lockfileVersion": 3, "requires": true, "packages": { - "node_modules/@discord-player/equalizer": { - "version": "0.1.3", - "resolved": "https://registry.npmjs.org/@discord-player/equalizer/-/equalizer-0.1.3.tgz", - "integrity": "sha512-cfHFTW7DCZNgFeFKNlBtWK6DzCaOlxZ5KnnY7jdbm3xQreyJnEt8iuv6hyBRUSjSlP98DI8K4KIC5xr/zP57AQ==" - }, "node_modules/@discordjs/builders": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.4.0.tgz", - "integrity": "sha512-nEeTCheTTDw5kO93faM1j8ZJPonAX86qpq/QVoznnSa8WWcCgJpjlu6GylfINTDW6o7zZY0my2SYdxx2mfNwGA==", - "dependencies": { - "@discordjs/util": "^0.1.0", - "@sapphire/shapeshift": "^3.7.1", - "discord-api-types": "^0.37.20", + "version": "1.6.3", + "resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.6.3.tgz", + "integrity": "sha512-CTCh8NqED3iecTNuiz49mwSsrc2iQb4d0MjMdmS/8pb69Y4IlzJ/DIy/p5GFlgOrFbNO2WzMHkWKQSiJ3VNXaw==", + "dependencies": { + "@discordjs/formatters": "^0.3.1", + "@discordjs/util": "^0.3.1", + "@sapphire/shapeshift": "^3.8.2", + "discord-api-types": "^0.37.41", "fast-deep-equal": "^3.1.3", - "ts-mixer": "^6.0.2", - "tslib": "^2.4.1" + "ts-mixer": "^6.0.3", + "tslib": "^2.5.0" }, "engines": { "node": ">=16.9.0" } }, "node_modules/@discordjs/collection": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.3.0.tgz", - "integrity": "sha512-ylt2NyZ77bJbRij4h9u/wVy7qYw/aDqQLWnadjvDqW/WoWCxrsX6M3CIw9GVP5xcGCDxsrKj5e0r5evuFYwrKg==", + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.5.1.tgz", + "integrity": "sha512-aWEc9DCf3TMDe9iaJoOnO2+JVAjeRNuRxPZQA6GVvBf+Z3gqUuWYBy2NWh4+5CLYq5uoc3MOvUQ5H5m8CJBqOA==", + "engines": { + "node": ">=16.9.0" + } + }, + "node_modules/@discordjs/formatters": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@discordjs/formatters/-/formatters-0.3.1.tgz", + "integrity": "sha512-M7X4IGiSeh4znwcRGcs+49B5tBkNDn4k5bmhxJDAUhRxRHTiFAOTVUNQ6yAKySu5jZTnCbSvTYHW3w0rAzV1MA==", + "dependencies": { + "discord-api-types": "^0.37.41" + }, "engines": { "node": ">=16.9.0" } }, "node_modules/@discordjs/rest": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-1.5.0.tgz", - "integrity": "sha512-lXgNFqHnbmzp5u81W0+frdXN6Etf4EUi8FAPcWpSykKd8hmlWh1xy6BmE0bsJypU1pxohaA8lQCgp70NUI3uzA==", + "version": "1.7.1", + "resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-1.7.1.tgz", + "integrity": "sha512-Ofa9UqT0U45G/eX86cURQnX7gzOJLG2oC28VhIk/G6IliYgQF7jFByBJEykPSHE4MxPhqCleYvmsrtfKh1nYmQ==", "dependencies": { - "@discordjs/collection": "^1.3.0", - "@discordjs/util": "^0.1.0", + "@discordjs/collection": "^1.5.1", + "@discordjs/util": "^0.3.0", "@sapphire/async-queue": "^1.5.0", - "@sapphire/snowflake": "^3.2.2", - "discord-api-types": "^0.37.23", - "file-type": "^18.0.0", - "tslib": "^2.4.1", - "undici": "^5.13.0" + "@sapphire/snowflake": "^3.4.2", + "discord-api-types": "^0.37.41", + "file-type": "^18.3.0", + "tslib": "^2.5.0", + "undici": "^5.22.0" }, "engines": { "node": ">=16.9.0" } }, "node_modules/@discordjs/util": { - "version": "0.1.0", - "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-0.1.0.tgz", - "integrity": "sha512-e7d+PaTLVQav6rOc2tojh2y6FE8S7REkqLldq1XF4soCx74XB/DIjbVbVLtBemf0nLW77ntz0v+o5DytKwFNLQ==", + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/@discordjs/util/-/util-0.3.1.tgz", + "integrity": "sha512-HxXKYKg7vohx2/OupUN/4Sd02Ev3PBJ5q0gtjdcvXb0ErCva8jNHWfe/v5sU3UKjIB/uxOhc+TDOnhqffj9pRA==", "engines": { "node": ">=16.9.0" } }, "node_modules/@discordjs/voice": { - "version": "0.11.0", - "resolved": "https://registry.npmjs.org/@discordjs/voice/-/voice-0.11.0.tgz", - "integrity": "sha512-6+9cj1dxzBJm7WJ9qyG2XZZQ8rcLl6x2caW0C0OxuTtMLAaEDntpb6lqMTFiBg/rDc4Rd59g1w0gJmib33CuHw==", + "version": "0.16.0", + "resolved": "https://registry.npmjs.org/@discordjs/voice/-/voice-0.16.0.tgz", + "integrity": "sha512-ToGCvHD1cBscuW3p+C7zOF5+L7MJmU4GjdOARfNk9mkHyFFZq4grK+Sxr3QXKbp27DtfDBc9uqD4GUOYgxngfA==", "dependencies": { - "@types/ws": "^8.5.3", - "discord-api-types": "^0.36.2", - "prism-media": "^1.3.4", - "tslib": "^2.4.0", - "ws": "^8.8.1" + "@types/ws": "^8.5.4", + "discord-api-types": "^0.37.37", + "prism-media": "^1.3.5", + "tslib": "^2.5.0", + "ws": "^8.13.0" }, "engines": { "node": ">=16.9.0" } }, - "node_modules/@discordjs/voice/node_modules/discord-api-types": { - "version": "0.36.3", - "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.36.3.tgz", - "integrity": "sha512-bz/NDyG0KBo/tY14vSkrwQ/n3HKPf87a0WFW/1M9+tXYK+vp5Z5EksawfCWo2zkAc6o7CClc0eff1Pjrqznlwg==" + "node_modules/@discordjs/ws": { + "version": "0.8.3", + "resolved": "https://registry.npmjs.org/@discordjs/ws/-/ws-0.8.3.tgz", + "integrity": "sha512-hcYtppanjHecbdNyCKQNH2I4RP9UrphDgmRgLYrATEQF1oo4sYSve7ZmGsBEXSzH72MO2tBPdWSThunbxUVk0g==", + "dependencies": { + "@discordjs/collection": "^1.5.1", + "@discordjs/rest": "^1.7.1", + "@discordjs/util": "^0.3.1", + "@sapphire/async-queue": "^1.5.0", + "@types/ws": "^8.5.4", + "@vladfrangu/async_event_emitter": "^2.2.1", + "discord-api-types": "^0.37.41", + "tslib": "^2.5.0", + "ws": "^8.13.0" + }, + "engines": { + "node": ">=16.9.0" + } }, "node_modules/@sapphire/async-queue": { "version": "1.5.0", @@ -89,9 +110,9 @@ } }, "node_modules/@sapphire/shapeshift": { - "version": "3.8.1", - "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-3.8.1.tgz", - "integrity": "sha512-xG1oXXBhCjPKbxrRTlox9ddaZTvVpOhYLmKmApD/vIWOV1xEYXnpoFs68zHIZBGbqztq6FrUPNPerIrO1Hqeaw==", + "version": "3.9.0", + "resolved": "https://registry.npmjs.org/@sapphire/shapeshift/-/shapeshift-3.9.0.tgz", + "integrity": "sha512-iJpHmjAdwX9aSL6MvFpVyo+tkokDtInmSjoJHbz/k4VJfnim3DjvG0hgGEKWtWZgCu45RaLgcoNgR1fCPdIz3w==", "dependencies": { "fast-deep-equal": "^3.1.3", "lodash": "^4.17.21" @@ -102,9 +123,9 @@ } }, "node_modules/@sapphire/snowflake": { - "version": "3.3.0", - "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.3.0.tgz", - "integrity": "sha512-Hec5N6zEkZuZFLybVKyLFLlcSgYmR6C1/+9NkIhxPwOf6tgX52ndJCSz8ADejmbrNE0VuNCNkpzhRZzenEC9vA==", + "version": "3.5.1", + "resolved": "https://registry.npmjs.org/@sapphire/snowflake/-/snowflake-3.5.1.tgz", + "integrity": "sha512-BxcYGzgEsdlG0dKAyOm0ehLGm2CafIrfQTZGWgkfKYbj+pNNsorZ7EotuZukc2MT70E0UbppVbtpBrqpzVzjNA==", "engines": { "node": ">=v14.0.0", "npm": ">=7.0.0" @@ -116,214 +137,153 @@ "integrity": "sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==" }, "node_modules/@types/node": { - "version": "18.11.16", - "resolved": "https://registry.npmjs.org/@types/node/-/node-18.11.16.tgz", - "integrity": "sha512-6T7P5bDkRhqRxrQtwj7vru+bWTpelgtcETAZEUSdq0YISKz8WKdoBukQLYQQ6DFHvU9JRsbFq0JH5C51X2ZdnA==" + "version": "20.2.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.2.1.tgz", + "integrity": "sha512-DqJociPbZP1lbZ5SQPk4oag6W7AyaGMO6gSfRwq3PWl4PXTwJpRQJhDq4W0kzrg3w6tJ1SwlvGZ5uKFHY13LIg==" }, "node_modules/@types/ws": { - "version": "8.5.3", - "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.3.tgz", - "integrity": "sha512-6YOoWjruKj1uLf3INHH7D3qTXwFfEsg1kf3c0uDdSBJwfa/llkwIjrAGV7j7mVgGNbzTQ3HiHKKDXl6bJPD97w==", + "version": "8.5.4", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.5.4.tgz", + "integrity": "sha512-zdQDHKUgcX/zBc4GrwsE/7dVdAD8JR4EuiAXiiUhhfyIJXXb2+PrGshFyeXWQPMmmZ2XxgaqclgpIC7eTXc1mg==", "dependencies": { "@types/node": "*" } }, - "node_modules/boolbase": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/boolbase/-/boolbase-1.0.0.tgz", - "integrity": "sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==", - "peer": true - }, - "node_modules/busboy": { - "version": "1.6.0", - "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", - "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", - "dependencies": { - "streamsearch": "^1.1.0" - }, + "node_modules/@vladfrangu/async_event_emitter": { + "version": "2.2.2", + "resolved": "https://registry.npmjs.org/@vladfrangu/async_event_emitter/-/async_event_emitter-2.2.2.tgz", + "integrity": "sha512-HIzRG7sy88UZjBJamssEczH5q7t5+axva19UbZLO6u0ySbYPrwzWiXBcC0WuHyhKKoeCyneH+FvYzKQq/zTtkQ==", "engines": { - "node": ">=10.16.0" + "node": ">=v14.0.0", + "npm": ">=7.0.0" } }, - "node_modules/cheerio": { - "version": "1.0.0-rc.12", - "resolved": "https://registry.npmjs.org/cheerio/-/cheerio-1.0.0-rc.12.tgz", - "integrity": "sha512-VqR8m68vM46BNnuZ5NtnGBKIE/DfN0cRIzg9n40EIq9NOv90ayxLBXA8fXC5gquFRGJSTRqBq25Jt2ECLR431Q==", - "peer": true, + "node_modules/bin-version": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/bin-version/-/bin-version-6.0.0.tgz", + "integrity": "sha512-nk5wEsP4RiKjG+vF+uG8lFsEn4d7Y6FVDamzzftSunXOoOcOOkzcWdKVlGgFFwlUQCj63SgnUkLLGF8v7lufhw==", "dependencies": { - "cheerio-select": "^2.1.0", - "dom-serializer": "^2.0.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1", - "htmlparser2": "^8.0.1", - "parse5": "^7.0.0", - "parse5-htmlparser2-tree-adapter": "^7.0.0" + "execa": "^5.0.0", + "find-versions": "^5.0.0" }, "engines": { - "node": ">= 6" + "node": ">=12" }, "funding": { - "url": "https://github.com/cheeriojs/cheerio?sponsor=1" + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/cheerio-select": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/cheerio-select/-/cheerio-select-2.1.0.tgz", - "integrity": "sha512-9v9kG0LvzrlcungtnJtpGNxY+fzECQKhK4EGJX2vByejiMX84MFNQw4UxPJl3bFbTMw+Dfs37XaIkCwTZfLh4g==", - "peer": true, + "node_modules/bin-version-check": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/bin-version-check/-/bin-version-check-5.0.0.tgz", + "integrity": "sha512-Q3FMQnS5eZmrBGqmDXLs4dbAn/f+52voP6ykJYmweSA60t6DyH4UTSwZhtbK5UH+LBoWvDljILUQMLRUtsynsA==", "dependencies": { - "boolbase": "^1.0.0", - "css-select": "^5.1.0", - "css-what": "^6.1.0", - "domelementtype": "^2.3.0", - "domhandler": "^5.0.3", - "domutils": "^3.0.1" + "bin-version": "^6.0.0", + "semver": "^7.3.5", + "semver-truncate": "^2.0.0" + }, + "engines": { + "node": ">=12" }, "funding": { - "url": "https://github.com/sponsors/fb55" + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/css-select": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/css-select/-/css-select-5.1.0.tgz", - "integrity": "sha512-nwoRF1rvRRnnCqqY7updORDsuqKzqYJ28+oSMaJMMgOauh3fvwHqMS7EZpIPqK8GL+g9mKxF1vP/ZjSeNjEVHg==", - "peer": true, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", "dependencies": { - "boolbase": "^1.0.0", - "css-what": "^6.1.0", - "domhandler": "^5.0.2", - "domutils": "^3.0.1", - "nth-check": "^2.0.1" + "streamsearch": "^1.1.0" }, - "funding": { - "url": "https://github.com/sponsors/fb55" - } - }, - "node_modules/css-what": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/css-what/-/css-what-6.1.0.tgz", - "integrity": "sha512-HTUrgRJ7r4dsZKU6GjmpfRK1O76h97Z8MfS1G0FozR+oF2kG6Vfe8JE6zwrkbxigziPHinCJ+gCPjA9EaBDtRw==", - "peer": true, "engines": { - "node": ">= 6" - }, - "funding": { - "url": "https://github.com/sponsors/fb55" + "node": ">=10.16.0" } }, - "node_modules/discord-api-types": { - "version": "0.37.23", - "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.23.tgz", - "integrity": "sha512-IixodMf9PjOSrsPorbti5aGv6sJVSPJybAlFMYsYDQXFS7zJyhSmA/ofpPTR9ZYqL1KEDY+xU74oZgBQa52eSQ==" - }, - "node_modules/discord-player": { - "version": "5.4.0", - "resolved": "https://registry.npmjs.org/discord-player/-/discord-player-5.4.0.tgz", - "integrity": "sha512-Hrab+4aNCZCGJwsGkiQx+nfvJNqMEr9T+vEAzTOybWJ83InJOxUK7t6muVqHlkonmXBM/nVOczWs2qacDlRH6g==", + "node_modules/cross-spawn": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", "dependencies": { - "@discord-player/equalizer": "^0.1.2", - "@discordjs/voice": "^0.11.0", - "libsodium-wrappers": "^0.7.10", - "tiny-typed-emitter": "^2.1.0", - "tslib": "^2.4.0" - }, - "funding": { - "url": "https://github.com/Androz2091/discord-player?sponsor=1" + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" }, - "peerDependencies": { - "soundcloud-scraper": "5.x", - "spotify-url-info": "3.x", - "youtube-sr": "4.x", - "ytdl-core": "4.x" + "engines": { + "node": ">= 8" } }, - "node_modules/discord.js": { - "version": "14.7.1", - "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.7.1.tgz", - "integrity": "sha512-1FECvqJJjjeYcjSm0IGMnPxLqja/pmG1B0W2l3lUY2Gi4KXiyTeQmU1IxWcbXHn2k+ytP587mMWqva2IA87EbA==", - "dependencies": { - "@discordjs/builders": "^1.4.0", - "@discordjs/collection": "^1.3.0", - "@discordjs/rest": "^1.4.0", - "@discordjs/util": "^0.1.0", - "@sapphire/snowflake": "^3.2.2", - "@types/ws": "^8.5.3", - "discord-api-types": "^0.37.20", - "fast-deep-equal": "^3.1.3", - "lodash.snakecase": "^4.1.1", - "tslib": "^2.4.1", - "undici": "^5.13.0", - "ws": "^8.11.0" - }, + "node_modules/dargs": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/dargs/-/dargs-7.0.0.tgz", + "integrity": "sha512-2iy1EkLdlBzQGvbweYRFxmFath8+K7+AKB0TlhHWkNuH+TmovaMH/Wp7V7R4u7f4SnX3OgLsU9t1NI9ioDnUpg==", "engines": { - "node": ">=16.9.0" + "node": ">=8" } }, - "node_modules/dom-serializer": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/dom-serializer/-/dom-serializer-2.0.0.tgz", - "integrity": "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg==", - "peer": true, + "node_modules/decompress-response": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/decompress-response/-/decompress-response-6.0.0.tgz", + "integrity": "sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ==", "dependencies": { - "domelementtype": "^2.3.0", - "domhandler": "^5.0.2", - "entities": "^4.2.0" + "mimic-response": "^3.1.0" + }, + "engines": { + "node": ">=10" }, "funding": { - "url": "https://github.com/cheeriojs/dom-serializer?sponsor=1" + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/domelementtype": { - "version": "2.3.0", - "resolved": "https://registry.npmjs.org/domelementtype/-/domelementtype-2.3.0.tgz", - "integrity": "sha512-OLETBj6w0OsagBwdXnPdN0cnMfF9opN69co+7ZrbfPGrdpPVNBUj02spi6B1N7wChLQiPn4CSH/zJvXw56gmHw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - ], - "peer": true + "node_modules/discord-api-types": { + "version": "0.37.43", + "resolved": "https://registry.npmjs.org/discord-api-types/-/discord-api-types-0.37.43.tgz", + "integrity": "sha512-bBhDWU3TF9KADxR/mHp1K4Bvu/LRtFQdGyBjADu4e66F3ZnD4kp12W/SJCttIaCcMXzPV3sfty6eDGRNRph51Q==" }, - "node_modules/domhandler": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/domhandler/-/domhandler-5.0.3.tgz", - "integrity": "sha512-cgwlv/1iFQiFnU96XXgROh8xTeetsnJiDsTc7TYCLFd9+/WNkIqPTxiM/8pSd8VIrhXGTf1Ny1q1hquVqDJB5w==", - "peer": true, - "dependencies": { - "domelementtype": "^2.3.0" + "node_modules/discord.js": { + "version": "14.11.0", + "resolved": "https://registry.npmjs.org/discord.js/-/discord.js-14.11.0.tgz", + "integrity": "sha512-CkueWYFQ28U38YPR8HgsBR/QT35oPpMbEsTNM30Fs8loBIhnA4s70AwQEoy6JvLcpWWJO7GY0y2BUzZmuBMepQ==", + "dependencies": { + "@discordjs/builders": "^1.6.3", + "@discordjs/collection": "^1.5.1", + "@discordjs/formatters": "^0.3.1", + "@discordjs/rest": "^1.7.1", + "@discordjs/util": "^0.3.1", + "@discordjs/ws": "^0.8.3", + "@sapphire/snowflake": "^3.4.2", + "@types/ws": "^8.5.4", + "discord-api-types": "^0.37.41", + "fast-deep-equal": "^3.1.3", + "lodash.snakecase": "^4.1.1", + "tslib": "^2.5.0", + "undici": "^5.22.0", + "ws": "^8.13.0" }, "engines": { - "node": ">= 4" - }, - "funding": { - "url": "https://github.com/fb55/domhandler?sponsor=1" + "node": ">=16.9.0" } }, - "node_modules/domutils": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/domutils/-/domutils-3.0.1.tgz", - "integrity": "sha512-z08c1l761iKhDFtfXO04C7kTdPBLi41zwOZl00WS8b5eiaebNpY00HKbztwBq+e3vyqWNwWF3mP9YLUeqIrF+Q==", - "peer": true, + "node_modules/execa": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/execa/-/execa-5.1.1.tgz", + "integrity": "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg==", "dependencies": { - "dom-serializer": "^2.0.0", - "domelementtype": "^2.3.0", - "domhandler": "^5.0.1" + "cross-spawn": "^7.0.3", + "get-stream": "^6.0.0", + "human-signals": "^2.1.0", + "is-stream": "^2.0.0", + "merge-stream": "^2.0.0", + "npm-run-path": "^4.0.1", + "onetime": "^5.1.2", + "signal-exit": "^3.0.3", + "strip-final-newline": "^2.0.0" }, - "funding": { - "url": "https://github.com/fb55/domutils?sponsor=1" - } - }, - "node_modules/entities": { - "version": "4.4.0", - "resolved": "https://registry.npmjs.org/entities/-/entities-4.4.0.tgz", - "integrity": "sha512-oYp7156SP8LkeGD0GF85ad1X9Ai79WtRsZ2gxJqtBuzH+98YUV6jkHEKlZkMbcrjJjIVJNIDP/3WL9wQkoPbWA==", - "peer": true, "engines": { - "node": ">=0.12" + "node": ">=10" }, "funding": { - "url": "https://github.com/fb55/entities?sponsor=1" + "url": "https://github.com/sindresorhus/execa?sponsor=1" } }, "node_modules/fast-deep-equal": { @@ -332,9 +292,9 @@ "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==" }, "node_modules/file-type": { - "version": "18.0.0", - "resolved": "https://registry.npmjs.org/file-type/-/file-type-18.0.0.tgz", - "integrity": "sha512-jjMwFpnW8PKofLE/4ohlhqwDk5k0NC6iy0UHAJFKoY1fQeGMN0GDdLgHQrvCbSpMwbqzoCZhRI5dETCZna5qVA==", + "version": "18.4.0", + "resolved": "https://registry.npmjs.org/file-type/-/file-type-18.4.0.tgz", + "integrity": "sha512-o6MQrZKTAK6WpvmQk3jqTVUmqxYBxW5bloUfrdH1ZnRFDvvAPNr+l+rgOxM3nkqWT+3khaj3FRMDydWe0xhu+w==", "dependencies": { "readable-web-to-node-stream": "^3.0.2", "strtok3": "^7.0.0", @@ -347,29 +307,37 @@ "url": "https://github.com/sindresorhus/file-type?sponsor=1" } }, - "node_modules/himalaya": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/himalaya/-/himalaya-1.1.0.tgz", - "integrity": "sha512-LLase1dHCRMel68/HZTFft0N0wti0epHr3nNY7ynpLbyZpmrKMQ8YIpiOV77TM97cNpC8Wb2n6f66IRggwdWPw==", - "peer": true - }, - "node_modules/htmlparser2": { - "version": "8.0.1", - "resolved": "https://registry.npmjs.org/htmlparser2/-/htmlparser2-8.0.1.tgz", - "integrity": "sha512-4lVbmc1diZC7GUJQtRQ5yBAeUCL1exyMwmForWkRLnwyzWBFxN633SALPMGYaWZvKe9j1pRZJpauvmxENSp/EA==", - "funding": [ - "https://github.com/fb55/htmlparser2?sponsor=1", - { - "type": "github", - "url": "https://github.com/sponsors/fb55" - } - ], - "peer": true, + "node_modules/find-versions": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/find-versions/-/find-versions-5.1.0.tgz", + "integrity": "sha512-+iwzCJ7C5v5KgcBuueqVoNiHVoQpwiUK5XFLjf0affFTep+Wcw93tPvmb8tqujDNmzhBDPddnWV/qgWSXgq+Hg==", "dependencies": { - "domelementtype": "^2.3.0", - "domhandler": "^5.0.2", - "domutils": "^3.0.1", - "entities": "^4.3.0" + "semver-regex": "^4.0.5" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-stream": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/get-stream/-/get-stream-6.0.1.tgz", + "integrity": "sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/human-signals": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/human-signals/-/human-signals-2.1.0.tgz", + "integrity": "sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw==", + "engines": { + "node": ">=10.17.0" } }, "node_modules/ieee754": { @@ -396,17 +364,41 @@ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, + "node_modules/is-stream": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz", + "integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg==", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-unix": { + "version": "2.0.7", + "resolved": "https://registry.npmjs.org/is-unix/-/is-unix-2.0.7.tgz", + "integrity": "sha512-5aio7Qef7QKjQxdb52cXAmim9Bh3+y3yc9IA2IsXWwZVlc1rRsJHWtBxNwGBu9KqW7PJCbhepNIkfFdilRkHpQ==", + "engines": { + "node": ">= 12" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==" + }, "node_modules/libsodium": { - "version": "0.7.10", - "resolved": "https://registry.npmjs.org/libsodium/-/libsodium-0.7.10.tgz", - "integrity": "sha512-eY+z7hDrDKxkAK+QKZVNv92A5KYkxfvIshtBJkmg5TSiCnYqZP3i9OO9whE79Pwgm4jGaoHgkM4ao/b9Cyu4zQ==" + "version": "0.7.11", + "resolved": "https://registry.npmjs.org/libsodium/-/libsodium-0.7.11.tgz", + "integrity": "sha512-WPfJ7sS53I2s4iM58QxY3Inb83/6mjlYgcmZs7DJsvDlnmVUwNinBCi5vBT43P6bHRy01O4zsMU2CoVR6xJ40A==" }, "node_modules/libsodium-wrappers": { - "version": "0.7.10", - "resolved": "https://registry.npmjs.org/libsodium-wrappers/-/libsodium-wrappers-0.7.10.tgz", - "integrity": "sha512-pO3F1Q9NPLB/MWIhehim42b/Fwb30JNScCNh8TcQ/kIc+qGLQch8ag8wb0keK3EP5kbGakk1H8Wwo7v+36rNQg==", + "version": "0.7.11", + "resolved": "https://registry.npmjs.org/libsodium-wrappers/-/libsodium-wrappers-0.7.11.tgz", + "integrity": "sha512-SrcLtXj7BM19vUKtQuyQKiQCRJPgbpauzl3s0rSwD+60wtHqSUuqcoawlMDheCJga85nKOQwxNYQxf/CKAvs6Q==", "dependencies": { - "libsodium": "^0.7.0" + "libsodium": "^0.7.11" } }, "node_modules/lodash": { @@ -419,11 +411,21 @@ "resolved": "https://registry.npmjs.org/lodash.snakecase/-/lodash.snakecase-4.1.1.tgz", "integrity": "sha512-QZ1d4xoBHYUeuouhEq3lk3Uq7ldgyFXGBhg04+oRLnIz8o9T65Eh+8YdroUwn846zchkA9yDsDl5CVVaV2nqYw==" }, + "node_modules/lru-cache": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", + "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", + "dependencies": { + "yallist": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/m3u8stream": { "version": "0.8.6", "resolved": "https://registry.npmjs.org/m3u8stream/-/m3u8stream-0.8.6.tgz", "integrity": "sha512-LZj8kIVf9KCphiHmH7sbFQTVe4tOemb202fWwvJwR9W5ENW/1hxJN6ksAWGhQgSBSa3jyWhnjKU1Fw1GaOdbyA==", - "peer": true, "dependencies": { "miniget": "^4.2.2", "sax": "^1.2.4" @@ -432,70 +434,77 @@ "node": ">=12" } }, + "node_modules/merge-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/merge-stream/-/merge-stream-2.0.0.tgz", + "integrity": "sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w==" + }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "engines": { + "node": ">=6" + } + }, + "node_modules/mimic-response": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/mimic-response/-/mimic-response-3.1.0.tgz", + "integrity": "sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/miniget": { "version": "4.2.2", "resolved": "https://registry.npmjs.org/miniget/-/miniget-4.2.2.tgz", "integrity": "sha512-a7voNL1N5lDMxvTMExOkg+Fq89jM2vY8pAi9ZEWzZtfNmdfP6RXkvUtFnCAXoCv2T9k1v/fUJVaAEuepGcvLYA==", - "peer": true, "engines": { "node": ">=12" } }, - "node_modules/node-fetch": { - "version": "2.6.8", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.8.tgz", - "integrity": "sha512-RZ6dBYuj8dRSfxpUSu+NsdF1dpPpluJxwOp+6IoDp/sH2QNDSvurYsAa+F1WxY2RjA1iP93xhcsUoYbF2XBqVg==", - "peer": true, + "node_modules/npm-run-path": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/npm-run-path/-/npm-run-path-4.0.1.tgz", + "integrity": "sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw==", "dependencies": { - "whatwg-url": "^5.0.0" + "path-key": "^3.0.0" }, "engines": { - "node": "4.x || >=6.0.0" - }, - "peerDependencies": { - "encoding": "^0.1.0" - }, - "peerDependenciesMeta": { - "encoding": { - "optional": true - } + "node": ">=8" } }, - "node_modules/nth-check": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/nth-check/-/nth-check-2.1.1.tgz", - "integrity": "sha512-lqjrjmaOoAnWfMmBPL+XNnynZh2+swxiX3WUE0s4yEHI6m+AwrK2UZOimIRl3X/4QctVqS8AiZjFqyOGrMXb/w==", - "peer": true, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", "dependencies": { - "boolbase": "^1.0.0" - }, - "funding": { - "url": "https://github.com/fb55/nth-check?sponsor=1" + "wrappy": "1" } }, - "node_modules/parse5": { - "version": "7.1.2", - "resolved": "https://registry.npmjs.org/parse5/-/parse5-7.1.2.tgz", - "integrity": "sha512-Czj1WaSVpaoj0wbhMzLmWD69anp2WH7FXMB9n1Sy8/ZFF9jolSQVMu1Ij5WIyGmcBmhk7EOndpO4mIpihVqAXw==", - "peer": true, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", "dependencies": { - "entities": "^4.4.0" + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" }, "funding": { - "url": "https://github.com/inikulin/parse5?sponsor=1" + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/parse5-htmlparser2-tree-adapter": { - "version": "7.0.0", - "resolved": "https://registry.npmjs.org/parse5-htmlparser2-tree-adapter/-/parse5-htmlparser2-tree-adapter-7.0.0.tgz", - "integrity": "sha512-B77tOZrqqfUfnVcOrUvfdLbz4pu4RopLD/4vmu3HUPswwTA8OH0EMW9BlWR2B0RCoiZRAHEUu7IxeP1Pd1UU+g==", - "peer": true, - "dependencies": { - "domhandler": "^5.0.2", - "parse5": "^7.0.0" - }, - "funding": { - "url": "https://github.com/inikulin/parse5?sponsor=1" + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "engines": { + "node": ">=8" } }, "node_modules/peek-readable": { @@ -511,11 +520,11 @@ } }, "node_modules/prism-media": { - "version": "1.3.4", - "resolved": "https://registry.npmjs.org/prism-media/-/prism-media-1.3.4.tgz", - "integrity": "sha512-eW7LXORkTCQznZs+eqe9VjGOrLBxcBPXgNyHXMTSRVhphvd/RrxgIR7WaWt4fkLuhshcdT5KHL88LAfcvS3f5g==", + "version": "1.3.5", + "resolved": "https://registry.npmjs.org/prism-media/-/prism-media-1.3.5.tgz", + "integrity": "sha512-IQdl0Q01m4LrkN1EGIE9lphov5Hy7WWlH6ulf5QdGePLlPas9p2mhgddTEHrlaXYjjFToM1/rWuwF37VF4taaA==", "peerDependencies": { - "@discordjs/opus": "^0.8.0", + "@discordjs/opus": ">=0.8.0 <1.0.0", "ffmpeg-static": "^5.0.2 || ^4.2.7 || ^3.0.0 || ^2.4.0", "node-opus": "^0.3.3", "opusscript": "^0.0.8" @@ -536,9 +545,9 @@ } }, "node_modules/readable-stream": { - "version": "3.6.0", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.0.tgz", - "integrity": "sha512-BViHy7LKeTz4oNnkcLJ+lVSL6vpiFeX6/d3oSH8zCW7UxP2onchk+vTGB143xuFjHS3deTgkKoXXymXqymiIdA==", + "version": "3.6.2", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", + "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", @@ -585,40 +594,117 @@ "node_modules/sax": { "version": "1.2.4", "resolved": "https://registry.npmjs.org/sax/-/sax-1.2.4.tgz", - "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==", - "peer": true + "integrity": "sha512-NqVDv9TpANUjFm0N8uM5GxL36UgKi9/atZw+x7YFnQ8ckwFGKrl4xX4yWtrey3UJm5nP1kUbnYgLopqWNSRhWw==" }, - "node_modules/soundcloud-scraper": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/soundcloud-scraper/-/soundcloud-scraper-5.0.3.tgz", - "integrity": "sha512-AmS9KmK7mMaPVzHzBk40rANpAttZila3+iAet6EA47EeiTBUzVwjq4B+1LCOLtgPmzDSGk0qn+LZOEd5UhnZTQ==", - "peer": true, + "node_modules/semver": { + "version": "7.5.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.1.tgz", + "integrity": "sha512-Wvss5ivl8TMRZXXESstBA4uR5iXgEN/VC5/sOcuXdVLzcdkz4HWetIoRfG5gb5X+ij/G9rw9YoGn3QoQ8OCSpw==", "dependencies": { - "cheerio": "^1.0.0-rc.10", - "m3u8stream": "^0.8.4", - "node-fetch": "^2.6.1" + "lru-cache": "^6.0.0" + }, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" } }, - "node_modules/spotify-uri": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/spotify-uri/-/spotify-uri-3.0.3.tgz", - "integrity": "sha512-mMstJ4dAMki6GbUjg94kp/h9ZH+7T7+ro/KUC00WVh+WKoLgMRrTKLkWMIwCZNO53Xa8DRHQw/6jwYtRZrVI3g==", - "peer": true, + "node_modules/semver-regex": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/semver-regex/-/semver-regex-4.0.5.tgz", + "integrity": "sha512-hunMQrEy1T6Jr2uEVjrAIqjwWcQTgOAcIM52C8MY1EZSD3DDNft04XzvYKPqjED65bNVVko0YI38nYeEHCX3yw==", "engines": { - "node": ">= 12" + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/spotify-url-info": { - "version": "3.2.3", - "resolved": "https://registry.npmjs.org/spotify-url-info/-/spotify-url-info-3.2.3.tgz", - "integrity": "sha512-h7LCEM86kE68uWWAW0+NbKP+33qPC00SsbdJXzvmzNc18aIA/NukTi8gKZKEwHBENusLX0VRsHfIhyKDg7Fong==", - "peer": true, + "node_modules/semver-truncate": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/semver-truncate/-/semver-truncate-2.0.0.tgz", + "integrity": "sha512-Rh266MLDYNeML5h90ttdMwfXe1+Nc4LAWd9X1KdJe8pPHP4kFmvLZALtsMNHNdvTyQygbEC0D59sIz47DIaq8w==", "dependencies": { - "himalaya": "~1.1.0", - "spotify-uri": "~3.0.3" + "semver": "^6.0.0" }, "engines": { - "node": ">= 12" + "node": ">=8" + } + }, + "node_modules/semver-truncate/node_modules/semver": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.0.tgz", + "integrity": "sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "engines": { + "node": ">=8" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" + }, + "node_modules/simple-concat": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/simple-concat/-/simple-concat-1.0.1.tgz", + "integrity": "sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/simple-get": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/simple-get/-/simple-get-4.0.1.tgz", + "integrity": "sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "dependencies": { + "decompress-response": "^6.0.0", + "once": "^1.3.1", + "simple-concat": "^1.0.0" } }, "node_modules/streamsearch": { @@ -637,6 +723,14 @@ "safe-buffer": "~5.2.0" } }, + "node_modules/strip-final-newline": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/strip-final-newline/-/strip-final-newline-2.0.0.tgz", + "integrity": "sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA==", + "engines": { + "node": ">=6" + } + }, "node_modules/strtok3": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/strtok3/-/strtok3-7.0.0.tgz", @@ -653,11 +747,6 @@ "url": "https://github.com/sponsors/Borewit" } }, - "node_modules/tiny-typed-emitter": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/tiny-typed-emitter/-/tiny-typed-emitter-2.1.0.tgz", - "integrity": "sha512-qVtvMxeXbVej0cQWKqVSSAHmKZEHAvxdF8HEUBFWts8h+xEo5m/lEiPakuyZ3BnCBjOD8i24kzNOiOLLgsSxhA==" - }, "node_modules/token-types": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/token-types/-/token-types-5.0.1.tgz", @@ -674,31 +763,25 @@ "url": "https://github.com/sponsors/Borewit" } }, - "node_modules/tr46": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "peer": true - }, "node_modules/ts-mixer": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.2.tgz", - "integrity": "sha512-zvHx3VM83m2WYCE8XL99uaM7mFwYSkjR2OZti98fabHrwkjsCvgwChda5xctein3xGOyaQhtTeDq/1H/GNvF3A==" + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/ts-mixer/-/ts-mixer-6.0.3.tgz", + "integrity": "sha512-k43M7uCG1AkTyxgnmI5MPwKoUvS/bRvLvUb7+Pgpdlmok8AoqmUaZxUUw8zKM5B1lqZrt41GjYgnvAi0fppqgQ==" }, "node_modules/tslib": { - "version": "2.4.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.4.1.tgz", - "integrity": "sha512-tGyy4dAjRIEwI7BzsB0lynWgOpfqjUdq91XXAlIWD2OwKBH7oCl/GZG/HT4BOHrTlPMOASlMQ7veyTqpmRcrNA==" + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.5.1.tgz", + "integrity": "sha512-KaI6gPil5m9vF7DKaoXxx1ia9fxS4qG5YveErRRVknPDXXriu5M8h48YRjB6h5ZUOKuAKlSJYb0GaDe8I39fRw==" }, "node_modules/undici": { - "version": "5.14.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-5.14.0.tgz", - "integrity": "sha512-yJlHYw6yXPPsuOH0x2Ib1Km61vu4hLiRRQoafs+WUgX1vO64vgnxiCEN9dpIrhZyHFsai3F0AEj4P9zy19enEQ==", + "version": "5.22.1", + "resolved": "https://registry.npmjs.org/undici/-/undici-5.22.1.tgz", + "integrity": "sha512-Ji2IJhFXZY0x/0tVBXeQwgPlLWw13GVzpsWPQ3rV50IFMMof2I55PZZxtm4P6iNq+L5znYN9nSTAq0ZyE6lSJw==", "dependencies": { "busboy": "^1.6.0" }, "engines": { - "node": ">=12.18" + "node": ">=14.0" } }, "node_modules/util-deprecate": { @@ -706,32 +789,35 @@ "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" }, - "node_modules/webidl-conversions": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "peer": true - }, - "node_modules/whatwg-url": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", - "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", - "peer": true, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", "dependencies": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" } }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" + }, "node_modules/ws": { - "version": "8.11.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz", - "integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==", + "version": "8.13.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz", + "integrity": "sha512-x9vcZYTrFPC7aSIbj7sRCYo7L/Xb8Iy+pW0ng0wt2vCJv7M9HOMy0UoN3rr+IFC7hb7vXoqS+P9ktyLLLhO+LA==", "engines": { "node": ">=10.0.0" }, "peerDependencies": { "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" + "utf-8-validate": ">=5.0.2" }, "peerDependenciesMeta": { "bufferutil": { @@ -742,25 +828,63 @@ } } }, - "node_modules/youtube-sr": { - "version": "4.3.4", - "resolved": "https://registry.npmjs.org/youtube-sr/-/youtube-sr-4.3.4.tgz", - "integrity": "sha512-olSYcR80XigutCrePEXBX3/RJJrWfonJQj7+/ggBiWU0CzTDLE1q8+lpWTWCG0JpzhzILp/IB/Bq/glGqqr1TQ==", - "peer": true + "node_modules/yallist": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", + "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" + }, + "node_modules/youtube-dl-exec": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/youtube-dl-exec/-/youtube-dl-exec-2.4.4.tgz", + "integrity": "sha512-vCBdcY3IK3//wZbJDPOVVufZpYNCylaUSGB/PzgU/5jJqUqJlpVdw8Qt4RA770dT18mN7PfBD7zOOlmkTTEh0A==", + "hasInstallScript": true, + "dependencies": { + "bin-version-check": "~5.0.0", + "dargs": "~7.0.0", + "execa": "~5.1.0", + "is-unix": "~2.0.1", + "simple-get": "~4.0.1" + }, + "engines": { + "node": ">= 14" + } }, "node_modules/ytdl-core": { - "version": "4.11.2", - "resolved": "https://registry.npmjs.org/ytdl-core/-/ytdl-core-4.11.2.tgz", - "integrity": "sha512-D939t9b4ZzP3v0zDvehR2q+KgG97UTgrTKju3pOPGQcXtl4W6W5z0EpznzcJFu+OOpl7S7Ge8hv8zU65QnxYug==", - "peer": true, + "name": "@distube/ytdl-core", + "version": "4.11.10", + "resolved": "https://registry.npmjs.org/@distube/ytdl-core/-/ytdl-core-4.11.10.tgz", + "integrity": "sha512-WS7d2N5vA9ptPNaA1hOMkhSs72dJYJ7U4PxLwq0ZLnnJ1JMhdjS2b+xjTinMW9vNNcq4YTcF7pa/GR5hmbcaBw==", "dependencies": { "m3u8stream": "^0.8.6", "miniget": "^4.2.2", - "sax": "^1.1.3" + "sax": "^1.2.4", + "undici": "^5.22.1" }, "engines": { "node": ">=12" } + }, + "node_modules/ytpl": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/ytpl/-/ytpl-2.3.0.tgz", + "integrity": "sha512-Cfw2rxq3PFK6qgWr2Z8gsRefVahEzbn9XEuiJldqdXHE6GhO7kTfEvbZKdfXing1SmgW635uJ/UL2g8r0fvu2Q==", + "dependencies": { + "miniget": "^4.2.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/ytsr": { + "version": "3.8.2", + "resolved": "https://registry.npmjs.org/ytsr/-/ytsr-3.8.2.tgz", + "integrity": "sha512-J+t+a1Ic6jL0Hd0zGX8eFn3uEKtXTf6naa96KO0q7H00GKBfCG8aXW55NAMnaBeUi9Hni6u1xKnf8xZF2F0E/A==", + "dependencies": { + "miniget": "^4.2.2" + }, + "engines": { + "node": ">=8" + } } } } diff --git a/node_modules/@discord-player/equalizer/LICENSE b/node_modules/@discord-player/equalizer/LICENSE deleted file mode 100644 index eceb839..0000000 --- a/node_modules/@discord-player/equalizer/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2023 Androz2091 - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/node_modules/@discord-player/equalizer/README.md b/node_modules/@discord-player/equalizer/README.md deleted file mode 100644 index 7d05b9e..0000000 --- a/node_modules/@discord-player/equalizer/README.md +++ /dev/null @@ -1,74 +0,0 @@ -# `@discord-player/equalizer` - -This library implements Lavaplayer's 15 Band PCM Equalizer & biquad utilities. - -## Installation - -```sh -$ npm install --save @discord-player/equalizer -``` - -## Example - -#### Equalizer - -```js -import { EqualizerStream } from '@discord-player/equalizer'; - -// initialize 15 band equalizer stream -const equalizer = new EqualizerStream(); - -// set equalizer bands, in this case add some bass -equalizer.setEQ([ - { band: 0, gain: 0.25 }, - { band: 1, gain: 0.25 }, - { band: 2, gain: 0.25 } -]); - -// input stream -const input = getPCMAudioSomehow(); - -// pipe input stream to equalizer -const output = input.pipe(equalizer); - -// now do something with the output stream -``` - -#### Biquad - -```js -import { BiquadStream, FilterType } from '@discord-player/equalizer'; - -// initialize biquad stream -const biquad = new BiquadStream(); - -// initialize with filter -const biquad = new BiquadStream({ - filter: FilterType.LowPass -}); - -// set filter -biquad.setFilter(FilterType.HighPass); - -// set gain (Gain is only applicable to LowShelf, HighShelf and PeakingEQ) -biquad.setGain(5); - -// input stream -const input = getPCMAudioSomehow(); - -// pipe input stream to biquad -const output = input.pipe(biquad); -``` - -#### Supported Biquad Filters - -* SinglePoleLowPassApprox -* SinglePoleLowPass -* LowPass -* HighPass -* BandPass -* Notch -* AllPass -* LowShelf -* HighShelf -* PeakingEQ \ No newline at end of file diff --git a/node_modules/@discord-player/equalizer/dist/index.d.ts b/node_modules/@discord-player/equalizer/dist/index.d.ts deleted file mode 100644 index bad7e5f..0000000 --- a/node_modules/@discord-player/equalizer/dist/index.d.ts +++ /dev/null @@ -1,218 +0,0 @@ -import { TransformOptions, Transform, TransformCallback } from 'stream'; - -declare const FilterType: { - readonly SinglePoleLowPassApprox: 0; - readonly SinglePoleLowPass: 1; - readonly LowPass: 2; - readonly HighPass: 3; - readonly BandPass: 4; - readonly Notch: 5; - readonly AllPass: 6; - readonly LowShelf: 7; - readonly HighShelf: 8; - readonly PeakingEQ: 9; -}; -type BiquadFilters = keyof typeof FilterType | (typeof FilterType)[keyof typeof FilterType]; -interface CoefficientsInit { - a1: number; - a2: number; - b0: number; - b1: number; - b2: number; -} -declare const Q_BUTTERWORTH: number; -declare class Coefficients { - a1: number; - a2: number; - b0: number; - b1: number; - b2: number; - constructor(data?: CoefficientsInit); - static from(filter: BiquadFilters, samplingFreq: number, cutoffFreq: number, Q: number, dbGain?: number): Coefficients; -} - -interface BiquadSetFilterProps { - f0: number; - fs: number; - Q: number; - gain?: number; -} -declare class BiquadFilter { - coefficients: Coefficients; - x1: number; - x2: number; - y1: number; - y2: number; - s1: number; - s2: number; - constructor(coefficients: Coefficients); - setFilter(filter: BiquadFilters, options: BiquadSetFilterProps): void; - update(coefficients: Coefficients): void; - replace(coefficients: Coefficients): void; - reset(): void; - run(input: number): number; - runTransposed(input: number): number; -} - -declare class Frequency { - private __val; - constructor(__val: number); - khz(): number; - mhz(): number; - hz(): number; - dt(): number; - valueOf(): number; - toString(): string; - toJSON(): string; -} - -type PCMType = `s${16 | 32}${'l' | 'b'}e`; -interface PCMTransformerOptions extends TransformOptions { - type?: PCMType; -} -declare class PCMTransformer extends Transform { - readonly type: PCMType; - bits: number; - bytes: number; - extremum: number; - constructor(options?: PCMTransformerOptions); - _readInt(buffer: Buffer, index: number): number; - _writeInt(buffer: Buffer, int: number, index: number): number; - clamp(val: number, max?: number, min?: number): number; -} - -interface BiquadStreamOptions extends PCMTransformerOptions { - disabled?: boolean; - filter?: BiquadFilters; - Q?: number; - sample?: number; - cutoff?: number; - gain?: number; -} -interface BiquadFilterUpdateData { - filter?: BiquadFilters; - Q?: number; - sample?: number; - cutoff?: number; - gain?: number; -} -declare class BiquadStream extends PCMTransformer { - disabled: boolean; - biquad: BiquadFilter; - sample: number; - cutoff: number; - gain: number; - filter: BiquadFilters; - Q: number; - constructor(options?: BiquadStreamOptions); - disable(): void; - enable(): void; - toggle(): void; - getFilterName(): BiquadFilters | null; - update(options: BiquadFilterUpdateData): void; - setFilter(filter: BiquadFilters): void; - setQ(Q: number): void; - setSample(fs: number): void; - setCutoff(f0: number): void; - setGain(dB: number): void; - _transform(chunk: Buffer, encoding: BufferEncoding, callback: TransformCallback): void; -} - -type ReadIntCallback = (buffer: Buffer, index: number) => number; -type WriteIntCallback = (buffer: Buffer, int: number, index: number) => number; -declare class ChannelProcessor { - history: number[]; - bandMultipliers: number[]; - current: number; - m1: number; - m2: number; - constructor(bandMultipliers: number[]); - process(samples: Buffer, extremum?: number, bytes?: number, readInt?: ReadIntCallback, writeInt?: WriteIntCallback): Buffer; - reset(): void; -} - -declare class EqualizerCoefficients { - beta: number; - alpha: number; - gamma: number; - constructor(beta: number, alpha: number, gamma: number); - setBeta(v: number): void; - setAlpha(v: number): void; - setGamma(v: number): void; - toJSON(): { - alpha: number; - beta: number; - gamma: number; - }; -} - -declare class EqualizerConfiguration { - bandMultipliers: number[]; - constructor(bandMultipliers: number[]); - setGain(band: number, value: number): void; - getGain(band: number): number; - isValidBand(band: number): boolean; -} - -interface ChannelProcessorInput { - data: Buffer; - readInt?: ReadIntCallback; - writeInt?: WriteIntCallback; - extremum?: number; - bytes?: number; -} -declare class Equalizer extends EqualizerConfiguration { - static BAND_COUNT: 15; - static SAMPLE_RATE: 48000; - static Coefficients48000: EqualizerCoefficients[]; - channels: ChannelProcessor[]; - channelCount: number; - constructor(channelCount: number, bandMultipliers: number[]); - createChannelProcessor(): ChannelProcessor[]; - process(input: ChannelProcessorInput[]): Buffer[]; -} - -interface EqualizerStreamOptions extends PCMTransformerOptions { - bandMultiplier?: EqualizerBand[]; - disabled?: boolean; - channels?: number; -} -interface EqualizerBand { - band: number; - gain: number; -} -declare class EqualizerStream extends PCMTransformer { - disabled: boolean; - bandMultipliers: number[]; - equalizer: Equalizer; - constructor(options?: EqualizerStreamOptions); - _processBands(multiplier: EqualizerBand[]): void; - disable(): void; - enable(): void; - toggle(): void; - _transform(chunk: Buffer, encoding: BufferEncoding, callback: TransformCallback): void; - getEQ(): EqualizerBand[]; - setEQ(bands: EqualizerBand[]): void; - resetEQ(): void; -} - -type MSTStrategy = 'm2s' | 's2m'; -interface MonoStereoTransformerOptions extends PCMTransformerOptions { - strategy: MSTStrategy; -} -declare class MonoStereoTransformer extends PCMTransformer { - disabled: boolean; - strategy: MSTStrategy; - constructor(options?: MonoStereoTransformerOptions); - disable(): void; - enable(): void; - toggle(): void; - setStrategy(strategy: MSTStrategy): void; - _transform(chunk: Buffer, encoding: BufferEncoding, callback: TransformCallback): void; - toStereo(sample: Buffer, len: number): Buffer; - toMono(sample: Buffer, len: number): Buffer; -} - -declare const version: string; - -export { BiquadFilter, BiquadFilterUpdateData, BiquadFilters, BiquadSetFilterProps, BiquadStream, BiquadStreamOptions, ChannelProcessor, ChannelProcessorInput, Coefficients, Equalizer, EqualizerBand, EqualizerCoefficients, EqualizerConfiguration, EqualizerStream, FilterType, Frequency, MSTStrategy, MonoStereoTransformer, MonoStereoTransformerOptions, PCMTransformer, PCMTransformerOptions, PCMType, Q_BUTTERWORTH, ReadIntCallback, WriteIntCallback, version }; diff --git a/node_modules/@discord-player/equalizer/dist/index.js b/node_modules/@discord-player/equalizer/dist/index.js deleted file mode 100644 index 9cdd74f..0000000 --- a/node_modules/@discord-player/equalizer/dist/index.js +++ /dev/null @@ -1,755 +0,0 @@ -"use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// src/index.ts -var src_exports = {}; -__export(src_exports, { - BiquadFilter: () => BiquadFilter, - BiquadStream: () => BiquadStream, - ChannelProcessor: () => ChannelProcessor, - Coefficients: () => Coefficients, - Equalizer: () => Equalizer, - EqualizerCoefficients: () => EqualizerCoefficients, - EqualizerConfiguration: () => EqualizerConfiguration, - EqualizerStream: () => EqualizerStream, - FilterType: () => FilterType, - Frequency: () => Frequency, - MonoStereoTransformer: () => MonoStereoTransformer, - PCMTransformer: () => PCMTransformer, - Q_BUTTERWORTH: () => Q_BUTTERWORTH, - version: () => version -}); -module.exports = __toCommonJS(src_exports); - -// src/biquad/Coefficients.ts -var FilterType = { - SinglePoleLowPassApprox: 0, - SinglePoleLowPass: 1, - LowPass: 2, - HighPass: 3, - BandPass: 4, - Notch: 5, - AllPass: 6, - LowShelf: 7, - HighShelf: 8, - PeakingEQ: 9 -}; -var Q_BUTTERWORTH = Math.SQRT1_2; -var Coefficients = class { - constructor(data) { - this.a1 = 0; - this.a2 = 0; - this.b0 = 0; - this.b1 = 0; - this.b2 = 0; - if (data) { - this.a1 = data.a1; - this.a2 = data.a2; - this.b0 = data.b0; - this.b1 = data.b1; - this.b2 = data.b2; - } - } - static from(filter, samplingFreq, cutoffFreq, Q, dbGain = 0) { - if (2 * cutoffFreq > samplingFreq) { - throw new Error(`Cutoff frequency is too big!`); - } - if (Q < 0) { - throw new Error(`Q may not be negative`); - } - const omega = 2 * Math.PI * cutoffFreq / samplingFreq; - if (typeof filter === "string") - filter = FilterType[filter]; - switch (filter) { - case FilterType.SinglePoleLowPassApprox: { - const alpha = omega / (omega + 1); - return new Coefficients({ - a1: alpha - 1, - a2: 0, - b0: alpha, - b1: 0, - b2: 0 - }); - } - case FilterType.SinglePoleLowPass: { - const omega_t = Math.tan(omega / 2); - const a0 = 1 + omega_t; - return new Coefficients({ - a1: (omega_t - 1) / a0, - a2: 0, - b0: omega_t / a0, - b1: omega_t / a0, - b2: 0 - }); - } - case FilterType.LowPass: { - const omega_s = Math.sin(omega); - const omega_c = Math.cos(omega); - const alpha = omega_s / (2 * Q); - const b0 = (1 - omega_c) * 0.5; - const b1 = 1 - omega_c; - const b2 = (1 - omega_c) * 0.5; - const a0 = 1 + alpha; - const a1 = -2 * omega_c; - const a2 = 1 - alpha; - const div = 1 / a0; - return new Coefficients({ - a1: a1 * div, - a2: a2 * div, - b0: b0 * div, - b1: b1 * div, - b2: b2 * div - }); - } - case FilterType.HighPass: { - const omega_s = Math.sin(omega); - const omega_c = Math.cos(omega); - const alpha = omega_s / (2 * Q); - const b0 = (1 + omega_c) * 0.5; - const b1 = -(1 + omega_c); - const b2 = (1 + omega_c) * 0.5; - const a0 = 1 + alpha; - const a1 = -2 * omega_c; - const a2 = 1 - alpha; - const div = 1 / a0; - return new Coefficients({ - a1: a1 * div, - a2: a2 * div, - b0: b0 * div, - b1: b1 * div, - b2: b2 * div - }); - } - case FilterType.Notch: { - const omega_s = Math.sin(omega); - const omega_c = Math.cos(omega); - const alpha = omega_s / (2 * Q); - const b0 = 1; - const b1 = -2 * omega_c; - const b2 = 1; - const a0 = 1 + alpha; - const a1 = -2 * omega_c; - const a2 = 1 - alpha; - const div = 1 / a0; - return new Coefficients({ - a1: a1 * div, - a2: a2 * div, - b0: b0 * div, - b1: b1 * div, - b2: b2 * div - }); - } - case FilterType.BandPass: { - const omega_s = Math.sin(omega); - const omega_c = Math.cos(omega); - const alpha = omega_s / (2 * Q); - const b0 = omega_s / 2; - const b1 = 0; - const b2 = -(omega_s / 2); - const a0 = 1 + alpha; - const a1 = -2 * omega_c; - const a2 = 1 - alpha; - const div = 1 / a0; - return new Coefficients({ - a1: a1 * div, - a2: a2 * div, - b0: b0 * div, - b1: b1 * div, - b2: b2 * div - }); - } - case FilterType.AllPass: { - const omega_s = Math.sin(omega); - const omega_c = Math.cos(omega); - const alpha = omega_s / (2 * Q); - const b0 = 1 - alpha; - const b1 = -2 * omega_c; - const b2 = 1 + alpha; - const a0 = 1 + alpha; - const a1 = -2 * omega_c; - const a2 = 1 - alpha; - return new Coefficients({ - a1: a1 / a0, - a2: a2 / a0, - b0: b0 / a0, - b1: b1 / a0, - b2: b2 / a0 - }); - } - case FilterType.LowShelf: { - const a = Math.pow(10, dbGain / 40); - const omega_s = Math.sin(omega); - const omega_c = Math.cos(omega); - const alpha = omega_s / (2 * Q); - const b0 = a * (a + 1 - (a - 1) * omega_c + 2 * alpha * Math.sqrt(a)); - const b1 = 2 * a * (a - 1 - (a + 1) * omega_c); - const b2 = a * (a + 1 - (a - 1) * omega_c - 2 * alpha * Math.sqrt(a)); - const a0 = a + 1 + (a - 1) * omega_c + 2 * alpha * Math.sqrt(a); - const a1 = -2 * (a - 1 + (a + 1) * omega_c); - const a2 = a + 1 + (a - 1) * omega_c - 2 * alpha * Math.sqrt(a); - return new Coefficients({ - a1: a1 / a0, - a2: a2 / a0, - b0: b0 / a0, - b1: b1 / a0, - b2: b2 / a0 - }); - } - case FilterType.HighShelf: { - const a = Math.pow(10, dbGain / 40); - const omega_s = Math.sin(omega); - const omega_c = Math.cos(omega); - const alpha = omega_s / (2 * Q); - const b0 = a * (a + 1 + (a - 1) * omega_c + 2 * alpha * Math.sqrt(a)); - const b1 = -2 * a * (a - 1 + (a + 1) * omega_c); - const b2 = a * (a + 1 + (a - 1) * omega_c - 2 * alpha * Math.sqrt(a)); - const a0 = a + 1 - (a - 1) * omega_c + 2 * alpha * Math.sqrt(a); - const a1 = 2 * (a - 1 - (a + 1) * omega_c); - const a2 = a + 1 - (a - 1) * omega_c - 2 * alpha * Math.sqrt(a); - return new Coefficients({ - a1: a1 / a0, - a2: a2 / a0, - b0: b0 / a0, - b1: b1 / a0, - b2: b2 / a0 - }); - } - case FilterType.PeakingEQ: { - const a = Math.pow(10, dbGain / 40); - const omega_s = Math.sin(omega); - const omega_c = Math.cos(omega); - const alpha = omega_s / (2 * Q); - const b0 = 1 + alpha * a; - const b1 = -2 * omega_c; - const b2 = 1 - alpha * a; - const a0 = 1 + alpha / a; - const a1 = -2 * omega_c; - const a2 = 1 - alpha / a; - return new Coefficients({ - a1: a1 / a0, - a2: a2 / a0, - b0: b0 / a0, - b1: b1 / a0, - b2: b2 / a0 - }); - } - default: - throw new TypeError("Invalid filter type"); - } - } -}; -__name(Coefficients, "Coefficients"); - -// src/biquad/Biquad.ts -var BiquadFilter = class { - constructor(coefficients) { - this.coefficients = coefficients; - this.x1 = 0; - this.x2 = 0; - this.y1 = 0; - this.y2 = 0; - this.s1 = 0; - this.s2 = 0; - } - setFilter(filter, options) { - const coefficients = Coefficients.from(filter, options.fs, options.f0, options.Q, options.gain); - this.update(coefficients); - } - update(coefficients) { - this.coefficients = coefficients; - } - replace(coefficients) { - this.coefficients = coefficients; - } - reset() { - this.x1 = 0; - this.x2 = 0; - this.y1 = 0; - this.y2 = 0; - this.s1 = 0; - this.s2 = 0; - } - run(input) { - const { a1, a2, b0, b1, b2 } = this.coefficients; - const out = b0 * input + b1 * this.x1 + b2 * this.x2 - a1 * this.y1 - a2 * this.y2; - this.x2 = this.x1; - this.x1 = input; - this.y2 = this.y1; - this.y1 = out; - return out; - } - runTransposed(input) { - const { a1, a2, b0, b1, b2 } = this.coefficients; - const out = this.s1 + b0 * input; - this.s1 = this.s2 + b1 * input - a1 * out; - this.s2 = b2 * input - a2 * out; - return out; - } -}; -__name(BiquadFilter, "BiquadFilter"); - -// src/utils/Frequency.ts -var Frequency = class { - constructor(__val) { - this.__val = __val; - if (typeof __val !== "number" || isNaN(__val) || __val === Infinity) - throw new TypeError("Frequency value must be a number"); - if (this.__val < 0) - throw new Error(`Frequency value cannot be negative (${__val})`); - } - khz() { - return this.__val * 1e3; - } - mhz() { - return this.__val * 1e6; - } - hz() { - return this.__val; - } - dt() { - return 1 / this.__val; - } - valueOf() { - return this.__val; - } - toString() { - return `${this.__val}Hz`; - } - toJSON() { - return this.toString(); - } -}; -__name(Frequency, "Frequency"); - -// src/utils/PCMTransformer.ts -var import_stream = require("stream"); -var PCMTransformer = class extends import_stream.Transform { - constructor(options = {}) { - super(options); - this.type = "s16le"; - options.type ?? (options.type = "s16le"); - switch (options.type) { - case "s16be": - case "s16le": - this.type = options.type; - this.bits = 16; - break; - case "s32be": - case "s32le": - this.type = options.type; - this.bits = 32; - break; - default: - throw new TypeError(`Expected type to be one of ${["s16be", "s16le", "s32be", "s32le"].join(", ")}, got "${options.type}"`); - } - this.bytes = this.bits / 8; - this.extremum = Math.pow(2, this.bits - 1); - } - _readInt(buffer, index) { - const method = `readInt${this.type.substring(1).toUpperCase()}`; - return buffer[method](index); - } - _writeInt(buffer, int, index) { - const method = `writeInt${this.type.substring(1).toUpperCase()}`; - return buffer[method](int, index); - } - clamp(val, max = this.extremum - 1, min = -this.extremum) { - return Math.min(max, Math.max(min, val)); - } -}; -__name(PCMTransformer, "PCMTransformer"); - -// src/biquad/BiquadStream.ts -var BiquadStream = class extends PCMTransformer { - constructor(options = {}) { - super(options); - this.disabled = false; - this.sample = 48e3; - this.cutoff = 80; - this.gain = 0; - this.Q = Q_BUTTERWORTH; - this.disabled = !!options.disabled; - if ("sample" in options) - this.sample = options.sample; - if ("cutoff" in options) - this.cutoff = options.cutoff; - if ("gain" in options) - this.gain = options.gain; - if ("Q" in options) - this.Q = options.Q; - if ("filter" in options) { - this.filter = options.filter; - if (this.filter != null) { - this.biquad = new BiquadFilter(Coefficients.from(this.filter, this.sample, this.cutoff, this.Q, this.gain)); - } - } - } - disable() { - this.disabled = true; - } - enable() { - this.disabled = false; - } - toggle() { - this.disabled = !this.disabled; - } - getFilterName() { - if (this.filter == null) - return null; - if (typeof this.filter === "string") - return this.filter; - return Object.entries(FilterType).find((r) => r[1] === this.filter)?.[0]; - } - update(options) { - if ("sample" in options) - this.sample = options.sample; - if ("cutoff" in options) - this.cutoff = options.cutoff; - if ("gain" in options) - this.gain = options.gain; - if ("Q" in options) - this.Q = options.Q; - if ("filter" in options) - this.filter = options.filter; - if (this.filter != null) { - this.biquad = new BiquadFilter(Coefficients.from(this.filter, this.sample, this.cutoff, this.Q, this.gain)); - } - } - setFilter(filter) { - this.update({ filter }); - } - setQ(Q) { - this.update({ Q }); - } - setSample(fs) { - this.update({ sample: fs }); - } - setCutoff(f0) { - this.update({ cutoff: f0 }); - } - setGain(dB) { - this.update({ gain: dB }); - } - _transform(chunk, encoding, callback) { - if (this.disabled || !this.biquad) { - this.push(chunk); - return callback(); - } - const endIndex = Math.floor(chunk.length / 2) * 2; - const { bytes, extremum } = this; - for (let sampleIndex = 0; sampleIndex < endIndex; sampleIndex += bytes) { - const int = this._readInt(chunk, sampleIndex); - const result = this.biquad.run(int); - const val = Math.min(extremum - 1, Math.max(-extremum, result)); - this._writeInt(chunk, val, sampleIndex); - } - this.push(chunk); - return callback(); - } -}; -__name(BiquadStream, "BiquadStream"); - -// src/equalizer/ChannelProcessor.ts -var ChannelProcessor = class { - constructor(bandMultipliers) { - this.history = new Array(Equalizer.BAND_COUNT * 6).fill(0); - this.bandMultipliers = bandMultipliers; - this.current = 0; - this.m1 = 2; - this.m2 = 1; - } - process(samples, extremum = 131072, bytes = 2, readInt, writeInt) { - const endIndex = Math.floor(samples.length / 2) * 2; - for (let sampleIndex = 0; sampleIndex < endIndex; sampleIndex += bytes) { - const sample = readInt?.(samples, sampleIndex) ?? samples.readInt16LE(sampleIndex); - let result = sample * 0.25; - for (let bandIndex = 0; bandIndex < Equalizer.BAND_COUNT; bandIndex++) { - const x = bandIndex * 6; - const y = x + 3; - const coefficients = Equalizer.Coefficients48000[bandIndex]; - const bandResult = coefficients.alpha * (sample - this.history[x + this.m2]) + coefficients.gamma * this.history[y + this.m1] - coefficients.beta * this.history[y + this.m2]; - this.history[x + this.current] = sample; - this.history[y + this.current] = bandResult; - result += bandResult * this.bandMultipliers[bandIndex]; - } - const val = Math.min(extremum - 1, Math.max(-extremum, result * 4)); - writeInt?.(samples, val, sampleIndex) ?? samples.writeInt16LE(val, sampleIndex); - if (++this.current === 3) { - this.current = 0; - } - if (++this.m1 === 3) { - this.m1 = 0; - } - if (++this.m2 === 3) { - this.m2 = 0; - } - } - return samples; - } - reset() { - this.history.fill(0); - } -}; -__name(ChannelProcessor, "ChannelProcessor"); - -// src/equalizer/Coefficients.ts -var EqualizerCoefficients = class { - constructor(beta, alpha, gamma) { - this.beta = beta; - this.alpha = alpha; - this.gamma = gamma; - } - setBeta(v) { - this.beta = v; - } - setAlpha(v) { - this.alpha = v; - } - setGamma(v) { - this.gamma = v; - } - toJSON() { - const { alpha, beta, gamma } = this; - return { alpha, beta, gamma }; - } -}; -__name(EqualizerCoefficients, "EqualizerCoefficients"); - -// src/equalizer/EqualizerConfiguration.ts -var EqualizerConfiguration = class { - constructor(bandMultipliers) { - this.bandMultipliers = bandMultipliers; - } - setGain(band, value) { - if (this.isValidBand(band)) { - this.bandMultipliers[band] = Math.max(Math.min(value, 1), -0.25); - } - } - getGain(band) { - if (this.isValidBand(band)) { - return this.bandMultipliers[band]; - } else { - return 0; - } - } - isValidBand(band) { - return band >= 0 && band < this.bandMultipliers.length; - } -}; -__name(EqualizerConfiguration, "EqualizerConfiguration"); - -// src/equalizer/Equalizer.ts -var Equalizer = class extends EqualizerConfiguration { - constructor(channelCount, bandMultipliers) { - super(bandMultipliers); - this.channels = []; - this.channelCount = channelCount; - this.channels = this.createChannelProcessor(); - } - createChannelProcessor() { - return Array.from({ length: this.channelCount }, () => { - return new ChannelProcessor(this.bandMultipliers); - }); - } - process(input) { - return this.channels.map((c, i) => { - const { data, extremum, readInt, writeInt, bytes } = input[i]; - return c.process(data, extremum, bytes, readInt, writeInt); - }); - } -}; -__name(Equalizer, "Equalizer"); -Equalizer.BAND_COUNT = 15; -Equalizer.SAMPLE_RATE = 48e3; -Equalizer.Coefficients48000 = [ - new EqualizerCoefficients(0.99847546664, 76226668143e-14, 1.9984647656), - new EqualizerCoefficients(0.99756184654, 0.0012190767289, 1.9975344645), - new EqualizerCoefficients(0.99616261379, 0.0019186931041, 1.9960947369), - new EqualizerCoefficients(0.99391578543, 0.0030421072865, 1.9937449618), - new EqualizerCoefficients(0.99028307215, 0.0048584639242, 1.9898465702), - new EqualizerCoefficients(0.98485897264, 0.0075705136795, 1.9837962543), - new EqualizerCoefficients(0.97588512657, 0.012057436715, 1.9731772447), - new EqualizerCoefficients(0.96228521814, 0.018857390928, 1.9556164694), - new EqualizerCoefficients(0.94080933132, 0.029595334338, 1.9242054384), - new EqualizerCoefficients(0.90702059196, 0.046489704022, 1.8653476166), - new EqualizerCoefficients(0.85868004289, 0.070659978553, 1.7600401337), - new EqualizerCoefficients(0.78409610788, 0.10795194606, 1.5450725522), - new EqualizerCoefficients(0.68332861002, 0.15833569499, 1.1426447155), - new EqualizerCoefficients(0.55267518228, 0.22366240886, 0.40186190803), - new EqualizerCoefficients(0.41811888447, 0.29094055777, -0.70905944223) -]; - -// src/equalizer/EqualizerStream.ts -var EqualizerStream = class extends PCMTransformer { - constructor(options) { - super(options); - this.disabled = false; - this.bandMultipliers = new Array(Equalizer.BAND_COUNT).fill(0); - options = Object.assign( - {}, - { - bandMultiplier: [], - channels: 1, - disabled: false - }, - options || {} - ); - if (options.disabled) - this.disabled = !!options.disabled; - this.equalizer = new Equalizer(options.channels || 1, this.bandMultipliers); - if (Array.isArray(options.bandMultiplier)) - this._processBands(options.bandMultiplier); - } - _processBands(multiplier) { - for (const mul of multiplier) { - if (mul.band > Equalizer.BAND_COUNT - 1 || mul.band < 0) - throw new RangeError(`Band value out of range. Expected >0 & <${Equalizer.BAND_COUNT - 1}, received "${mul.band}"`); - this.equalizer.setGain(mul.band, mul.gain); - } - } - disable() { - this.disabled = true; - } - enable() { - this.disabled = false; - } - toggle() { - this.disabled = !this.disabled; - } - _transform(chunk, encoding, callback) { - if (this.disabled) { - this.push(chunk); - return callback(); - } - this.equalizer.process([ - { - data: chunk, - extremum: this.extremum, - readInt: (b, idx) => this._readInt(b, idx), - writeInt: (b, i, idx) => this._writeInt(b, i, idx), - bytes: this.bytes - } - ]); - this.push(chunk); - return callback(); - } - getEQ() { - return this.bandMultipliers.map((m, i) => ({ - band: i, - gain: m - })); - } - setEQ(bands) { - this._processBands(bands); - } - resetEQ() { - this._processBands( - Array.from( - { - length: Equalizer.BAND_COUNT - }, - (_, i) => ({ - band: i, - gain: 0 - }) - ) - ); - } -}; -__name(EqualizerStream, "EqualizerStream"); - -// src/audio/MonoStereoTransformer.ts -var MonoStereoTransformer = class extends PCMTransformer { - constructor(options) { - super(options); - this.disabled = false; - if (!["m2s", "s2m"].includes(options?.strategy)) { - throw new TypeError(`Strategy must be "m2s" or "s2m"`); - } - this.strategy = options.strategy; - } - disable() { - this.disabled = true; - } - enable() { - this.disabled = false; - } - toggle() { - this.disabled = !this.disabled; - } - setStrategy(strategy) { - this.strategy = strategy; - } - _transform(chunk, encoding, callback) { - if (this.disabled) { - this.push(chunk); - return callback(); - } - const len = Math.floor(chunk.length / 2) * 2; - if (this.strategy === "m2s") { - this.push(this.toStereo(chunk, len)); - } else { - this.push(this.toMono(chunk, len)); - } - return callback(); - } - toStereo(sample, len) { - const bytes = this.bytes; - const stereoBuffer = Buffer.alloc(len * 2); - for (let i = 0; i < len; i += bytes) { - stereoBuffer[i * 2 + 0] = sample[i]; - stereoBuffer[i * 2 + 1] = sample[i + 1]; - stereoBuffer[i * 2 + 2] = sample[i]; - stereoBuffer[i * 2 + 3] = sample[i + 1]; - } - return stereoBuffer; - } - toMono(sample, len) { - const bytes = this.bytes; - const monoBuffer = Buffer.alloc(Math.floor(len / 2)); - for (let i = 0; i < len; i += bytes) { - monoBuffer[i] = sample[i * 2 + 0]; - monoBuffer[i + 1] = sample[i * 2 + 1]; - } - return monoBuffer; - } -}; -__name(MonoStereoTransformer, "MonoStereoTransformer"); - -// src/index.ts -var version = "0.1.3"; -// Annotate the CommonJS export names for ESM import in node: -0 && (module.exports = { - BiquadFilter, - BiquadStream, - ChannelProcessor, - Coefficients, - Equalizer, - EqualizerCoefficients, - EqualizerConfiguration, - EqualizerStream, - FilterType, - Frequency, - MonoStereoTransformer, - PCMTransformer, - Q_BUTTERWORTH, - version -}); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@discord-player/equalizer/dist/index.js.map b/node_modules/@discord-player/equalizer/dist/index.js.map deleted file mode 100644 index d1b792a..0000000 --- a/node_modules/@discord-player/equalizer/dist/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["../src/index.ts","../src/biquad/Coefficients.ts","../src/biquad/Biquad.ts","../src/utils/Frequency.ts","../src/utils/PCMTransformer.ts","../src/biquad/BiquadStream.ts","../src/equalizer/ChannelProcessor.ts","../src/equalizer/Coefficients.ts","../src/equalizer/EqualizerConfiguration.ts","../src/equalizer/Equalizer.ts","../src/equalizer/EqualizerStream.ts","../src/audio/MonoStereoTransformer.ts"],"sourcesContent":["export * from './biquad';\nexport * from './equalizer';\nexport * from './utils';\nexport * from './audio';\n\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const version: string = '0.1.3';\n","export const FilterType = {\n SinglePoleLowPassApprox: 0,\n SinglePoleLowPass: 1,\n LowPass: 2,\n HighPass: 3,\n BandPass: 4,\n Notch: 5,\n AllPass: 6,\n LowShelf: 7,\n HighShelf: 8,\n PeakingEQ: 9\n} as const;\n\nexport type BiquadFilters = keyof typeof FilterType | (typeof FilterType)[keyof typeof FilterType];\n\ninterface CoefficientsInit {\n a1: number;\n a2: number;\n b0: number;\n b1: number;\n b2: number;\n}\n\nexport const Q_BUTTERWORTH = Math.SQRT1_2;\n\nexport class Coefficients {\n // Denominator coefficients\n public a1 = 0;\n public a2 = 0;\n\n // Nominator coefficients\n public b0 = 0;\n public b1 = 0;\n public b2 = 0;\n\n public constructor(data?: CoefficientsInit) {\n if (data) {\n this.a1 = data.a1;\n this.a2 = data.a2;\n this.b0 = data.b0;\n this.b1 = data.b1;\n this.b2 = data.b2;\n }\n }\n\n public static from(filter: BiquadFilters, samplingFreq: number, cutoffFreq: number, Q: number, dbGain = 0) {\n if (2.0 * cutoffFreq > samplingFreq) {\n throw new Error(`Cutoff frequency is too big!`);\n }\n\n if (Q < 0) {\n throw new Error(`Q may not be negative`);\n }\n\n const omega = (2.0 * Math.PI * cutoffFreq) / samplingFreq;\n\n if (typeof filter === 'string') filter = FilterType[filter];\n\n switch (filter) {\n case FilterType.SinglePoleLowPassApprox: {\n const alpha = omega / (omega + 1.0);\n\n return new Coefficients({\n a1: alpha - 1.0,\n a2: 0.0,\n b0: alpha,\n b1: 0.0,\n b2: 0.0\n });\n }\n case FilterType.SinglePoleLowPass: {\n const omega_t = Math.tan(omega / 2.0);\n const a0 = 1.0 + omega_t;\n\n return new Coefficients({\n a1: (omega_t - 1.0) / a0,\n a2: 0.0,\n b0: omega_t / a0,\n b1: omega_t / a0,\n b2: 0.0\n });\n }\n case FilterType.LowPass: {\n const omega_s = Math.sin(omega);\n const omega_c = Math.cos(omega);\n const alpha = omega_s / (2.0 * Q);\n\n const b0 = (1.0 - omega_c) * 0.5;\n const b1 = 1.0 - omega_c;\n const b2 = (1.0 - omega_c) * 0.5;\n const a0 = 1.0 + alpha;\n const a1 = -2.0 * omega_c;\n const a2 = 1.0 - alpha;\n\n const div = 1.0 / a0;\n\n return new Coefficients({\n a1: a1 * div,\n a2: a2 * div,\n b0: b0 * div,\n b1: b1 * div,\n b2: b2 * div\n });\n }\n case FilterType.HighPass: {\n const omega_s = Math.sin(omega);\n const omega_c = Math.cos(omega);\n const alpha = omega_s / (2.0 * Q);\n\n const b0 = (1.0 + omega_c) * 0.5;\n const b1 = -(1.0 + omega_c);\n const b2 = (1.0 + omega_c) * 0.5;\n const a0 = 1.0 + alpha;\n const a1 = -2.0 * omega_c;\n const a2 = 1.0 - alpha;\n\n const div = 1.0 / a0;\n\n return new Coefficients({\n a1: a1 * div,\n a2: a2 * div,\n b0: b0 * div,\n b1: b1 * div,\n b2: b2 * div\n });\n }\n case FilterType.Notch: {\n const omega_s = Math.sin(omega);\n const omega_c = Math.cos(omega);\n const alpha = omega_s / (2.0 * Q);\n\n const b0 = 1.0;\n const b1 = -2.0 * omega_c;\n const b2 = 1.0;\n const a0 = 1.0 + alpha;\n const a1 = -2.0 * omega_c;\n const a2 = 1.0 - alpha;\n\n const div = 1.0 / a0;\n\n return new Coefficients({\n a1: a1 * div,\n a2: a2 * div,\n b0: b0 * div,\n b1: b1 * div,\n b2: b2 * div\n });\n }\n case FilterType.BandPass: {\n const omega_s = Math.sin(omega);\n const omega_c = Math.cos(omega);\n const alpha = omega_s / (2.0 * Q);\n\n const b0 = omega_s / 2.0;\n const b1 = 0;\n const b2 = -(omega_s / 2.0);\n const a0 = 1.0 + alpha;\n const a1 = -2.0 * omega_c;\n const a2 = 1.0 - alpha;\n\n const div = 1.0 / a0;\n\n return new Coefficients({\n a1: a1 * div,\n a2: a2 * div,\n b0: b0 * div,\n b1: b1 * div,\n b2: b2 * div\n });\n }\n case FilterType.AllPass: {\n const omega_s = Math.sin(omega);\n const omega_c = Math.cos(omega);\n const alpha = omega_s / (2.0 * Q);\n\n const b0 = 1.0 - alpha;\n const b1 = -2.0 * omega_c;\n const b2 = 1.0 + alpha;\n const a0 = 1.0 + alpha;\n const a1 = -2.0 * omega_c;\n const a2 = 1.0 - alpha;\n\n return new Coefficients({\n a1: a1 / a0,\n a2: a2 / a0,\n b0: b0 / a0,\n b1: b1 / a0,\n b2: b2 / a0\n });\n }\n case FilterType.LowShelf: {\n const a = Math.pow(10.0, dbGain / 40.0);\n const omega_s = Math.sin(omega);\n const omega_c = Math.cos(omega);\n const alpha = omega_s / (2.0 * Q);\n\n const b0 = a * (a + 1.0 - (a - 1.0) * omega_c + 2.0 * alpha * Math.sqrt(a));\n const b1 = 2.0 * a * (a - 1.0 - (a + 1.0) * omega_c);\n const b2 = a * (a + 1.0 - (a - 1.0) * omega_c - 2.0 * alpha * Math.sqrt(a));\n const a0 = a + 1.0 + (a - 1.0) * omega_c + 2.0 * alpha * Math.sqrt(a);\n const a1 = -2.0 * (a - 1.0 + (a + 1.0) * omega_c);\n const a2 = a + 1.0 + (a - 1.0) * omega_c - 2.0 * alpha * Math.sqrt(a);\n\n return new Coefficients({\n a1: a1 / a0,\n a2: a2 / a0,\n b0: b0 / a0,\n b1: b1 / a0,\n b2: b2 / a0\n });\n }\n case FilterType.HighShelf: {\n const a = Math.pow(10.0, dbGain / 40.0);\n const omega_s = Math.sin(omega);\n const omega_c = Math.cos(omega);\n const alpha = omega_s / (2.0 * Q);\n\n const b0 = a * (a + 1.0 + (a - 1.0) * omega_c + 2.0 * alpha * Math.sqrt(a));\n const b1 = -2.0 * a * (a - 1.0 + (a + 1.0) * omega_c);\n const b2 = a * (a + 1.0 + (a - 1.0) * omega_c - 2.0 * alpha * Math.sqrt(a));\n const a0 = a + 1.0 - (a - 1.0) * omega_c + 2.0 * alpha * Math.sqrt(a);\n const a1 = 2.0 * (a - 1.0 - (a + 1.0) * omega_c);\n const a2 = a + 1.0 - (a - 1.0) * omega_c - 2.0 * alpha * Math.sqrt(a);\n\n return new Coefficients({\n a1: a1 / a0,\n a2: a2 / a0,\n b0: b0 / a0,\n b1: b1 / a0,\n b2: b2 / a0\n });\n }\n case FilterType.PeakingEQ: {\n const a = Math.pow(10.0, dbGain / 40.0);\n const omega_s = Math.sin(omega);\n const omega_c = Math.cos(omega);\n const alpha = omega_s / (2.0 * Q);\n\n const b0 = 1.0 + alpha * a;\n const b1 = -2.0 * omega_c;\n const b2 = 1.0 - alpha * a;\n const a0 = 1.0 + alpha / a;\n const a1 = -2.0 * omega_c;\n const a2 = 1.0 - alpha / a;\n\n return new Coefficients({\n a1: a1 / a0,\n a2: a2 / a0,\n b0: b0 / a0,\n b1: b1 / a0,\n b2: b2 / a0\n });\n }\n default:\n throw new TypeError('Invalid filter type');\n }\n }\n}\n","import { BiquadFilters, Coefficients } from './Coefficients';\n\nexport interface BiquadSetFilterProps {\n f0: number;\n fs: number;\n Q: number;\n gain?: number;\n}\n\nexport class BiquadFilter {\n public x1 = 0.0;\n public x2 = 0.0;\n public y1 = 0.0;\n public y2 = 0.0;\n public s1 = 0.0;\n public s2 = 0.0;\n\n public constructor(public coefficients: Coefficients) {}\n\n public setFilter(filter: BiquadFilters, options: BiquadSetFilterProps) {\n const coefficients = Coefficients.from(filter, options.fs, options.f0, options.Q, options.gain);\n\n this.update(coefficients);\n }\n\n public update(coefficients: Coefficients) {\n this.coefficients = coefficients;\n }\n\n public replace(coefficients: Coefficients) {\n this.coefficients = coefficients;\n }\n\n public reset() {\n this.x1 = 0.0;\n this.x2 = 0.0;\n this.y1 = 0.0;\n this.y2 = 0.0;\n this.s1 = 0.0;\n this.s2 = 0.0;\n }\n\n public run(input: number) {\n const { a1, a2, b0, b1, b2 } = this.coefficients;\n\n const out = b0 * input + b1 * this.x1 + b2 * this.x2 - a1 * this.y1 - a2 * this.y2;\n\n this.x2 = this.x1;\n this.x1 = input;\n this.y2 = this.y1;\n this.y1 = out;\n\n return out;\n }\n\n public runTransposed(input: number) {\n const { a1, a2, b0, b1, b2 } = this.coefficients;\n\n const out = this.s1 + b0 * input;\n\n this.s1 = this.s2 + b1 * input - a1 * out;\n this.s2 = b2 * input - a2 * out;\n\n return out;\n }\n}\n","export class Frequency {\n public constructor(private __val: number) {\n if (typeof __val !== 'number' || isNaN(__val) || __val === Infinity) throw new TypeError('Frequency value must be a number');\n if (this.__val < 0) throw new Error(`Frequency value cannot be negative (${__val})`);\n }\n\n public khz() {\n return this.__val * 1000.0;\n }\n\n public mhz() {\n return this.__val * 1_000_000.0;\n }\n\n public hz() {\n return this.__val;\n }\n\n public dt() {\n return 1.0 / this.__val;\n }\n\n public valueOf() {\n return this.__val;\n }\n\n public toString() {\n return `${this.__val}Hz`;\n }\n\n public toJSON() {\n return this.toString();\n }\n}\n","import { Transform, TransformOptions } from 'stream';\n\nexport type PCMType = `s${16 | 32}${'l' | 'b'}e`;\n\nexport interface PCMTransformerOptions extends TransformOptions {\n type?: PCMType;\n}\n\nexport class PCMTransformer extends Transform {\n public readonly type: PCMType = 's16le';\n public bits: number;\n public bytes: number;\n public extremum: number;\n\n public constructor(options: PCMTransformerOptions = {}) {\n super(options);\n\n options.type ??= 's16le';\n\n switch (options.type) {\n case 's16be':\n case 's16le':\n this.type = options.type;\n this.bits = 16;\n break;\n case 's32be':\n case 's32le':\n this.type = options.type;\n this.bits = 32;\n break;\n default:\n throw new TypeError(`Expected type to be one of ${(['s16be', 's16le', 's32be', 's32le'] as PCMType[]).join(', ')}, got \"${options.type}\"`);\n }\n\n this.bytes = this.bits / 8;\n this.extremum = Math.pow(2, this.bits - 1);\n }\n\n public _readInt(buffer: Buffer, index: number) {\n const method = `readInt${this.type.substring(1).toUpperCase()}` as `readInt${16 | 32}${'L' | 'B'}E`;\n return buffer[method](index);\n }\n\n public _writeInt(buffer: Buffer, int: number, index: number) {\n const method = `writeInt${this.type.substring(1).toUpperCase()}` as `writeInt${16 | 32}${'L' | 'B'}E`;\n return buffer[method](int, index);\n }\n\n public clamp(val: number, max = this.extremum - 1, min = -this.extremum) {\n return Math.min(max, Math.max(min, val));\n }\n}\n","import { TransformCallback } from 'stream';\nimport { PCMTransformer, PCMTransformerOptions } from '../utils';\nimport { BiquadFilter } from './Biquad';\nimport { BiquadFilters, Coefficients, FilterType, Q_BUTTERWORTH } from './Coefficients';\n\nexport interface BiquadStreamOptions extends PCMTransformerOptions {\n disabled?: boolean;\n filter?: BiquadFilters;\n Q?: number;\n sample?: number;\n cutoff?: number;\n gain?: number;\n}\n\nexport interface BiquadFilterUpdateData {\n filter?: BiquadFilters;\n Q?: number;\n sample?: number;\n cutoff?: number;\n gain?: number;\n}\n\nexport class BiquadStream extends PCMTransformer {\n public disabled = false;\n public biquad!: BiquadFilter;\n public sample = 48000;\n public cutoff = 80;\n public gain = 0;\n public filter!: BiquadFilters;\n public Q = Q_BUTTERWORTH;\n public constructor(options: BiquadStreamOptions = {}) {\n super(options);\n\n this.disabled = !!options.disabled;\n\n if ('sample' in options) this.sample = options.sample!;\n if ('cutoff' in options) this.cutoff = options.cutoff!;\n if ('gain' in options) this.gain = options.gain!;\n if ('Q' in options) this.Q = options.Q!;\n if ('filter' in options) {\n this.filter = options.filter!;\n if (this.filter != null) {\n this.biquad = new BiquadFilter(Coefficients.from(this.filter, this.sample, this.cutoff, this.Q, this.gain));\n }\n }\n }\n\n public disable() {\n this.disabled = true;\n }\n\n public enable() {\n this.disabled = false;\n }\n\n public toggle() {\n this.disabled = !this.disabled;\n }\n\n public getFilterName() {\n if (this.filter == null) return null;\n if (typeof this.filter === 'string') return this.filter;\n return Object.entries(FilterType).find((r) => r[1] === this.filter)?.[0] as BiquadFilters;\n }\n\n public update(options: BiquadFilterUpdateData) {\n if ('sample' in options) this.sample = options.sample!;\n if ('cutoff' in options) this.cutoff = options.cutoff!;\n if ('gain' in options) this.gain = options.gain!;\n if ('Q' in options) this.Q = options.Q!;\n if ('filter' in options) this.filter = options.filter!;\n\n if (this.filter != null) {\n this.biquad = new BiquadFilter(Coefficients.from(this.filter, this.sample, this.cutoff, this.Q, this.gain));\n }\n }\n\n public setFilter(filter: BiquadFilters) {\n this.update({ filter });\n }\n\n public setQ(Q: number) {\n this.update({ Q });\n }\n\n public setSample(fs: number) {\n this.update({ sample: fs });\n }\n\n public setCutoff(f0: number) {\n this.update({ cutoff: f0 });\n }\n\n public setGain(dB: number) {\n this.update({ gain: dB });\n }\n\n public _transform(chunk: Buffer, encoding: BufferEncoding, callback: TransformCallback) {\n if (this.disabled || !this.biquad) {\n this.push(chunk);\n return callback();\n }\n\n const endIndex = Math.floor(chunk.length / 2) * 2;\n const { bytes, extremum } = this;\n\n for (let sampleIndex = 0; sampleIndex < endIndex; sampleIndex += bytes) {\n const int = this._readInt(chunk, sampleIndex);\n const result = this.biquad.run(int);\n const val = Math.min(extremum - 1, Math.max(-extremum, result));\n this._writeInt(chunk, val, sampleIndex);\n }\n\n this.push(chunk);\n return callback();\n }\n}\n","import { Equalizer } from './Equalizer';\n\nexport type ReadIntCallback = (buffer: Buffer, index: number) => number;\nexport type WriteIntCallback = (buffer: Buffer, int: number, index: number) => number;\n\nexport class ChannelProcessor {\n public history: number[];\n public bandMultipliers: number[];\n public current: number;\n public m1: number;\n public m2: number;\n\n public constructor(bandMultipliers: number[]) {\n this.history = new Array(Equalizer.BAND_COUNT * 6).fill(0);\n this.bandMultipliers = bandMultipliers;\n this.current = 0;\n this.m1 = 2;\n this.m2 = 1;\n }\n\n public process(samples: Buffer, extremum = 131072, bytes = 2, readInt?: ReadIntCallback, writeInt?: WriteIntCallback) {\n const endIndex = Math.floor(samples.length / 2) * 2;\n for (let sampleIndex = 0; sampleIndex < endIndex; sampleIndex += bytes) {\n const sample = readInt?.(samples, sampleIndex) ?? samples.readInt16LE(sampleIndex);\n let result = sample * 0.25;\n\n for (let bandIndex = 0; bandIndex < Equalizer.BAND_COUNT; bandIndex++) {\n const x = bandIndex * 6;\n const y = x + 3;\n\n const coefficients = Equalizer.Coefficients48000[bandIndex];\n\n const bandResult = coefficients.alpha * (sample - this.history[x + this.m2]) + coefficients.gamma * this.history[y + this.m1] - coefficients.beta * this.history[y + this.m2];\n\n this.history[x + this.current] = sample;\n this.history[y + this.current] = bandResult;\n\n result += bandResult * this.bandMultipliers[bandIndex];\n }\n\n const val = Math.min(extremum - 1, Math.max(-extremum, result * 4.0));\n writeInt?.(samples, val, sampleIndex) ?? samples.writeInt16LE(val, sampleIndex);\n\n if (++this.current === 3) {\n this.current = 0;\n }\n\n if (++this.m1 === 3) {\n this.m1 = 0;\n }\n\n if (++this.m2 === 3) {\n this.m2 = 0;\n }\n }\n\n return samples;\n }\n\n public reset() {\n this.history.fill(0.0);\n }\n}\n","export class EqualizerCoefficients {\n public constructor(public beta: number, public alpha: number, public gamma: number) {}\n\n public setBeta(v: number) {\n this.beta = v;\n }\n\n public setAlpha(v: number) {\n this.alpha = v;\n }\n\n public setGamma(v: number) {\n this.gamma = v;\n }\n\n public toJSON() {\n const { alpha, beta, gamma } = this;\n\n return { alpha, beta, gamma };\n }\n}\n","export class EqualizerConfiguration {\n public constructor(public bandMultipliers: number[]) {}\n\n public setGain(band: number, value: number) {\n if (this.isValidBand(band)) {\n this.bandMultipliers[band] = Math.max(Math.min(value, 1.0), -0.25);\n }\n }\n\n public getGain(band: number) {\n if (this.isValidBand(band)) {\n return this.bandMultipliers[band];\n } else {\n return 0.0;\n }\n }\n\n public isValidBand(band: number) {\n return band >= 0 && band < this.bandMultipliers.length;\n }\n}\n","import { ChannelProcessor, ReadIntCallback, WriteIntCallback } from './ChannelProcessor';\nimport { EqualizerCoefficients } from './Coefficients';\nimport { EqualizerConfiguration } from './EqualizerConfiguration';\n\nexport interface ChannelProcessorInput {\n data: Buffer;\n readInt?: ReadIntCallback;\n writeInt?: WriteIntCallback;\n extremum?: number;\n bytes?: number;\n}\n\nexport class Equalizer extends EqualizerConfiguration {\n public static BAND_COUNT = 15 as const;\n public static SAMPLE_RATE = 48000 as const;\n public static Coefficients48000 = [\n new EqualizerCoefficients(9.9847546664e-1, 7.6226668143e-4, 1.9984647656),\n new EqualizerCoefficients(9.9756184654e-1, 1.2190767289e-3, 1.9975344645),\n new EqualizerCoefficients(9.9616261379e-1, 1.9186931041e-3, 1.9960947369),\n new EqualizerCoefficients(9.9391578543e-1, 3.0421072865e-3, 1.9937449618),\n new EqualizerCoefficients(9.9028307215e-1, 4.8584639242e-3, 1.9898465702),\n new EqualizerCoefficients(9.8485897264e-1, 7.5705136795e-3, 1.9837962543),\n new EqualizerCoefficients(9.7588512657e-1, 1.2057436715e-2, 1.9731772447),\n new EqualizerCoefficients(9.6228521814e-1, 1.8857390928e-2, 1.9556164694),\n new EqualizerCoefficients(9.4080933132e-1, 2.9595334338e-2, 1.9242054384),\n new EqualizerCoefficients(9.0702059196e-1, 4.6489704022e-2, 1.8653476166),\n new EqualizerCoefficients(8.5868004289e-1, 7.0659978553e-2, 1.7600401337),\n new EqualizerCoefficients(7.8409610788e-1, 1.0795194606e-1, 1.5450725522),\n new EqualizerCoefficients(6.8332861002e-1, 1.5833569499e-1, 1.1426447155),\n new EqualizerCoefficients(5.5267518228e-1, 2.2366240886e-1, 4.0186190803e-1),\n new EqualizerCoefficients(4.1811888447e-1, 2.9094055777e-1, -7.0905944223e-1)\n ];\n public channels: ChannelProcessor[] = [];\n public channelCount: number;\n\n public constructor(channelCount: number, bandMultipliers: number[]) {\n super(bandMultipliers);\n this.channelCount = channelCount;\n this.channels = this.createChannelProcessor();\n }\n\n public createChannelProcessor() {\n return Array.from({ length: this.channelCount }, () => {\n return new ChannelProcessor(this.bandMultipliers);\n });\n }\n\n public process(input: ChannelProcessorInput[]) {\n return this.channels.map((c, i) => {\n const { data, extremum, readInt, writeInt, bytes } = input[i];\n\n return c.process(data, extremum, bytes, readInt, writeInt);\n });\n }\n}\n","import { TransformCallback } from 'stream';\nimport { PCMTransformer, PCMTransformerOptions } from '../utils';\nimport { Equalizer } from './Equalizer';\n\ninterface EqualizerStreamOptions extends PCMTransformerOptions {\n bandMultiplier?: EqualizerBand[];\n disabled?: boolean;\n channels?: number;\n}\n\nexport interface EqualizerBand {\n band: number;\n gain: number;\n}\n\nexport class EqualizerStream extends PCMTransformer {\n public disabled = false;\n public bandMultipliers: number[] = new Array(Equalizer.BAND_COUNT).fill(0);\n public equalizer: Equalizer;\n public constructor(options?: EqualizerStreamOptions) {\n super(options);\n\n options = Object.assign(\n {},\n {\n bandMultiplier: [],\n channels: 1,\n disabled: false\n },\n options || {}\n );\n\n if (options.disabled) this.disabled = !!options.disabled;\n this.equalizer = new Equalizer(options.channels || 1, this.bandMultipliers);\n if (Array.isArray(options.bandMultiplier)) this._processBands(options.bandMultiplier);\n }\n\n public _processBands(multiplier: EqualizerBand[]) {\n for (const mul of multiplier) {\n if (mul.band > Equalizer.BAND_COUNT - 1 || mul.band < 0) throw new RangeError(`Band value out of range. Expected >0 & <${Equalizer.BAND_COUNT - 1}, received \"${mul.band}\"`);\n this.equalizer.setGain(mul.band, mul.gain);\n }\n }\n\n public disable() {\n this.disabled = true;\n }\n\n public enable() {\n this.disabled = false;\n }\n\n public toggle() {\n this.disabled = !this.disabled;\n }\n\n public _transform(chunk: Buffer, encoding: BufferEncoding, callback: TransformCallback): void {\n if (this.disabled) {\n this.push(chunk);\n return callback();\n }\n\n this.equalizer.process([\n {\n data: chunk,\n extremum: this.extremum,\n readInt: (b, idx) => this._readInt(b, idx),\n writeInt: (b, i, idx) => this._writeInt(b, i, idx),\n bytes: this.bytes\n }\n ]);\n\n this.push(chunk);\n\n return callback();\n }\n\n public getEQ() {\n return this.bandMultipliers.map((m, i) => ({\n band: i,\n gain: m\n })) as EqualizerBand[];\n }\n\n public setEQ(bands: EqualizerBand[]) {\n this._processBands(bands);\n }\n\n public resetEQ() {\n this._processBands(\n Array.from(\n {\n length: Equalizer.BAND_COUNT\n },\n (_, i) => ({\n band: i,\n gain: 0\n })\n )\n );\n }\n}\n","import { TransformCallback } from 'stream';\nimport { PCMTransformer, PCMTransformerOptions } from '../utils';\n\n/*\nMono: [0, 1, 2, 3, 4, 5]\nStereo: [0, 1, 0, 1, 2, 3, 2, 3, 4, 5, 4, 5]\n*/\n\nexport type MSTStrategy = 'm2s' | 's2m';\n\nexport interface MonoStereoTransformerOptions extends PCMTransformerOptions {\n strategy: MSTStrategy;\n}\n\nexport class MonoStereoTransformer extends PCMTransformer {\n public disabled = false;\n public strategy: MSTStrategy;\n\n public constructor(options?: MonoStereoTransformerOptions) {\n super(options);\n if (!['m2s', 's2m'].includes(options?.strategy as MSTStrategy)) {\n throw new TypeError(`Strategy must be \"m2s\" or \"s2m\"`);\n }\n\n this.strategy = options!.strategy;\n }\n\n public disable() {\n this.disabled = true;\n }\n\n public enable() {\n this.disabled = false;\n }\n\n public toggle() {\n this.disabled = !this.disabled;\n }\n\n public setStrategy(strategy: MSTStrategy) {\n this.strategy = strategy;\n }\n\n public _transform(chunk: Buffer, encoding: BufferEncoding, callback: TransformCallback): void {\n if (this.disabled) {\n this.push(chunk);\n return callback();\n }\n\n const len = Math.floor(chunk.length / 2) * 2;\n\n if (this.strategy === 'm2s') {\n this.push(this.toStereo(chunk, len));\n } else {\n this.push(this.toMono(chunk, len));\n }\n\n return callback();\n }\n\n public toStereo(sample: Buffer, len: number) {\n const bytes = this.bytes;\n const stereoBuffer = Buffer.alloc(len * 2);\n\n for (let i = 0; i < len; i += bytes) {\n stereoBuffer[i * 2 + 0] = sample[i];\n stereoBuffer[i * 2 + 1] = sample[i + 1];\n stereoBuffer[i * 2 + 2] = sample[i];\n stereoBuffer[i * 2 + 3] = sample[i + 1];\n }\n\n return stereoBuffer;\n }\n\n public toMono(sample: Buffer, len: number) {\n const bytes = this.bytes;\n const monoBuffer = Buffer.alloc(Math.floor(len / 2));\n\n for (let i = 0; i < len; i += bytes) {\n monoBuffer[i] = sample[i * 2 + 0];\n monoBuffer[i + 1] = sample[i * 2 + 1];\n }\n\n return monoBuffer;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAO,IAAM,aAAa;AAAA,EACtB,yBAAyB;AAAA,EACzB,mBAAmB;AAAA,EACnB,SAAS;AAAA,EACT,UAAU;AAAA,EACV,UAAU;AAAA,EACV,OAAO;AAAA,EACP,SAAS;AAAA,EACT,UAAU;AAAA,EACV,WAAW;AAAA,EACX,WAAW;AACf;AAYO,IAAM,gBAAgB,KAAK;AAE3B,IAAM,eAAN,MAAmB;AAAA,EAUf,YAAY,MAAyB;AAR5C,SAAO,KAAK;AACZ,SAAO,KAAK;AAGZ,SAAO,KAAK;AACZ,SAAO,KAAK;AACZ,SAAO,KAAK;AAGR,QAAI,MAAM;AACN,WAAK,KAAK,KAAK;AACf,WAAK,KAAK,KAAK;AACf,WAAK,KAAK,KAAK;AACf,WAAK,KAAK,KAAK;AACf,WAAK,KAAK,KAAK;AAAA,IACnB;AAAA,EACJ;AAAA,EAEA,OAAc,KAAK,QAAuB,cAAsB,YAAoB,GAAW,SAAS,GAAG;AACvG,QAAI,IAAM,aAAa,cAAc;AACjC,YAAM,IAAI,MAAM,8BAA8B;AAAA,IAClD;AAEA,QAAI,IAAI,GAAG;AACP,YAAM,IAAI,MAAM,uBAAuB;AAAA,IAC3C;AAEA,UAAM,QAAS,IAAM,KAAK,KAAK,aAAc;AAE7C,QAAI,OAAO,WAAW;AAAU,eAAS,WAAW;AAEpD,YAAQ,QAAQ;AAAA,MACZ,KAAK,WAAW,yBAAyB;AACrC,cAAM,QAAQ,SAAS,QAAQ;AAE/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,WAAK,KAAK,KAAK,SAAS,OAAO,GAAG,CAAC;AAAA,IACvC,OAAO;AACH,WAAK,KAAK,KAAK,OAAO,OAAO,GAAG,CAAC;AAAA,IACrC;AAEA,WAAO,SAAS;AAAA,EACpB;AAAA,EAEO,SAAS,QAAgB,KAAa;AACzC,UAAM,QAAQ,KAAK;AACnB,UAAM,eAAe,OAAO,MAAM,MAAM,CAAC;AAEzC,aAAS,IAAI,GAAG,IAAI,KAAK,KAAK,OAAO;AACjC,mBAAa,IAAI,IAAI,KAAK,OAAO;AACjC,mBAAa,IAAI,IAAI,KAAK,OAAO,IAAI;AACrC,mBAAa,IAAI,IAAI,KAAK,OAAO;AACjC,mBAAa,IAAI,IAAI,KAAK,OAAO,IAAI;AAAA,IACzC;AAEA,WAAO;AAAA,EACX;AAAA,EAEO,OAAO,QAAgB,KAAa;AACvC,UAAM,QAAQ,KAAK;AACnB,UAAM,aAAa,OAAO,MAAM,KAAK,MAAM,MAAM,CAAC,CAAC;AAEnD,aAAS,IAAI,GAAG,IAAI,KAAK,KAAK,OAAO;AACjC,iBAAW,KAAK,OAAO,IAAI,IAAI;AAC/B,iBAAW,IAAI,KAAK,OAAO,IAAI,IAAI;AAAA,IACvC;AAEA,WAAO;AAAA,EACX;AACJ;AAvEa;;;AXRN,IAAM,UAAkB;","names":[]} \ No newline at end of file diff --git a/node_modules/@discord-player/equalizer/dist/index.mjs b/node_modules/@discord-player/equalizer/dist/index.mjs deleted file mode 100644 index 71f5f5b..0000000 --- a/node_modules/@discord-player/equalizer/dist/index.mjs +++ /dev/null @@ -1,717 +0,0 @@ -var __defProp = Object.defineProperty; -var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); - -// src/biquad/Coefficients.ts -var FilterType = { - SinglePoleLowPassApprox: 0, - SinglePoleLowPass: 1, - LowPass: 2, - HighPass: 3, - BandPass: 4, - Notch: 5, - AllPass: 6, - LowShelf: 7, - HighShelf: 8, - PeakingEQ: 9 -}; -var Q_BUTTERWORTH = Math.SQRT1_2; -var Coefficients = class { - constructor(data) { - this.a1 = 0; - this.a2 = 0; - this.b0 = 0; - this.b1 = 0; - this.b2 = 0; - if (data) { - this.a1 = data.a1; - this.a2 = data.a2; - this.b0 = data.b0; - this.b1 = data.b1; - this.b2 = data.b2; - } - } - static from(filter, samplingFreq, cutoffFreq, Q, dbGain = 0) { - if (2 * cutoffFreq > samplingFreq) { - throw new Error(`Cutoff frequency is too big!`); - } - if (Q < 0) { - throw new Error(`Q may not be negative`); - } - const omega = 2 * Math.PI * cutoffFreq / samplingFreq; - if (typeof filter === "string") - filter = FilterType[filter]; - switch (filter) { - case FilterType.SinglePoleLowPassApprox: { - const alpha = omega / (omega + 1); - return new Coefficients({ - a1: alpha - 1, - a2: 0, - b0: alpha, - b1: 0, - b2: 0 - }); - } - case FilterType.SinglePoleLowPass: { - const omega_t = Math.tan(omega / 2); - const a0 = 1 + omega_t; - return new Coefficients({ - a1: (omega_t - 1) / a0, - a2: 0, - b0: omega_t / a0, - b1: omega_t / a0, - b2: 0 - }); - } - case FilterType.LowPass: { - const omega_s = Math.sin(omega); - const omega_c = Math.cos(omega); - const alpha = omega_s / (2 * Q); - const b0 = (1 - omega_c) * 0.5; - const b1 = 1 - omega_c; - const b2 = (1 - omega_c) * 0.5; - const a0 = 1 + alpha; - const a1 = -2 * omega_c; - const a2 = 1 - alpha; - const div = 1 / a0; - return new Coefficients({ - a1: a1 * div, - a2: a2 * div, - b0: b0 * div, - b1: b1 * div, - b2: b2 * div - }); - } - case FilterType.HighPass: { - const omega_s = Math.sin(omega); - const omega_c = Math.cos(omega); - const alpha = omega_s / (2 * Q); - const b0 = (1 + omega_c) * 0.5; - const b1 = -(1 + omega_c); - const b2 = (1 + omega_c) * 0.5; - const a0 = 1 + alpha; - const a1 = -2 * omega_c; - const a2 = 1 - alpha; - const div = 1 / a0; - return new Coefficients({ - a1: a1 * div, - a2: a2 * div, - b0: b0 * div, - b1: b1 * div, - b2: b2 * div - }); - } - case FilterType.Notch: { - const omega_s = Math.sin(omega); - const omega_c = Math.cos(omega); - const alpha = omega_s / (2 * Q); - const b0 = 1; - const b1 = -2 * omega_c; - const b2 = 1; - const a0 = 1 + alpha; - const a1 = -2 * omega_c; - const a2 = 1 - alpha; - const div = 1 / a0; - return new Coefficients({ - a1: a1 * div, - a2: a2 * div, - b0: b0 * div, - b1: b1 * div, - b2: b2 * div - }); - } - case FilterType.BandPass: { - const omega_s = Math.sin(omega); - const omega_c = Math.cos(omega); - const alpha = omega_s / (2 * Q); - const b0 = omega_s / 2; - const b1 = 0; - const b2 = -(omega_s / 2); - const a0 = 1 + alpha; - const a1 = -2 * omega_c; - const a2 = 1 - alpha; - const div = 1 / a0; - return new Coefficients({ - a1: a1 * div, - a2: a2 * div, - b0: b0 * div, - b1: b1 * div, - b2: b2 * div - }); - } - case FilterType.AllPass: { - const omega_s = Math.sin(omega); - const omega_c = Math.cos(omega); - const alpha = omega_s / (2 * Q); - const b0 = 1 - alpha; - const b1 = -2 * omega_c; - const b2 = 1 + alpha; - const a0 = 1 + alpha; - const a1 = -2 * omega_c; - const a2 = 1 - alpha; - return new Coefficients({ - a1: a1 / a0, - a2: a2 / a0, - b0: b0 / a0, - b1: b1 / a0, - b2: b2 / a0 - }); - } - case FilterType.LowShelf: { - const a = Math.pow(10, dbGain / 40); - const omega_s = Math.sin(omega); - const omega_c = Math.cos(omega); - const alpha = omega_s / (2 * Q); - const b0 = a * (a + 1 - (a - 1) * omega_c + 2 * alpha * Math.sqrt(a)); - const b1 = 2 * a * (a - 1 - (a + 1) * omega_c); - const b2 = a * (a + 1 - (a - 1) * omega_c - 2 * alpha * Math.sqrt(a)); - const a0 = a + 1 + (a - 1) * omega_c + 2 * alpha * Math.sqrt(a); - const a1 = -2 * (a - 1 + (a + 1) * omega_c); - const a2 = a + 1 + (a - 1) * omega_c - 2 * alpha * Math.sqrt(a); - return new Coefficients({ - a1: a1 / a0, - a2: a2 / a0, - b0: b0 / a0, - b1: b1 / a0, - b2: b2 / a0 - }); - } - case FilterType.HighShelf: { - const a = Math.pow(10, dbGain / 40); - const omega_s = Math.sin(omega); - const omega_c = Math.cos(omega); - const alpha = omega_s / (2 * Q); - const b0 = a * (a + 1 + (a - 1) * omega_c + 2 * alpha * Math.sqrt(a)); - const b1 = -2 * a * (a - 1 + (a + 1) * omega_c); - const b2 = a * (a + 1 + (a - 1) * omega_c - 2 * alpha * Math.sqrt(a)); - const a0 = a + 1 - (a - 1) * omega_c + 2 * alpha * Math.sqrt(a); - const a1 = 2 * (a - 1 - (a + 1) * omega_c); - const a2 = a + 1 - (a - 1) * omega_c - 2 * alpha * Math.sqrt(a); - return new Coefficients({ - a1: a1 / a0, - a2: a2 / a0, - b0: b0 / a0, - b1: b1 / a0, - b2: b2 / a0 - }); - } - case FilterType.PeakingEQ: { - const a = Math.pow(10, dbGain / 40); - const omega_s = Math.sin(omega); - const omega_c = Math.cos(omega); - const alpha = omega_s / (2 * Q); - const b0 = 1 + alpha * a; - const b1 = -2 * omega_c; - const b2 = 1 - alpha * a; - const a0 = 1 + alpha / a; - const a1 = -2 * omega_c; - const a2 = 1 - alpha / a; - return new Coefficients({ - a1: a1 / a0, - a2: a2 / a0, - b0: b0 / a0, - b1: b1 / a0, - b2: b2 / a0 - }); - } - default: - throw new TypeError("Invalid filter type"); - } - } -}; -__name(Coefficients, "Coefficients"); - -// src/biquad/Biquad.ts -var BiquadFilter = class { - constructor(coefficients) { - this.coefficients = coefficients; - this.x1 = 0; - this.x2 = 0; - this.y1 = 0; - this.y2 = 0; - this.s1 = 0; - this.s2 = 0; - } - setFilter(filter, options) { - const coefficients = Coefficients.from(filter, options.fs, options.f0, options.Q, options.gain); - this.update(coefficients); - } - update(coefficients) { - this.coefficients = coefficients; - } - replace(coefficients) { - this.coefficients = coefficients; - } - reset() { - this.x1 = 0; - this.x2 = 0; - this.y1 = 0; - this.y2 = 0; - this.s1 = 0; - this.s2 = 0; - } - run(input) { - const { a1, a2, b0, b1, b2 } = this.coefficients; - const out = b0 * input + b1 * this.x1 + b2 * this.x2 - a1 * this.y1 - a2 * this.y2; - this.x2 = this.x1; - this.x1 = input; - this.y2 = this.y1; - this.y1 = out; - return out; - } - runTransposed(input) { - const { a1, a2, b0, b1, b2 } = this.coefficients; - const out = this.s1 + b0 * input; - this.s1 = this.s2 + b1 * input - a1 * out; - this.s2 = b2 * input - a2 * out; - return out; - } -}; -__name(BiquadFilter, "BiquadFilter"); - -// src/utils/Frequency.ts -var Frequency = class { - constructor(__val) { - this.__val = __val; - if (typeof __val !== "number" || isNaN(__val) || __val === Infinity) - throw new TypeError("Frequency value must be a number"); - if (this.__val < 0) - throw new Error(`Frequency value cannot be negative (${__val})`); - } - khz() { - return this.__val * 1e3; - } - mhz() { - return this.__val * 1e6; - } - hz() { - return this.__val; - } - dt() { - return 1 / this.__val; - } - valueOf() { - return this.__val; - } - toString() { - return `${this.__val}Hz`; - } - toJSON() { - return this.toString(); - } -}; -__name(Frequency, "Frequency"); - -// src/utils/PCMTransformer.ts -import { Transform } from "stream"; -var PCMTransformer = class extends Transform { - constructor(options = {}) { - super(options); - this.type = "s16le"; - options.type ?? (options.type = "s16le"); - switch (options.type) { - case "s16be": - case "s16le": - this.type = options.type; - this.bits = 16; - break; - case "s32be": - case "s32le": - this.type = options.type; - this.bits = 32; - break; - default: - throw new TypeError(`Expected type to be one of ${["s16be", "s16le", "s32be", "s32le"].join(", ")}, got "${options.type}"`); - } - this.bytes = this.bits / 8; - this.extremum = Math.pow(2, this.bits - 1); - } - _readInt(buffer, index) { - const method = `readInt${this.type.substring(1).toUpperCase()}`; - return buffer[method](index); - } - _writeInt(buffer, int, index) { - const method = `writeInt${this.type.substring(1).toUpperCase()}`; - return buffer[method](int, index); - } - clamp(val, max = this.extremum - 1, min = -this.extremum) { - return Math.min(max, Math.max(min, val)); - } -}; -__name(PCMTransformer, "PCMTransformer"); - -// src/biquad/BiquadStream.ts -var BiquadStream = class extends PCMTransformer { - constructor(options = {}) { - super(options); - this.disabled = false; - this.sample = 48e3; - this.cutoff = 80; - this.gain = 0; - this.Q = Q_BUTTERWORTH; - this.disabled = !!options.disabled; - if ("sample" in options) - this.sample = options.sample; - if ("cutoff" in options) - this.cutoff = options.cutoff; - if ("gain" in options) - this.gain = options.gain; - if ("Q" in options) - this.Q = options.Q; - if ("filter" in options) { - this.filter = options.filter; - if (this.filter != null) { - this.biquad = new BiquadFilter(Coefficients.from(this.filter, this.sample, this.cutoff, this.Q, this.gain)); - } - } - } - disable() { - this.disabled = true; - } - enable() { - this.disabled = false; - } - toggle() { - this.disabled = !this.disabled; - } - getFilterName() { - if (this.filter == null) - return null; - if (typeof this.filter === "string") - return this.filter; - return Object.entries(FilterType).find((r) => r[1] === this.filter)?.[0]; - } - update(options) { - if ("sample" in options) - this.sample = options.sample; - if ("cutoff" in options) - this.cutoff = options.cutoff; - if ("gain" in options) - this.gain = options.gain; - if ("Q" in options) - this.Q = options.Q; - if ("filter" in options) - this.filter = options.filter; - if (this.filter != null) { - this.biquad = new BiquadFilter(Coefficients.from(this.filter, this.sample, this.cutoff, this.Q, this.gain)); - } - } - setFilter(filter) { - this.update({ filter }); - } - setQ(Q) { - this.update({ Q }); - } - setSample(fs) { - this.update({ sample: fs }); - } - setCutoff(f0) { - this.update({ cutoff: f0 }); - } - setGain(dB) { - this.update({ gain: dB }); - } - _transform(chunk, encoding, callback) { - if (this.disabled || !this.biquad) { - this.push(chunk); - return callback(); - } - const endIndex = Math.floor(chunk.length / 2) * 2; - const { bytes, extremum } = this; - for (let sampleIndex = 0; sampleIndex < endIndex; sampleIndex += bytes) { - const int = this._readInt(chunk, sampleIndex); - const result = this.biquad.run(int); - const val = Math.min(extremum - 1, Math.max(-extremum, result)); - this._writeInt(chunk, val, sampleIndex); - } - this.push(chunk); - return callback(); - } -}; -__name(BiquadStream, "BiquadStream"); - -// src/equalizer/ChannelProcessor.ts -var ChannelProcessor = class { - constructor(bandMultipliers) { - this.history = new Array(Equalizer.BAND_COUNT * 6).fill(0); - this.bandMultipliers = bandMultipliers; - this.current = 0; - this.m1 = 2; - this.m2 = 1; - } - process(samples, extremum = 131072, bytes = 2, readInt, writeInt) { - const endIndex = Math.floor(samples.length / 2) * 2; - for (let sampleIndex = 0; sampleIndex < endIndex; sampleIndex += bytes) { - const sample = readInt?.(samples, sampleIndex) ?? samples.readInt16LE(sampleIndex); - let result = sample * 0.25; - for (let bandIndex = 0; bandIndex < Equalizer.BAND_COUNT; bandIndex++) { - const x = bandIndex * 6; - const y = x + 3; - const coefficients = Equalizer.Coefficients48000[bandIndex]; - const bandResult = coefficients.alpha * (sample - this.history[x + this.m2]) + coefficients.gamma * this.history[y + this.m1] - coefficients.beta * this.history[y + this.m2]; - this.history[x + this.current] = sample; - this.history[y + this.current] = bandResult; - result += bandResult * this.bandMultipliers[bandIndex]; - } - const val = Math.min(extremum - 1, Math.max(-extremum, result * 4)); - writeInt?.(samples, val, sampleIndex) ?? samples.writeInt16LE(val, sampleIndex); - if (++this.current === 3) { - this.current = 0; - } - if (++this.m1 === 3) { - this.m1 = 0; - } - if (++this.m2 === 3) { - this.m2 = 0; - } - } - return samples; - } - reset() { - this.history.fill(0); - } -}; -__name(ChannelProcessor, "ChannelProcessor"); - -// src/equalizer/Coefficients.ts -var EqualizerCoefficients = class { - constructor(beta, alpha, gamma) { - this.beta = beta; - this.alpha = alpha; - this.gamma = gamma; - } - setBeta(v) { - this.beta = v; - } - setAlpha(v) { - this.alpha = v; - } - setGamma(v) { - this.gamma = v; - } - toJSON() { - const { alpha, beta, gamma } = this; - return { alpha, beta, gamma }; - } -}; -__name(EqualizerCoefficients, "EqualizerCoefficients"); - -// src/equalizer/EqualizerConfiguration.ts -var EqualizerConfiguration = class { - constructor(bandMultipliers) { - this.bandMultipliers = bandMultipliers; - } - setGain(band, value) { - if (this.isValidBand(band)) { - this.bandMultipliers[band] = Math.max(Math.min(value, 1), -0.25); - } - } - getGain(band) { - if (this.isValidBand(band)) { - return this.bandMultipliers[band]; - } else { - return 0; - } - } - isValidBand(band) { - return band >= 0 && band < this.bandMultipliers.length; - } -}; -__name(EqualizerConfiguration, "EqualizerConfiguration"); - -// src/equalizer/Equalizer.ts -var Equalizer = class extends EqualizerConfiguration { - constructor(channelCount, bandMultipliers) { - super(bandMultipliers); - this.channels = []; - this.channelCount = channelCount; - this.channels = this.createChannelProcessor(); - } - createChannelProcessor() { - return Array.from({ length: this.channelCount }, () => { - return new ChannelProcessor(this.bandMultipliers); - }); - } - process(input) { - return this.channels.map((c, i) => { - const { data, extremum, readInt, writeInt, bytes } = input[i]; - return c.process(data, extremum, bytes, readInt, writeInt); - }); - } -}; -__name(Equalizer, "Equalizer"); -Equalizer.BAND_COUNT = 15; -Equalizer.SAMPLE_RATE = 48e3; -Equalizer.Coefficients48000 = [ - new EqualizerCoefficients(0.99847546664, 76226668143e-14, 1.9984647656), - new EqualizerCoefficients(0.99756184654, 0.0012190767289, 1.9975344645), - new EqualizerCoefficients(0.99616261379, 0.0019186931041, 1.9960947369), - new EqualizerCoefficients(0.99391578543, 0.0030421072865, 1.9937449618), - new EqualizerCoefficients(0.99028307215, 0.0048584639242, 1.9898465702), - new EqualizerCoefficients(0.98485897264, 0.0075705136795, 1.9837962543), - new EqualizerCoefficients(0.97588512657, 0.012057436715, 1.9731772447), - new EqualizerCoefficients(0.96228521814, 0.018857390928, 1.9556164694), - new EqualizerCoefficients(0.94080933132, 0.029595334338, 1.9242054384), - new EqualizerCoefficients(0.90702059196, 0.046489704022, 1.8653476166), - new EqualizerCoefficients(0.85868004289, 0.070659978553, 1.7600401337), - new EqualizerCoefficients(0.78409610788, 0.10795194606, 1.5450725522), - new EqualizerCoefficients(0.68332861002, 0.15833569499, 1.1426447155), - new EqualizerCoefficients(0.55267518228, 0.22366240886, 0.40186190803), - new EqualizerCoefficients(0.41811888447, 0.29094055777, -0.70905944223) -]; - -// src/equalizer/EqualizerStream.ts -var EqualizerStream = class extends PCMTransformer { - constructor(options) { - super(options); - this.disabled = false; - this.bandMultipliers = new Array(Equalizer.BAND_COUNT).fill(0); - options = Object.assign( - {}, - { - bandMultiplier: [], - channels: 1, - disabled: false - }, - options || {} - ); - if (options.disabled) - this.disabled = !!options.disabled; - this.equalizer = new Equalizer(options.channels || 1, this.bandMultipliers); - if (Array.isArray(options.bandMultiplier)) - this._processBands(options.bandMultiplier); - } - _processBands(multiplier) { - for (const mul of multiplier) { - if (mul.band > Equalizer.BAND_COUNT - 1 || mul.band < 0) - throw new RangeError(`Band value out of range. Expected >0 & <${Equalizer.BAND_COUNT - 1}, received "${mul.band}"`); - this.equalizer.setGain(mul.band, mul.gain); - } - } - disable() { - this.disabled = true; - } - enable() { - this.disabled = false; - } - toggle() { - this.disabled = !this.disabled; - } - _transform(chunk, encoding, callback) { - if (this.disabled) { - this.push(chunk); - return callback(); - } - this.equalizer.process([ - { - data: chunk, - extremum: this.extremum, - readInt: (b, idx) => this._readInt(b, idx), - writeInt: (b, i, idx) => this._writeInt(b, i, idx), - bytes: this.bytes - } - ]); - this.push(chunk); - return callback(); - } - getEQ() { - return this.bandMultipliers.map((m, i) => ({ - band: i, - gain: m - })); - } - setEQ(bands) { - this._processBands(bands); - } - resetEQ() { - this._processBands( - Array.from( - { - length: Equalizer.BAND_COUNT - }, - (_, i) => ({ - band: i, - gain: 0 - }) - ) - ); - } -}; -__name(EqualizerStream, "EqualizerStream"); - -// src/audio/MonoStereoTransformer.ts -var MonoStereoTransformer = class extends PCMTransformer { - constructor(options) { - super(options); - this.disabled = false; - if (!["m2s", "s2m"].includes(options?.strategy)) { - throw new TypeError(`Strategy must be "m2s" or "s2m"`); - } - this.strategy = options.strategy; - } - disable() { - this.disabled = true; - } - enable() { - this.disabled = false; - } - toggle() { - this.disabled = !this.disabled; - } - setStrategy(strategy) { - this.strategy = strategy; - } - _transform(chunk, encoding, callback) { - if (this.disabled) { - this.push(chunk); - return callback(); - } - const len = Math.floor(chunk.length / 2) * 2; - if (this.strategy === "m2s") { - this.push(this.toStereo(chunk, len)); - } else { - this.push(this.toMono(chunk, len)); - } - return callback(); - } - toStereo(sample, len) { - const bytes = this.bytes; - const stereoBuffer = Buffer.alloc(len * 2); - for (let i = 0; i < len; i += bytes) { - stereoBuffer[i * 2 + 0] = sample[i]; - stereoBuffer[i * 2 + 1] = sample[i + 1]; - stereoBuffer[i * 2 + 2] = sample[i]; - stereoBuffer[i * 2 + 3] = sample[i + 1]; - } - return stereoBuffer; - } - toMono(sample, len) { - const bytes = this.bytes; - const monoBuffer = Buffer.alloc(Math.floor(len / 2)); - for (let i = 0; i < len; i += bytes) { - monoBuffer[i] = sample[i * 2 + 0]; - monoBuffer[i + 1] = sample[i * 2 + 1]; - } - return monoBuffer; - } -}; -__name(MonoStereoTransformer, "MonoStereoTransformer"); - -// src/index.ts -var version = "0.1.3"; -export { - BiquadFilter, - BiquadStream, - ChannelProcessor, - Coefficients, - Equalizer, - EqualizerCoefficients, - EqualizerConfiguration, - EqualizerStream, - FilterType, - Frequency, - MonoStereoTransformer, - PCMTransformer, - Q_BUTTERWORTH, - version -}; -//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@discord-player/equalizer/dist/index.mjs.map b/node_modules/@discord-player/equalizer/dist/index.mjs.map deleted file mode 100644 index 1173559..0000000 --- a/node_modules/@discord-player/equalizer/dist/index.mjs.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["../src/biquad/Coefficients.ts","../src/biquad/Biquad.ts","../src/utils/Frequency.ts","../src/utils/PCMTransformer.ts","../src/biquad/BiquadStream.ts","../src/equalizer/ChannelProcessor.ts","../src/equalizer/Coefficients.ts","../src/equalizer/EqualizerConfiguration.ts","../src/equalizer/Equalizer.ts","../src/equalizer/EqualizerStream.ts","../src/audio/MonoStereoTransformer.ts","../src/index.ts"],"sourcesContent":["export const FilterType = {\n SinglePoleLowPassApprox: 0,\n SinglePoleLowPass: 1,\n LowPass: 2,\n HighPass: 3,\n BandPass: 4,\n Notch: 5,\n AllPass: 6,\n LowShelf: 7,\n HighShelf: 8,\n PeakingEQ: 9\n} as const;\n\nexport type BiquadFilters = keyof typeof FilterType | (typeof FilterType)[keyof typeof FilterType];\n\ninterface CoefficientsInit {\n a1: number;\n a2: number;\n b0: number;\n b1: number;\n b2: number;\n}\n\nexport const Q_BUTTERWORTH = Math.SQRT1_2;\n\nexport class Coefficients {\n // Denominator coefficients\n public a1 = 0;\n public a2 = 0;\n\n // Nominator coefficients\n public b0 = 0;\n public b1 = 0;\n public b2 = 0;\n\n public constructor(data?: CoefficientsInit) {\n if (data) {\n this.a1 = data.a1;\n this.a2 = data.a2;\n this.b0 = data.b0;\n this.b1 = data.b1;\n this.b2 = data.b2;\n }\n }\n\n public static from(filter: BiquadFilters, samplingFreq: number, cutoffFreq: number, Q: number, dbGain = 0) {\n if (2.0 * cutoffFreq > samplingFreq) {\n throw new Error(`Cutoff frequency is too big!`);\n }\n\n if (Q < 0) {\n throw new Error(`Q may not be negative`);\n }\n\n const omega = (2.0 * Math.PI * cutoffFreq) / samplingFreq;\n\n if (typeof filter === 'string') filter = FilterType[filter];\n\n switch (filter) {\n case FilterType.SinglePoleLowPassApprox: {\n const alpha = omega / (omega + 1.0);\n\n return new Coefficients({\n a1: alpha - 1.0,\n a2: 0.0,\n b0: alpha,\n b1: 0.0,\n b2: 0.0\n });\n }\n case FilterType.SinglePoleLowPass: {\n const omega_t = Math.tan(omega / 2.0);\n const a0 = 1.0 + omega_t;\n\n return new Coefficients({\n a1: (omega_t - 1.0) / a0,\n a2: 0.0,\n b0: omega_t / a0,\n b1: omega_t / a0,\n b2: 0.0\n });\n }\n case FilterType.LowPass: {\n const omega_s = Math.sin(omega);\n const omega_c = Math.cos(omega);\n const alpha = omega_s / (2.0 * Q);\n\n const b0 = (1.0 - omega_c) * 0.5;\n const b1 = 1.0 - omega_c;\n const b2 = (1.0 - omega_c) * 0.5;\n const a0 = 1.0 + alpha;\n const a1 = -2.0 * omega_c;\n const a2 = 1.0 - alpha;\n\n const div = 1.0 / a0;\n\n return new Coefficients({\n a1: a1 * div,\n a2: a2 * div,\n b0: b0 * div,\n b1: b1 * div,\n b2: b2 * div\n });\n }\n case FilterType.HighPass: {\n const omega_s = Math.sin(omega);\n const omega_c = Math.cos(omega);\n const alpha = omega_s / (2.0 * Q);\n\n const b0 = (1.0 + omega_c) * 0.5;\n const b1 = -(1.0 + omega_c);\n const b2 = (1.0 + omega_c) * 0.5;\n const a0 = 1.0 + alpha;\n const a1 = -2.0 * omega_c;\n const a2 = 1.0 - alpha;\n\n const div = 1.0 / a0;\n\n return new Coefficients({\n a1: a1 * div,\n a2: a2 * div,\n b0: b0 * div,\n b1: b1 * div,\n b2: b2 * div\n });\n }\n case FilterType.Notch: {\n const omega_s = Math.sin(omega);\n const omega_c = Math.cos(omega);\n const alpha = omega_s / (2.0 * Q);\n\n const b0 = 1.0;\n const b1 = -2.0 * omega_c;\n const b2 = 1.0;\n const a0 = 1.0 + alpha;\n const a1 = -2.0 * omega_c;\n const a2 = 1.0 - alpha;\n\n const div = 1.0 / a0;\n\n return new Coefficients({\n a1: a1 * div,\n a2: a2 * div,\n b0: b0 * div,\n b1: b1 * div,\n b2: b2 * div\n });\n }\n case FilterType.BandPass: {\n const omega_s = Math.sin(omega);\n const omega_c = Math.cos(omega);\n const alpha = omega_s / (2.0 * Q);\n\n const b0 = omega_s / 2.0;\n const b1 = 0;\n const b2 = -(omega_s / 2.0);\n const a0 = 1.0 + alpha;\n const a1 = -2.0 * omega_c;\n const a2 = 1.0 - alpha;\n\n const div = 1.0 / a0;\n\n return new Coefficients({\n a1: a1 * div,\n a2: a2 * div,\n b0: b0 * div,\n b1: b1 * div,\n b2: b2 * div\n });\n }\n case FilterType.AllPass: {\n const omega_s = Math.sin(omega);\n const omega_c = Math.cos(omega);\n const alpha = omega_s / (2.0 * Q);\n\n const b0 = 1.0 - alpha;\n const b1 = -2.0 * omega_c;\n const b2 = 1.0 + alpha;\n const a0 = 1.0 + alpha;\n const a1 = -2.0 * omega_c;\n const a2 = 1.0 - alpha;\n\n return new Coefficients({\n a1: a1 / a0,\n a2: a2 / a0,\n b0: b0 / a0,\n b1: b1 / a0,\n b2: b2 / a0\n });\n }\n case FilterType.LowShelf: {\n const a = Math.pow(10.0, dbGain / 40.0);\n const omega_s = Math.sin(omega);\n const omega_c = Math.cos(omega);\n const alpha = omega_s / (2.0 * Q);\n\n const b0 = a * (a + 1.0 - (a - 1.0) * omega_c + 2.0 * alpha * Math.sqrt(a));\n const b1 = 2.0 * a * (a - 1.0 - (a + 1.0) * omega_c);\n const b2 = a * (a + 1.0 - (a - 1.0) * omega_c - 2.0 * alpha * Math.sqrt(a));\n const a0 = a + 1.0 + (a - 1.0) * omega_c + 2.0 * alpha * Math.sqrt(a);\n const a1 = -2.0 * (a - 1.0 + (a + 1.0) * omega_c);\n const a2 = a + 1.0 + (a - 1.0) * omega_c - 2.0 * alpha * Math.sqrt(a);\n\n return new Coefficients({\n a1: a1 / a0,\n a2: a2 / a0,\n b0: b0 / a0,\n b1: b1 / a0,\n b2: b2 / a0\n });\n }\n case FilterType.HighShelf: {\n const a = Math.pow(10.0, dbGain / 40.0);\n const omega_s = Math.sin(omega);\n const omega_c = Math.cos(omega);\n const alpha = omega_s / (2.0 * Q);\n\n const b0 = a * (a + 1.0 + (a - 1.0) * omega_c + 2.0 * alpha * Math.sqrt(a));\n const b1 = -2.0 * a * (a - 1.0 + (a + 1.0) * omega_c);\n const b2 = a * (a + 1.0 + (a - 1.0) * omega_c - 2.0 * alpha * Math.sqrt(a));\n const a0 = a + 1.0 - (a - 1.0) * omega_c + 2.0 * alpha * Math.sqrt(a);\n const a1 = 2.0 * (a - 1.0 - (a + 1.0) * omega_c);\n const a2 = a + 1.0 - (a - 1.0) * omega_c - 2.0 * alpha * Math.sqrt(a);\n\n return new Coefficients({\n a1: a1 / a0,\n a2: a2 / a0,\n b0: b0 / a0,\n b1: b1 / a0,\n b2: b2 / a0\n });\n }\n case FilterType.PeakingEQ: {\n const a = Math.pow(10.0, dbGain / 40.0);\n const omega_s = Math.sin(omega);\n const omega_c = Math.cos(omega);\n const alpha = omega_s / (2.0 * Q);\n\n const b0 = 1.0 + alpha * a;\n const b1 = -2.0 * omega_c;\n const b2 = 1.0 - alpha * a;\n const a0 = 1.0 + alpha / a;\n const a1 = -2.0 * omega_c;\n const a2 = 1.0 - alpha / a;\n\n return new Coefficients({\n a1: a1 / a0,\n a2: a2 / a0,\n b0: b0 / a0,\n b1: b1 / a0,\n b2: b2 / a0\n });\n }\n default:\n throw new TypeError('Invalid filter type');\n }\n }\n}\n","import { BiquadFilters, Coefficients } from './Coefficients';\n\nexport interface BiquadSetFilterProps {\n f0: number;\n fs: number;\n Q: number;\n gain?: number;\n}\n\nexport class BiquadFilter {\n public x1 = 0.0;\n public x2 = 0.0;\n public y1 = 0.0;\n public y2 = 0.0;\n public s1 = 0.0;\n public s2 = 0.0;\n\n public constructor(public coefficients: Coefficients) {}\n\n public setFilter(filter: BiquadFilters, options: BiquadSetFilterProps) {\n const coefficients = Coefficients.from(filter, options.fs, options.f0, options.Q, options.gain);\n\n this.update(coefficients);\n }\n\n public update(coefficients: Coefficients) {\n this.coefficients = coefficients;\n }\n\n public replace(coefficients: Coefficients) {\n this.coefficients = coefficients;\n }\n\n public reset() {\n this.x1 = 0.0;\n this.x2 = 0.0;\n this.y1 = 0.0;\n this.y2 = 0.0;\n this.s1 = 0.0;\n this.s2 = 0.0;\n }\n\n public run(input: number) {\n const { a1, a2, b0, b1, b2 } = this.coefficients;\n\n const out = b0 * input + b1 * this.x1 + b2 * this.x2 - a1 * this.y1 - a2 * this.y2;\n\n this.x2 = this.x1;\n this.x1 = input;\n this.y2 = this.y1;\n this.y1 = out;\n\n return out;\n }\n\n public runTransposed(input: number) {\n const { a1, a2, b0, b1, b2 } = this.coefficients;\n\n const out = this.s1 + b0 * input;\n\n this.s1 = this.s2 + b1 * input - a1 * out;\n this.s2 = b2 * input - a2 * out;\n\n return out;\n }\n}\n","export class Frequency {\n public constructor(private __val: number) {\n if (typeof __val !== 'number' || isNaN(__val) || __val === Infinity) throw new TypeError('Frequency value must be a number');\n if (this.__val < 0) throw new Error(`Frequency value cannot be negative (${__val})`);\n }\n\n public khz() {\n return this.__val * 1000.0;\n }\n\n public mhz() {\n return this.__val * 1_000_000.0;\n }\n\n public hz() {\n return this.__val;\n }\n\n public dt() {\n return 1.0 / this.__val;\n }\n\n public valueOf() {\n return this.__val;\n }\n\n public toString() {\n return `${this.__val}Hz`;\n }\n\n public toJSON() {\n return this.toString();\n }\n}\n","import { Transform, TransformOptions } from 'stream';\n\nexport type PCMType = `s${16 | 32}${'l' | 'b'}e`;\n\nexport interface PCMTransformerOptions extends TransformOptions {\n type?: PCMType;\n}\n\nexport class PCMTransformer extends Transform {\n public readonly type: PCMType = 's16le';\n public bits: number;\n public bytes: number;\n public extremum: number;\n\n public constructor(options: PCMTransformerOptions = {}) {\n super(options);\n\n options.type ??= 's16le';\n\n switch (options.type) {\n case 's16be':\n case 's16le':\n this.type = options.type;\n this.bits = 16;\n break;\n case 's32be':\n case 's32le':\n this.type = options.type;\n this.bits = 32;\n break;\n default:\n throw new TypeError(`Expected type to be one of ${(['s16be', 's16le', 's32be', 's32le'] as PCMType[]).join(', ')}, got \"${options.type}\"`);\n }\n\n this.bytes = this.bits / 8;\n this.extremum = Math.pow(2, this.bits - 1);\n }\n\n public _readInt(buffer: Buffer, index: number) {\n const method = `readInt${this.type.substring(1).toUpperCase()}` as `readInt${16 | 32}${'L' | 'B'}E`;\n return buffer[method](index);\n }\n\n public _writeInt(buffer: Buffer, int: number, index: number) {\n const method = `writeInt${this.type.substring(1).toUpperCase()}` as `writeInt${16 | 32}${'L' | 'B'}E`;\n return buffer[method](int, index);\n }\n\n public clamp(val: number, max = this.extremum - 1, min = -this.extremum) {\n return Math.min(max, Math.max(min, val));\n }\n}\n","import { TransformCallback } from 'stream';\nimport { PCMTransformer, PCMTransformerOptions } from '../utils';\nimport { BiquadFilter } from './Biquad';\nimport { BiquadFilters, Coefficients, FilterType, Q_BUTTERWORTH } from './Coefficients';\n\nexport interface BiquadStreamOptions extends PCMTransformerOptions {\n disabled?: boolean;\n filter?: BiquadFilters;\n Q?: number;\n sample?: number;\n cutoff?: number;\n gain?: number;\n}\n\nexport interface BiquadFilterUpdateData {\n filter?: BiquadFilters;\n Q?: number;\n sample?: number;\n cutoff?: number;\n gain?: number;\n}\n\nexport class BiquadStream extends PCMTransformer {\n public disabled = false;\n public biquad!: BiquadFilter;\n public sample = 48000;\n public cutoff = 80;\n public gain = 0;\n public filter!: BiquadFilters;\n public Q = Q_BUTTERWORTH;\n public constructor(options: BiquadStreamOptions = {}) {\n super(options);\n\n this.disabled = !!options.disabled;\n\n if ('sample' in options) this.sample = options.sample!;\n if ('cutoff' in options) this.cutoff = options.cutoff!;\n if ('gain' in options) this.gain = options.gain!;\n if ('Q' in options) this.Q = options.Q!;\n if ('filter' in options) {\n this.filter = options.filter!;\n if (this.filter != null) {\n this.biquad = new BiquadFilter(Coefficients.from(this.filter, this.sample, this.cutoff, this.Q, this.gain));\n }\n }\n }\n\n public disable() {\n this.disabled = true;\n }\n\n public enable() {\n this.disabled = false;\n }\n\n public toggle() {\n this.disabled = !this.disabled;\n }\n\n public getFilterName() {\n if (this.filter == null) return null;\n if (typeof this.filter === 'string') return this.filter;\n return Object.entries(FilterType).find((r) => r[1] === this.filter)?.[0] as BiquadFilters;\n }\n\n public update(options: BiquadFilterUpdateData) {\n if ('sample' in options) this.sample = options.sample!;\n if ('cutoff' in options) this.cutoff = options.cutoff!;\n if ('gain' in options) this.gain = options.gain!;\n if ('Q' in options) this.Q = options.Q!;\n if ('filter' in options) this.filter = options.filter!;\n\n if (this.filter != null) {\n this.biquad = new BiquadFilter(Coefficients.from(this.filter, this.sample, this.cutoff, this.Q, this.gain));\n }\n }\n\n public setFilter(filter: BiquadFilters) {\n this.update({ filter });\n }\n\n public setQ(Q: number) {\n this.update({ Q });\n }\n\n public setSample(fs: number) {\n this.update({ sample: fs });\n }\n\n public setCutoff(f0: number) {\n this.update({ cutoff: f0 });\n }\n\n public setGain(dB: number) {\n this.update({ gain: dB });\n }\n\n public _transform(chunk: Buffer, encoding: BufferEncoding, callback: TransformCallback) {\n if (this.disabled || !this.biquad) {\n this.push(chunk);\n return callback();\n }\n\n const endIndex = Math.floor(chunk.length / 2) * 2;\n const { bytes, extremum } = this;\n\n for (let sampleIndex = 0; sampleIndex < endIndex; sampleIndex += bytes) {\n const int = this._readInt(chunk, sampleIndex);\n const result = this.biquad.run(int);\n const val = Math.min(extremum - 1, Math.max(-extremum, result));\n this._writeInt(chunk, val, sampleIndex);\n }\n\n this.push(chunk);\n return callback();\n }\n}\n","import { Equalizer } from './Equalizer';\n\nexport type ReadIntCallback = (buffer: Buffer, index: number) => number;\nexport type WriteIntCallback = (buffer: Buffer, int: number, index: number) => number;\n\nexport class ChannelProcessor {\n public history: number[];\n public bandMultipliers: number[];\n public current: number;\n public m1: number;\n public m2: number;\n\n public constructor(bandMultipliers: number[]) {\n this.history = new Array(Equalizer.BAND_COUNT * 6).fill(0);\n this.bandMultipliers = bandMultipliers;\n this.current = 0;\n this.m1 = 2;\n this.m2 = 1;\n }\n\n public process(samples: Buffer, extremum = 131072, bytes = 2, readInt?: ReadIntCallback, writeInt?: WriteIntCallback) {\n const endIndex = Math.floor(samples.length / 2) * 2;\n for (let sampleIndex = 0; sampleIndex < endIndex; sampleIndex += bytes) {\n const sample = readInt?.(samples, sampleIndex) ?? samples.readInt16LE(sampleIndex);\n let result = sample * 0.25;\n\n for (let bandIndex = 0; bandIndex < Equalizer.BAND_COUNT; bandIndex++) {\n const x = bandIndex * 6;\n const y = x + 3;\n\n const coefficients = Equalizer.Coefficients48000[bandIndex];\n\n const bandResult = coefficients.alpha * (sample - this.history[x + this.m2]) + coefficients.gamma * this.history[y + this.m1] - coefficients.beta * this.history[y + this.m2];\n\n this.history[x + this.current] = sample;\n this.history[y + this.current] = bandResult;\n\n result += bandResult * this.bandMultipliers[bandIndex];\n }\n\n const val = Math.min(extremum - 1, Math.max(-extremum, result * 4.0));\n writeInt?.(samples, val, sampleIndex) ?? samples.writeInt16LE(val, sampleIndex);\n\n if (++this.current === 3) {\n this.current = 0;\n }\n\n if (++this.m1 === 3) {\n this.m1 = 0;\n }\n\n if (++this.m2 === 3) {\n this.m2 = 0;\n }\n }\n\n return samples;\n }\n\n public reset() {\n this.history.fill(0.0);\n }\n}\n","export class EqualizerCoefficients {\n public constructor(public beta: number, public alpha: number, public gamma: number) {}\n\n public setBeta(v: number) {\n this.beta = v;\n }\n\n public setAlpha(v: number) {\n this.alpha = v;\n }\n\n public setGamma(v: number) {\n this.gamma = v;\n }\n\n public toJSON() {\n const { alpha, beta, gamma } = this;\n\n return { alpha, beta, gamma };\n }\n}\n","export class EqualizerConfiguration {\n public constructor(public bandMultipliers: number[]) {}\n\n public setGain(band: number, value: number) {\n if (this.isValidBand(band)) {\n this.bandMultipliers[band] = Math.max(Math.min(value, 1.0), -0.25);\n }\n }\n\n public getGain(band: number) {\n if (this.isValidBand(band)) {\n return this.bandMultipliers[band];\n } else {\n return 0.0;\n }\n }\n\n public isValidBand(band: number) {\n return band >= 0 && band < this.bandMultipliers.length;\n }\n}\n","import { ChannelProcessor, ReadIntCallback, WriteIntCallback } from './ChannelProcessor';\nimport { EqualizerCoefficients } from './Coefficients';\nimport { EqualizerConfiguration } from './EqualizerConfiguration';\n\nexport interface ChannelProcessorInput {\n data: Buffer;\n readInt?: ReadIntCallback;\n writeInt?: WriteIntCallback;\n extremum?: number;\n bytes?: number;\n}\n\nexport class Equalizer extends EqualizerConfiguration {\n public static BAND_COUNT = 15 as const;\n public static SAMPLE_RATE = 48000 as const;\n public static Coefficients48000 = [\n new EqualizerCoefficients(9.9847546664e-1, 7.6226668143e-4, 1.9984647656),\n new EqualizerCoefficients(9.9756184654e-1, 1.2190767289e-3, 1.9975344645),\n new EqualizerCoefficients(9.9616261379e-1, 1.9186931041e-3, 1.9960947369),\n new EqualizerCoefficients(9.9391578543e-1, 3.0421072865e-3, 1.9937449618),\n new EqualizerCoefficients(9.9028307215e-1, 4.8584639242e-3, 1.9898465702),\n new EqualizerCoefficients(9.8485897264e-1, 7.5705136795e-3, 1.9837962543),\n new EqualizerCoefficients(9.7588512657e-1, 1.2057436715e-2, 1.9731772447),\n new EqualizerCoefficients(9.6228521814e-1, 1.8857390928e-2, 1.9556164694),\n new EqualizerCoefficients(9.4080933132e-1, 2.9595334338e-2, 1.9242054384),\n new EqualizerCoefficients(9.0702059196e-1, 4.6489704022e-2, 1.8653476166),\n new EqualizerCoefficients(8.5868004289e-1, 7.0659978553e-2, 1.7600401337),\n new EqualizerCoefficients(7.8409610788e-1, 1.0795194606e-1, 1.5450725522),\n new EqualizerCoefficients(6.8332861002e-1, 1.5833569499e-1, 1.1426447155),\n new EqualizerCoefficients(5.5267518228e-1, 2.2366240886e-1, 4.0186190803e-1),\n new EqualizerCoefficients(4.1811888447e-1, 2.9094055777e-1, -7.0905944223e-1)\n ];\n public channels: ChannelProcessor[] = [];\n public channelCount: number;\n\n public constructor(channelCount: number, bandMultipliers: number[]) {\n super(bandMultipliers);\n this.channelCount = channelCount;\n this.channels = this.createChannelProcessor();\n }\n\n public createChannelProcessor() {\n return Array.from({ length: this.channelCount }, () => {\n return new ChannelProcessor(this.bandMultipliers);\n });\n }\n\n public process(input: ChannelProcessorInput[]) {\n return this.channels.map((c, i) => {\n const { data, extremum, readInt, writeInt, bytes } = input[i];\n\n return c.process(data, extremum, bytes, readInt, writeInt);\n });\n }\n}\n","import { TransformCallback } from 'stream';\nimport { PCMTransformer, PCMTransformerOptions } from '../utils';\nimport { Equalizer } from './Equalizer';\n\ninterface EqualizerStreamOptions extends PCMTransformerOptions {\n bandMultiplier?: EqualizerBand[];\n disabled?: boolean;\n channels?: number;\n}\n\nexport interface EqualizerBand {\n band: number;\n gain: number;\n}\n\nexport class EqualizerStream extends PCMTransformer {\n public disabled = false;\n public bandMultipliers: number[] = new Array(Equalizer.BAND_COUNT).fill(0);\n public equalizer: Equalizer;\n public constructor(options?: EqualizerStreamOptions) {\n super(options);\n\n options = Object.assign(\n {},\n {\n bandMultiplier: [],\n channels: 1,\n disabled: false\n },\n options || {}\n );\n\n if (options.disabled) this.disabled = !!options.disabled;\n this.equalizer = new Equalizer(options.channels || 1, this.bandMultipliers);\n if (Array.isArray(options.bandMultiplier)) this._processBands(options.bandMultiplier);\n }\n\n public _processBands(multiplier: EqualizerBand[]) {\n for (const mul of multiplier) {\n if (mul.band > Equalizer.BAND_COUNT - 1 || mul.band < 0) throw new RangeError(`Band value out of range. Expected >0 & <${Equalizer.BAND_COUNT - 1}, received \"${mul.band}\"`);\n this.equalizer.setGain(mul.band, mul.gain);\n }\n }\n\n public disable() {\n this.disabled = true;\n }\n\n public enable() {\n this.disabled = false;\n }\n\n public toggle() {\n this.disabled = !this.disabled;\n }\n\n public _transform(chunk: Buffer, encoding: BufferEncoding, callback: TransformCallback): void {\n if (this.disabled) {\n this.push(chunk);\n return callback();\n }\n\n this.equalizer.process([\n {\n data: chunk,\n extremum: this.extremum,\n readInt: (b, idx) => this._readInt(b, idx),\n writeInt: (b, i, idx) => this._writeInt(b, i, idx),\n bytes: this.bytes\n }\n ]);\n\n this.push(chunk);\n\n return callback();\n }\n\n public getEQ() {\n return this.bandMultipliers.map((m, i) => ({\n band: i,\n gain: m\n })) as EqualizerBand[];\n }\n\n public setEQ(bands: EqualizerBand[]) {\n this._processBands(bands);\n }\n\n public resetEQ() {\n this._processBands(\n Array.from(\n {\n length: Equalizer.BAND_COUNT\n },\n (_, i) => ({\n band: i,\n gain: 0\n })\n )\n );\n }\n}\n","import { TransformCallback } from 'stream';\nimport { PCMTransformer, PCMTransformerOptions } from '../utils';\n\n/*\nMono: [0, 1, 2, 3, 4, 5]\nStereo: [0, 1, 0, 1, 2, 3, 2, 3, 4, 5, 4, 5]\n*/\n\nexport type MSTStrategy = 'm2s' | 's2m';\n\nexport interface MonoStereoTransformerOptions extends PCMTransformerOptions {\n strategy: MSTStrategy;\n}\n\nexport class MonoStereoTransformer extends PCMTransformer {\n public disabled = false;\n public strategy: MSTStrategy;\n\n public constructor(options?: MonoStereoTransformerOptions) {\n super(options);\n if (!['m2s', 's2m'].includes(options?.strategy as MSTStrategy)) {\n throw new TypeError(`Strategy must be \"m2s\" or \"s2m\"`);\n }\n\n this.strategy = options!.strategy;\n }\n\n public disable() {\n this.disabled = true;\n }\n\n public enable() {\n this.disabled = false;\n }\n\n public toggle() {\n this.disabled = !this.disabled;\n }\n\n public setStrategy(strategy: MSTStrategy) {\n this.strategy = strategy;\n }\n\n public _transform(chunk: Buffer, encoding: BufferEncoding, callback: TransformCallback): void {\n if (this.disabled) {\n this.push(chunk);\n return callback();\n }\n\n const len = Math.floor(chunk.length / 2) * 2;\n\n if (this.strategy === 'm2s') {\n this.push(this.toStereo(chunk, len));\n } else {\n this.push(this.toMono(chunk, len));\n }\n\n return callback();\n }\n\n public toStereo(sample: Buffer, len: number) {\n const bytes = this.bytes;\n const stereoBuffer = Buffer.alloc(len * 2);\n\n for (let i = 0; i < len; i += bytes) {\n stereoBuffer[i * 2 + 0] = sample[i];\n stereoBuffer[i * 2 + 1] = sample[i + 1];\n stereoBuffer[i * 2 + 2] = sample[i];\n stereoBuffer[i * 2 + 3] = sample[i + 1];\n }\n\n return stereoBuffer;\n }\n\n public toMono(sample: Buffer, len: number) {\n const bytes = this.bytes;\n const monoBuffer = Buffer.alloc(Math.floor(len / 2));\n\n for (let i = 0; i < len; i += bytes) {\n monoBuffer[i] = sample[i * 2 + 0];\n monoBuffer[i + 1] = sample[i * 2 + 1];\n }\n\n return monoBuffer;\n }\n}\n","export * from './biquad';\nexport * from './equalizer';\nexport * from './utils';\nexport * from './audio';\n\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const version: string = '0.1.3';\n"],"mappings":";;;;AAAO,IAAM,aAAa;AAAA,EACtB,yBAAyB;AAAA,EACzB,mBAAmB;AAAA,EACnB,SAAS;AAAA,EACT,UAAU;AAAA,EACV,UAAU;AAAA,EACV,OAAO;AAAA,EACP,SAAS;A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AA,IACzC;AAEA,WAAO;AAAA,EACX;AAAA,EAEO,OAAO,QAAgB,KAAa;AACvC,UAAM,QAAQ,KAAK;AACnB,UAAM,aAAa,OAAO,MAAM,KAAK,MAAM,MAAM,CAAC,CAAC;AAEnD,aAAS,IAAI,GAAG,IAAI,KAAK,KAAK,OAAO;AACjC,iBAAW,KAAK,OAAO,IAAI,IAAI;AAC/B,iBAAW,IAAI,KAAK,OAAO,IAAI,IAAI;AAAA,IACvC;AAEA,WAAO;AAAA,EACX;AACJ;AAvEa;;;ACRN,IAAM,UAAkB;","names":[]} \ No newline at end of file diff --git a/node_modules/@discord-player/equalizer/package.json b/node_modules/@discord-player/equalizer/package.json deleted file mode 100644 index 1edadee..0000000 --- a/node_modules/@discord-player/equalizer/package.json +++ /dev/null @@ -1,44 +0,0 @@ -{ - "name": "@discord-player/equalizer", - "version": "0.1.3", - "description": "PCM Equalizer implementation for Discord Player", - "keywords": [ - "discord-player", - "pcm", - "equalizer", - "music", - "bot", - "discord.js", - "javascript", - "voip", - "lavalink", - "lavaplayer" - ], - "author": "Androz2091 ", - "homepage": "https://discord-player.js.org", - "license": "MIT", - "main": "dist/index.js", - "module": "dist/index.mjs", - "types": "dist/index.d.ts", - "directories": { - "dist": "dist", - "src": "src" - }, - "files": [ - "dist" - ], - "repository": { - "type": "git", - "url": "git+https://github.com/Androz2091/discord-player.git" - }, - "scripts": { - "build": "tsup", - "build:check": "tsc --noEmit" - }, - "bugs": { - "url": "https://github.com/Androz2091/discord-player/issues" - }, - "devDependencies": { - "@discord-player/tsconfig": "*" - } -} \ No newline at end of file diff --git a/node_modules/@discordjs/builders/CHANGELOG.md b/node_modules/@discordjs/builders/CHANGELOG.md index 0ab0974..de5bb4f 100644 --- a/node_modules/@discordjs/builders/CHANGELOG.md +++ b/node_modules/@discordjs/builders/CHANGELOG.md @@ -2,6 +2,70 @@ All notable changes to this project will be documented in this file. +# [@discordjs/builders@1.6.3](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.6.2...@discordjs/builders@1.6.3) - (2023-05-01) + +## Refactor + +- Remove `@discordjs/util` re-export (#9488) ([54ceedf](https://github.com/discordjs/discord.js/commit/54ceedf6c535d4641643d4106b6286cbef09de4a)) + +# [@discordjs/builders@1.6.2](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.6.1...@discordjs/builders@1.6.2) - (2023-05-01) + +## Bug Fixes + +- **BaseSelectMenuBuilder:** Modify class to be `abstract` (#9358) ([ca4de2d](https://github.com/discordjs/discord.js/commit/ca4de2d9c6bc204e85d1b7eae7eabd23dbeb4475)) +- Correct `@link` tags that involve parents (#9351) ([fbbce3e](https://github.com/discordjs/discord.js/commit/fbbce3eb4ba20bc0c4806ca2259d1f86001594be)) +- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2)) + +## Documentation + +- Reference package names properly (#9426) ([d6bca9b](https://github.com/discordjs/discord.js/commit/d6bca9bb4d976dc069a5039250db7d5b3e9142ef)) +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) +- **builders:** Add some basic documentation (#9359) ([8073561](https://github.com/discordjs/discord.js/commit/8073561824f911d1a18d0b4f1de39f452bc69fa9)) +- Use `@link` in `@see` (#9348) ([d66d113](https://github.com/discordjs/discord.js/commit/d66d1133331b81563588db4500c63a18c3c3dfae)) + +# [@discordjs/builders@1.6.2](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.6.1...@discordjs/builders@1.6.2) - (2023-05-01) + +## Bug Fixes + +- **BaseSelectMenuBuilder:** Modify class to be `abstract` (#9358) ([ca4de2d](https://github.com/discordjs/discord.js/commit/ca4de2d9c6bc204e85d1b7eae7eabd23dbeb4475)) +- Correct `@link` tags that involve parents (#9351) ([fbbce3e](https://github.com/discordjs/discord.js/commit/fbbce3eb4ba20bc0c4806ca2259d1f86001594be)) +- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2)) + +## Documentation + +- Reference package names properly (#9426) ([d6bca9b](https://github.com/discordjs/discord.js/commit/d6bca9bb4d976dc069a5039250db7d5b3e9142ef)) +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) +- **builders:** Add some basic documentation (#9359) ([8073561](https://github.com/discordjs/discord.js/commit/8073561824f911d1a18d0b4f1de39f452bc69fa9)) +- Use `@link` in `@see` (#9348) ([d66d113](https://github.com/discordjs/discord.js/commit/d66d1133331b81563588db4500c63a18c3c3dfae)) + +# [@discordjs/builders@1.6.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.5.0...@discordjs/builders@1.6.0) - (2023-04-01) + +## Bug Fixes + +- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b)) + +## Features + +- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b)) + +# [@discordjs/builders@1.5.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.4.0...@discordjs/builders@1.5.0) - (2023-03-12) + +## Documentation + +- **EmbedBuilder#spliceFields:** Fix a typo (#9159) ([4367ab9](https://github.com/discordjs/discord.js/commit/4367ab930227048868db3ed8437f6c4507ff32e1)) +- Fix version export (#9049) ([8b70f49](https://github.com/discordjs/discord.js/commit/8b70f497a1207e30edebdecd12b926c981c13d28)) + +## Features + +- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38)) +- **StringSelectMenu:** Add `spliceOptions()` (#8937) ([a6941d5](https://github.com/discordjs/discord.js/commit/a6941d536ce24ed2b5446a154cbc886b2b97c63a)) +- Add support for nsfw commands (#7976) ([7a51344](https://github.com/discordjs/discord.js/commit/7a5134459c5f06864bf74631d83b96d9c21b72d8)) +- Add `@discordjs/formatters` (#8889) ([3fca638](https://github.com/discordjs/discord.js/commit/3fca638a8470dcea2f79ddb9f18526dbc0017c88)) + +## Styling + +- Run prettier (#9041) ([2798ba1](https://github.com/discordjs/discord.js/commit/2798ba1eb3d734f0cf2eeccd2e16cfba6804873b)) + # [@discordjs/builders@1.4.0](https://github.com/discordjs/discord.js/compare/@discordjs/builders@1.3.0...@discordjs/builders@1.4.0) - (2022-11-28) ## Bug Fixes diff --git a/node_modules/@discordjs/builders/README.md b/node_modules/@discordjs/builders/README.md index 59508dd..2981f19 100644 --- a/node_modules/@discordjs/builders/README.md +++ b/node_modules/@discordjs/builders/README.md @@ -16,11 +16,15 @@

+## About + +`@discordjs/builders` is a utility package for easily building Discord API payloads. + ## Installation **Node.js 16.9.0 or newer is required.** -```sh-session +```sh npm install @discordjs/builders yarn add @discordjs/builders pnpm add @discordjs/builders @@ -28,16 +32,14 @@ pnpm add @discordjs/builders ## Examples -Here are some examples for the builders and utilities you can find in this package: - -- [Slash Command Builders][example] +You can find examples of how to use the builders in the [Slash Command Builders][example] examples. ## Links - [Website][website] ([source][website-source]) - [Documentation][documentation] - [Guide][guide] ([source][guide-source]) - See also the [Update Guide][guide-update], including updated and removed items in the library. + Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library. - [discord.js Discord server][discord] - [Discord API Discord server][discord-api] - [GitHub][source] @@ -52,13 +54,12 @@ See [the contribution guide][contributing] if you'd like to submit a PR. ## Help -If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle -nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. +If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. [example]: https://github.com/discordjs/discord.js/blob/main/packages/builders/docs/examples/Slash%20Command%20Builders.md -[website]: https://discord.js.org/ +[website]: https://discord.js.org [website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website -[documentation]: https://discord.js.org/#/docs/builders +[documentation]: https://discord.js.org/docs/packages/builders/stable [guide]: https://discordjs.guide/ [guide-source]: https://github.com/discordjs/guide [guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html diff --git a/node_modules/@discordjs/builders/dist/index.d.ts b/node_modules/@discordjs/builders/dist/index.d.ts index f5df124..5237d9b 100644 --- a/node_modules/@discordjs/builders/dist/index.d.ts +++ b/node_modules/@discordjs/builders/dist/index.d.ts @@ -1,9 +1,7 @@ import * as _sapphire_shapeshift from '@sapphire/shapeshift'; -import { APIEmbedField, APIEmbedAuthor, APIEmbedFooter, APIEmbedImage, APIEmbed, APISelectMenuOption, APIMessageComponentEmoji, ButtonStyle, ChannelType, APIActionRowComponent, APIActionRowComponentTypes, APIBaseComponent, ComponentType, APIButtonComponent, APISelectMenuComponent, APIChannelSelectComponent, APIMentionableSelectComponent, APIRoleSelectComponent, APIStringSelectComponent, APIUserSelectComponent, APITextInputComponent, TextInputStyle, APIMessageActionRowComponent, APIModalActionRowComponent, APIModalComponent, APIMessageComponent, APIModalInteractionResponseCallbackData, LocalizationMap, LocaleString, ApplicationCommandOptionType, APIApplicationCommandBasicOption, APIApplicationCommandAttachmentOption, APIApplicationCommandBooleanOption, APIApplicationCommandChannelOption, APIApplicationCommandOptionChoice, APIApplicationCommandIntegerOption, APIApplicationCommandMentionableOption, APIApplicationCommandNumberOption, APIApplicationCommandRoleOption, APIApplicationCommandStringOption, APIApplicationCommandUserOption, APIApplicationCommandSubcommandGroupOption, APIApplicationCommandSubcommandOption, Permissions, RESTPostAPIChatInputApplicationCommandsJSONBody, APIApplicationCommandOption, Locale, RESTPostAPIContextMenuApplicationCommandsJSONBody, ApplicationCommandType } from 'discord-api-types/v10'; -import { URL } from 'node:url'; -import { Snowflake } from 'discord-api-types/globals'; +import { APIEmbedField, APIEmbedAuthor, APIEmbedFooter, APIEmbedImage, APIEmbed, APISelectMenuOption, APIMessageComponentEmoji, ButtonStyle, ChannelType, APIActionRowComponent, APIActionRowComponentTypes, APIBaseComponent, ComponentType, APIButtonComponent, APISelectMenuComponent, APIChannelSelectComponent, APIMentionableSelectComponent, APIRoleSelectComponent, APIStringSelectComponent, APIUserSelectComponent, APITextInputComponent, TextInputStyle, APIMessageActionRowComponent, APIModalActionRowComponent, APIModalComponent, APIMessageComponent, APIModalInteractionResponseCallbackData, LocalizationMap, LocaleString, ApplicationCommandOptionType, APIApplicationCommandBasicOption, APIApplicationCommandAttachmentOption, APIApplicationCommandBooleanOption, APIApplicationCommandChannelOption, APIApplicationCommandOptionChoice, APIApplicationCommandIntegerOption, APIApplicationCommandMentionableOption, APIApplicationCommandNumberOption, APIApplicationCommandRoleOption, APIApplicationCommandStringOption, APIApplicationCommandUserOption, APIApplicationCommandSubcommandGroupOption, APIApplicationCommandSubcommandOption, Permissions, RESTPostAPIChatInputApplicationCommandsJSONBody, APIApplicationCommandOption, Locale, ApplicationCommandType, RESTPostAPIContextMenuApplicationCommandsJSONBody } from 'discord-api-types/v10'; +export * from '@discordjs/formatters'; import { JSONEncodable, Equatable } from '@discordjs/util'; -export * from '@discordjs/util'; declare const fieldNamePredicate: _sapphire_shapeshift.StringValidator; declare const fieldValuePredicate: _sapphire_shapeshift.StringValidator; @@ -54,92 +52,136 @@ declare const embedFooterPredicate: _sapphire_shapeshift.ObjectValidator<{ declare const timestampPredicate: _sapphire_shapeshift.UnionValidator; declare const titlePredicate: _sapphire_shapeshift.UnionValidator; -declare const Assertions$5_fieldNamePredicate: typeof fieldNamePredicate; -declare const Assertions$5_fieldValuePredicate: typeof fieldValuePredicate; -declare const Assertions$5_fieldInlinePredicate: typeof fieldInlinePredicate; -declare const Assertions$5_embedFieldPredicate: typeof embedFieldPredicate; -declare const Assertions$5_embedFieldsArrayPredicate: typeof embedFieldsArrayPredicate; -declare const Assertions$5_fieldLengthPredicate: typeof fieldLengthPredicate; -declare const Assertions$5_validateFieldLength: typeof validateFieldLength; -declare const Assertions$5_authorNamePredicate: typeof authorNamePredicate; -declare const Assertions$5_imageURLPredicate: typeof imageURLPredicate; -declare const Assertions$5_urlPredicate: typeof urlPredicate; -declare const Assertions$5_embedAuthorPredicate: typeof embedAuthorPredicate; declare const Assertions$5_RGBPredicate: typeof RGBPredicate; +declare const Assertions$5_authorNamePredicate: typeof authorNamePredicate; declare const Assertions$5_colorPredicate: typeof colorPredicate; declare const Assertions$5_descriptionPredicate: typeof descriptionPredicate; -declare const Assertions$5_footerTextPredicate: typeof footerTextPredicate; +declare const Assertions$5_embedAuthorPredicate: typeof embedAuthorPredicate; +declare const Assertions$5_embedFieldPredicate: typeof embedFieldPredicate; +declare const Assertions$5_embedFieldsArrayPredicate: typeof embedFieldsArrayPredicate; declare const Assertions$5_embedFooterPredicate: typeof embedFooterPredicate; +declare const Assertions$5_fieldInlinePredicate: typeof fieldInlinePredicate; +declare const Assertions$5_fieldLengthPredicate: typeof fieldLengthPredicate; +declare const Assertions$5_fieldNamePredicate: typeof fieldNamePredicate; +declare const Assertions$5_fieldValuePredicate: typeof fieldValuePredicate; +declare const Assertions$5_footerTextPredicate: typeof footerTextPredicate; +declare const Assertions$5_imageURLPredicate: typeof imageURLPredicate; declare const Assertions$5_timestampPredicate: typeof timestampPredicate; declare const Assertions$5_titlePredicate: typeof titlePredicate; +declare const Assertions$5_urlPredicate: typeof urlPredicate; +declare const Assertions$5_validateFieldLength: typeof validateFieldLength; declare namespace Assertions$5 { export { - Assertions$5_fieldNamePredicate as fieldNamePredicate, - Assertions$5_fieldValuePredicate as fieldValuePredicate, - Assertions$5_fieldInlinePredicate as fieldInlinePredicate, - Assertions$5_embedFieldPredicate as embedFieldPredicate, - Assertions$5_embedFieldsArrayPredicate as embedFieldsArrayPredicate, - Assertions$5_fieldLengthPredicate as fieldLengthPredicate, - Assertions$5_validateFieldLength as validateFieldLength, - Assertions$5_authorNamePredicate as authorNamePredicate, - Assertions$5_imageURLPredicate as imageURLPredicate, - Assertions$5_urlPredicate as urlPredicate, - Assertions$5_embedAuthorPredicate as embedAuthorPredicate, Assertions$5_RGBPredicate as RGBPredicate, + Assertions$5_authorNamePredicate as authorNamePredicate, Assertions$5_colorPredicate as colorPredicate, Assertions$5_descriptionPredicate as descriptionPredicate, - Assertions$5_footerTextPredicate as footerTextPredicate, + Assertions$5_embedAuthorPredicate as embedAuthorPredicate, + Assertions$5_embedFieldPredicate as embedFieldPredicate, + Assertions$5_embedFieldsArrayPredicate as embedFieldsArrayPredicate, Assertions$5_embedFooterPredicate as embedFooterPredicate, + Assertions$5_fieldInlinePredicate as fieldInlinePredicate, + Assertions$5_fieldLengthPredicate as fieldLengthPredicate, + Assertions$5_fieldNamePredicate as fieldNamePredicate, + Assertions$5_fieldValuePredicate as fieldValuePredicate, + Assertions$5_footerTextPredicate as footerTextPredicate, + Assertions$5_imageURLPredicate as imageURLPredicate, Assertions$5_timestampPredicate as timestampPredicate, Assertions$5_titlePredicate as titlePredicate, + Assertions$5_urlPredicate as urlPredicate, + Assertions$5_validateFieldLength as validateFieldLength, }; } +/** + * Normalizes data that is a rest parameter or an array into an array with a depth of 1. + * + * @typeParam T - The data that must satisfy {@link RestOrArray}. + * @param arr - The (possibly variadic) data to normalize + */ declare function normalizeArray(arr: RestOrArray): T[]; +/** + * Represents data that may be an array or came from a rest parameter. + * + * @remarks + * This type is used throughout builders to ensure both an array and variadic arguments + * may be used. It is normalized with {@link normalizeArray}. + */ type RestOrArray = T[] | [T[]]; +/** + * A tuple satisfying the RGB color model. + * + * @see {@link https://developer.mozilla.org/docs/Glossary/RGB} + */ type RGBTuple = [red: number, green: number, blue: number]; +/** + * The base icon data typically used in payloads. + */ interface IconData { /** - * The URL of the icon + * The URL of the icon. */ iconURL?: string; /** - * The proxy URL of the icon + * The proxy URL of the icon. */ proxyIconURL?: string; } +/** + * Represents the author data of an embed. + */ type EmbedAuthorData = IconData & Omit; +/** + * Represents the author options of an embed. + */ type EmbedAuthorOptions = Omit; +/** + * Represents the footer data of an embed. + */ type EmbedFooterData = IconData & Omit; +/** + * Represents the footer options of an embed. + */ type EmbedFooterOptions = Omit; +/** + * Represents the image data of an embed. + */ interface EmbedImageData extends Omit { /** - * The proxy URL for the image + * The proxy URL for the image. */ proxyURL?: string; } /** - * Represents a embed in a message (image/video preview, rich embed, etc.) + * A builder that creates API-compatible JSON data for embeds. */ declare class EmbedBuilder { + /** + * The API data associated with this embed. + */ readonly data: APIEmbed; + /** + * Creates a new embed from API data. + * + * @param data - The API data to create this embed with + */ constructor(data?: APIEmbed); /** - * Appends fields to the embed + * Appends fields to the embed. * * @remarks * This method accepts either an array of fields or a variable number of field parameters. * The maximum amount of fields that can be added is 25. * @example - * Using an array + * Using an array: * ```ts * const fields: APIEmbedField[] = ...; * const embed = new EmbedBuilder() * .addFields(fields); * ``` * @example - * Using rest parameters (variadic) + * Using rest parameters (variadic): * ```ts * const embed = new EmbedBuilder() * .addFields( @@ -151,27 +193,27 @@ declare class EmbedBuilder { */ addFields(...fields: RestOrArray): this; /** - * Removes, replaces, or inserts fields in the embed. + * Removes, replaces, or inserts fields for this embed. * * @remarks * This method behaves similarly - * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice}. + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice | Array.prototype.splice()}. * The maximum amount of fields that can be added is 25. * * It's useful for modifying and adjusting order of the already-existing fields of an embed. * @example - * Remove the first field + * Remove the first field: * ```ts * embed.spliceFields(0, 1); * ``` * @example - * Remove the first n fields + * Remove the first n fields: * ```ts - * const n = 4 + * const n = 4; * embed.spliceFields(0, n); * ``` * @example - * Remove the last field + * Remove the last field: * ```ts * embed.spliceFields(-1, 1); * ``` @@ -181,7 +223,7 @@ declare class EmbedBuilder { */ spliceFields(index: number, deleteCount: number, ...fields: APIEmbedField[]): this; /** - * Sets the embed's fields + * Sets the fields for this embed. * * @remarks * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically, @@ -192,350 +234,80 @@ declare class EmbedBuilder { */ setFields(...fields: RestOrArray): this; /** - * Sets the author of this embed + * Sets the author of this embed. * - * @param options - The options for the author + * @param options - The options to use */ setAuthor(options: EmbedAuthorOptions | null): this; /** - * Sets the color of this embed + * Sets the color of this embed. * - * @param color - The color of the embed + * @param color - The color to use */ setColor(color: RGBTuple | number | null): this; /** - * Sets the description of this embed + * Sets the description of this embed. * - * @param description - The description + * @param description - The description to use */ setDescription(description: string | null): this; /** - * Sets the footer of this embed + * Sets the footer of this embed. * - * @param options - The options for the footer + * @param options - The footer to use */ setFooter(options: EmbedFooterOptions | null): this; /** - * Sets the image of this embed + * Sets the image of this embed. * - * @param url - The URL of the image + * @param url - The image URL to use */ setImage(url: string | null): this; /** - * Sets the thumbnail of this embed + * Sets the thumbnail of this embed. * - * @param url - The URL of the thumbnail + * @param url - The thumbnail URL to use */ setThumbnail(url: string | null): this; /** - * Sets the timestamp of this embed + * Sets the timestamp of this embed. * - * @param timestamp - The timestamp or date + * @param timestamp - The timestamp or date to use */ setTimestamp(timestamp?: Date | number | null): this; /** - * Sets the title of this embed + * Sets the title for this embed. * - * @param title - The title + * @param title - The title to use */ setTitle(title: string | null): this; /** - * Sets the URL of this embed + * Sets the URL of this embed. * - * @param url - The URL + * @param url - The URL to use */ setURL(url: string | null): this; /** - * Transforms the embed to a plain object + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. */ toJSON(): APIEmbed; } /** - * Wraps the content inside a codeblock with no language - * - * @param content - The content to wrap - */ -declare function codeBlock(content: C): `\`\`\`\n${C}\n\`\`\``; -/** - * Wraps the content inside a codeblock with the specified language - * - * @param language - The language for the codeblock - * @param content - The content to wrap - */ -declare function codeBlock(language: L, content: C): `\`\`\`${L}\n${C}\n\`\`\``; -/** - * Wraps the content inside \`backticks\`, which formats it as inline code - * - * @param content - The content to wrap - */ -declare function inlineCode(content: C): `\`${C}\``; -/** - * Formats the content into italic text - * - * @param content - The content to wrap - */ -declare function italic(content: C): `_${C}_`; -/** - * Formats the content into bold text - * - * @param content - The content to wrap - */ -declare function bold(content: C): `**${C}**`; -/** - * Formats the content into underscored text - * - * @param content - The content to wrap - */ -declare function underscore(content: C): `__${C}__`; -/** - * Formats the content into strike-through text - * - * @param content - The content to wrap - */ -declare function strikethrough(content: C): `~~${C}~~`; -/** - * Formats the content into a quote. This needs to be at the start of the line for Discord to format it - * - * @param content - The content to wrap - */ -declare function quote(content: C): `> ${C}`; -/** - * Formats the content into a block quote. This needs to be at the start of the line for Discord to format it - * - * @param content - The content to wrap - */ -declare function blockQuote(content: C): `>>> ${C}`; -/** - * Wraps the URL into `<>`, which stops it from embedding - * - * @param url - The URL to wrap - */ -declare function hideLinkEmbed(url: C): `<${C}>`; -/** - * Wraps the URL into `<>`, which stops it from embedding - * - * @param url - The URL to wrap - */ -declare function hideLinkEmbed(url: URL): `<${string}>`; -/** - * Formats the content and the URL into a masked URL - * - * @param content - The content to display - * @param url - The URL the content links to - */ -declare function hyperlink(content: C, url: URL): `[${C}](${string})`; -/** - * Formats the content and the URL into a masked URL - * - * @param content - The content to display - * @param url - The URL the content links to - */ -declare function hyperlink(content: C, url: U): `[${C}](${U})`; -/** - * Formats the content and the URL into a masked URL - * - * @param content - The content to display - * @param url - The URL the content links to - * @param title - The title shown when hovering on the masked link - */ -declare function hyperlink(content: C, url: URL, title: T): `[${C}](${string} "${T}")`; -/** - * Formats the content and the URL into a masked URL - * - * @param content - The content to display - * @param url - The URL the content links to - * @param title - The title shown when hovering on the masked link - */ -declare function hyperlink(content: C, url: U, title: T): `[${C}](${U} "${T}")`; -/** - * Wraps the content inside spoiler (hidden text) - * - * @param content - The content to wrap - */ -declare function spoiler(content: C): `||${C}||`; -/** - * Formats a user ID into a user mention - * - * @param userId - The user ID to format - */ -declare function userMention(userId: C): `<@${C}>`; -/** - * Formats a channel ID into a channel mention - * - * @param channelId - The channel ID to format - */ -declare function channelMention(channelId: C): `<#${C}>`; -/** - * Formats a role ID into a role mention - * - * @param roleId - The role ID to format - */ -declare function roleMention(roleId: C): `<@&${C}>`; -/** - * Formats an application command name, subcommand group name, subcommand name, and ID into an application command mention - * - * @param commandName - The application command name to format - * @param subcommandGroupName - The subcommand group name to format - * @param subcommandName - The subcommand name to format - * @param commandId - The application command ID to format - */ -declare function chatInputApplicationCommandMention(commandName: N, subcommandGroupName: G, subcommandName: S, commandId: I): ``; -/** - * Formats an application command name, subcommand name, and ID into an application command mention - * - * @param commandName - The application command name to format - * @param subcommandName - The subcommand name to format - * @param commandId - The application command ID to format - */ -declare function chatInputApplicationCommandMention(commandName: N, subcommandName: S, commandId: I): ``; -/** - * Formats an application command name and ID into an application command mention - * - * @param commandName - The application command name to format - * @param commandId - The application command ID to format - */ -declare function chatInputApplicationCommandMention(commandName: N, commandId: I): ``; -/** - * Formats an emoji ID into a fully qualified emoji identifier - * - * @param emojiId - The emoji ID to format - */ -declare function formatEmoji(emojiId: C, animated?: false): `<:_:${C}>`; -/** - * Formats an emoji ID into a fully qualified emoji identifier - * - * @param emojiId - The emoji ID to format - * @param animated - Whether the emoji is animated or not. Defaults to `false` - */ -declare function formatEmoji(emojiId: C, animated?: true): ``; -/** - * Formats an emoji ID into a fully qualified emoji identifier - * - * @param emojiId - The emoji ID to format - * @param animated - Whether the emoji is animated or not. Defaults to `false` - */ -declare function formatEmoji(emojiId: C, animated?: boolean): `<:_:${C}>` | ``; -/** - * Formats a channel link for a direct message channel. - * - * @param channelId - The channel's id - */ -declare function channelLink(channelId: C): `https://discord.com/channels/@me/${C}`; -/** - * Formats a channel link for a guild channel. - * - * @param channelId - The channel's id - * @param guildId - The guild's id - */ -declare function channelLink(channelId: C, guildId: G): `https://discord.com/channels/${G}/${C}`; -/** - * Formats a message link for a direct message channel. - * - * @param channelId - The channel's id - * @param messageId - The message's id - */ -declare function messageLink(channelId: C, messageId: M): `https://discord.com/channels/@me/${C}/${M}`; -/** - * Formats a message link for a guild channel. - * - * @param channelId - The channel's id - * @param messageId - The message's id - * @param guildId - The guild's id - */ -declare function messageLink(channelId: C, messageId: M, guildId: G): `https://discord.com/channels/${G}/${C}/${M}`; -/** - * Formats a date into a short date-time string - * - * @param date - The date to format, defaults to the current time - */ -declare function time(date?: Date): ``; -/** - * Formats a date given a format style - * - * @param date - The date to format - * @param style - The style to use - */ -declare function time(date: Date, style: S): ``; -/** - * Formats the given timestamp into a short date-time string - * - * @param seconds - The time to format, represents an UNIX timestamp in seconds - */ -declare function time(seconds: C): ``; -/** - * Formats the given timestamp into a short date-time string - * - * @param seconds - The time to format, represents an UNIX timestamp in seconds - * @param style - The style to use - */ -declare function time(seconds: C, style: S): ``; -/** - * The {@link https://discord.com/developers/docs/reference#message-formatting-timestamp-styles | message formatting timestamp styles} supported by Discord - */ -declare const TimestampStyles: { - /** - * Short time format, consisting of hours and minutes, e.g. 16:20 - */ - readonly ShortTime: "t"; - /** - * Long time format, consisting of hours, minutes, and seconds, e.g. 16:20:30 - */ - readonly LongTime: "T"; - /** - * Short date format, consisting of day, month, and year, e.g. 20/04/2021 - */ - readonly ShortDate: "d"; - /** - * Long date format, consisting of day, month, and year, e.g. 20 April 2021 - */ - readonly LongDate: "D"; - /** - * Short date-time format, consisting of short date and short time formats, e.g. 20 April 2021 16:20 - */ - readonly ShortDateTime: "f"; - /** - * Long date-time format, consisting of long date and short time formats, e.g. Tuesday, 20 April 2021 16:20 - */ - readonly LongDateTime: "F"; - /** - * Relative time format, consisting of a relative duration format, e.g. 2 months ago - */ - readonly RelativeTime: "R"; -}; -/** - * The possible values, see {@link TimestampStyles} for more information - */ -type TimestampStylesString = typeof TimestampStyles[keyof typeof TimestampStyles]; -/** - * An enum with all the available faces from Discord's native slash commands - */ -declare enum Faces { - /** - * Β―\\_(ツ)\\_/Β― - */ - Shrug = "\u00AF\\_(\u30C4)\\_/\u00AF", - /** - * (β•―Β°β–‘Β°οΌ‰β•―οΈ΅ ┻━┻ - */ - Tableflip = "(\u256F\u00B0\u25A1\u00B0\uFF09\u256F\uFE35 \u253B\u2501\u253B", - /** - * ┬─┬ γƒŽ( γ‚œ-γ‚œγƒŽ) - */ - Unflip = "\u252C\u2500\u252C \u30CE( \u309C-\u309C\u30CE)" -} - -/** - * Represents an option within a string select menu component + * A builder that creates API-compatible JSON data for string select menu options. */ declare class StringSelectMenuOptionBuilder implements JSONEncodable { data: Partial; /** - * Creates a new string select menu option from API data + * Creates a new string select menu option from API data. * * @param data - The API data to create this string select menu option with * @example - * Creating a string select menu option from an API data object + * Creating a string select menu option from an API data object: * ```ts * const selectMenuOption = new SelectMenuOptionBuilder({ * label: 'catchy label', @@ -543,48 +315,48 @@ declare class StringSelectMenuOptionBuilder implements JSONEncodable); /** - * Sets the label of this option + * Sets the label for this option. * - * @param label - The label to show on this option + * @param label - The label to use */ setLabel(label: string): this; /** - * Sets the value of this option + * Sets the value for this option. * - * @param value - The value of this option + * @param value - The value to use */ setValue(value: string): this; /** - * Sets the description of this option + * Sets the description for this option. * - * @param description - The description of this option + * @param description - The description to use */ setDescription(description: string): this; /** - * Sets whether this option is selected by default + * Sets whether this option is selected by default. * * @param isDefault - Whether this option is selected by default */ setDefault(isDefault?: boolean): this; /** - * Sets the emoji to display on this option + * Sets the emoji to display for this option. * - * @param emoji - The emoji to display on this option + * @param emoji - The emoji to use */ setEmoji(emoji: APIMessageComponentEmoji): this; /** - * {@inheritDoc ComponentBuilder.toJSON} + * {@inheritDoc BaseSelectMenuBuilder.toJSON} */ toJSON(): APISelectMenuOption; } @@ -636,78 +408,86 @@ declare const channelTypesValidator: _sapphire_shapeshift.ArrayValidator; declare function validateRequiredButtonParameters(style?: ButtonStyle, label?: string, emoji?: APIMessageComponentEmoji, customId?: string, url?: string): void; -declare const Assertions$4_customIdValidator: typeof customIdValidator; -declare const Assertions$4_emojiValidator: typeof emojiValidator; -declare const Assertions$4_disabledValidator: typeof disabledValidator; declare const Assertions$4_buttonLabelValidator: typeof buttonLabelValidator; declare const Assertions$4_buttonStyleValidator: typeof buttonStyleValidator; -declare const Assertions$4_minMaxValidator: typeof minMaxValidator; -declare const Assertions$4_labelValueDescriptionValidator: typeof labelValueDescriptionValidator; +declare const Assertions$4_channelTypesValidator: typeof channelTypesValidator; +declare const Assertions$4_customIdValidator: typeof customIdValidator; +declare const Assertions$4_defaultValidator: typeof defaultValidator; +declare const Assertions$4_disabledValidator: typeof disabledValidator; +declare const Assertions$4_emojiValidator: typeof emojiValidator; declare const Assertions$4_jsonOptionValidator: typeof jsonOptionValidator; +declare const Assertions$4_labelValueDescriptionValidator: typeof labelValueDescriptionValidator; +declare const Assertions$4_minMaxValidator: typeof minMaxValidator; declare const Assertions$4_optionValidator: typeof optionValidator; -declare const Assertions$4_optionsValidator: typeof optionsValidator; declare const Assertions$4_optionsLengthValidator: typeof optionsLengthValidator; -declare const Assertions$4_validateRequiredSelectMenuParameters: typeof validateRequiredSelectMenuParameters; -declare const Assertions$4_defaultValidator: typeof defaultValidator; -declare const Assertions$4_validateRequiredSelectMenuOptionParameters: typeof validateRequiredSelectMenuOptionParameters; -declare const Assertions$4_channelTypesValidator: typeof channelTypesValidator; +declare const Assertions$4_optionsValidator: typeof optionsValidator; declare const Assertions$4_urlValidator: typeof urlValidator; declare const Assertions$4_validateRequiredButtonParameters: typeof validateRequiredButtonParameters; +declare const Assertions$4_validateRequiredSelectMenuOptionParameters: typeof validateRequiredSelectMenuOptionParameters; +declare const Assertions$4_validateRequiredSelectMenuParameters: typeof validateRequiredSelectMenuParameters; declare namespace Assertions$4 { export { - Assertions$4_customIdValidator as customIdValidator, - Assertions$4_emojiValidator as emojiValidator, - Assertions$4_disabledValidator as disabledValidator, Assertions$4_buttonLabelValidator as buttonLabelValidator, Assertions$4_buttonStyleValidator as buttonStyleValidator, - placeholderValidator$1 as placeholderValidator, - Assertions$4_minMaxValidator as minMaxValidator, - Assertions$4_labelValueDescriptionValidator as labelValueDescriptionValidator, + Assertions$4_channelTypesValidator as channelTypesValidator, + Assertions$4_customIdValidator as customIdValidator, + Assertions$4_defaultValidator as defaultValidator, + Assertions$4_disabledValidator as disabledValidator, + Assertions$4_emojiValidator as emojiValidator, Assertions$4_jsonOptionValidator as jsonOptionValidator, + Assertions$4_labelValueDescriptionValidator as labelValueDescriptionValidator, + Assertions$4_minMaxValidator as minMaxValidator, Assertions$4_optionValidator as optionValidator, - Assertions$4_optionsValidator as optionsValidator, Assertions$4_optionsLengthValidator as optionsLengthValidator, - Assertions$4_validateRequiredSelectMenuParameters as validateRequiredSelectMenuParameters, - Assertions$4_defaultValidator as defaultValidator, - Assertions$4_validateRequiredSelectMenuOptionParameters as validateRequiredSelectMenuOptionParameters, - Assertions$4_channelTypesValidator as channelTypesValidator, + Assertions$4_optionsValidator as optionsValidator, + placeholderValidator$1 as placeholderValidator, Assertions$4_urlValidator as urlValidator, Assertions$4_validateRequiredButtonParameters as validateRequiredButtonParameters, + Assertions$4_validateRequiredSelectMenuOptionParameters as validateRequiredSelectMenuOptionParameters, + Assertions$4_validateRequiredSelectMenuParameters as validateRequiredSelectMenuParameters, }; } +/** + * Any action row component data represented as an object. + */ type AnyAPIActionRowComponent = APIActionRowComponent | APIActionRowComponentTypes; /** - * Represents a discord component + * The base component builder that contains common symbols for all sorts of components. * * @typeParam DataType - The type of internal API data that is stored within the component */ declare abstract class ComponentBuilder> = APIBaseComponent> implements JSONEncodable { /** - * The API data associated with this component + * The API data associated with this component. */ readonly data: Partial; /** - * Serializes this component to an API-compatible JSON object + * Serializes this builder to API-compatible JSON data. * * @remarks * This method runs validations on the data before serializing it. * As such, it may throw an error if the data is invalid. */ abstract toJSON(): AnyAPIActionRowComponent; + /** + * Constructs a new kind of component. + * + * @param data - The data to construct a component out of + */ constructor(data: Partial); } /** - * Represents a button component + * A builder that creates API-compatible JSON data for buttons. */ declare class ButtonBuilder extends ComponentBuilder { /** - * Creates a new button from API data + * Creates a new button from API data. * * @param data - The API data to create this button with * @example - * Creating a button from an API data object + * Creating a button from an API data object: * ```ts * const button = new ButtonBuilder({ * custom_id: 'a cool button', @@ -720,7 +500,7 @@ declare class ButtonBuilder extends ComponentBuilder { * }); * ``` * @example - * Creating a button using setters and API data + * Creating a button using setters and API data: * ```ts * const button = new ButtonBuilder({ * style: ButtonStyle.Secondary, @@ -732,44 +512,44 @@ declare class ButtonBuilder extends ComponentBuilder { */ constructor(data?: Partial); /** - * Sets the style of this button + * Sets the style of this button. * - * @param style - The style of the button + * @param style - The style to use */ setStyle(style: ButtonStyle): this; /** - * Sets the URL for this button + * Sets the URL for this button. * * @remarks * This method is only available to buttons using the `Link` button style. - * Only three types of URL schemes are currently supported: `https://`, `http://` and `discord://` - * @param url - The URL to open when this button is clicked + * Only three types of URL schemes are currently supported: `https://`, `http://`, and `discord://`. + * @param url - The URL to use */ setURL(url: string): this; /** - * Sets the custom id for this button + * Sets the custom id for this button. * * @remarks * This method is only applicable to buttons that are not using the `Link` button style. - * @param customId - The custom id to use for this button + * @param customId - The custom id to use */ setCustomId(customId: string): this; /** - * Sets the emoji to display on this button + * Sets the emoji to display on this button. * - * @param emoji - The emoji to display on this button + * @param emoji - The emoji to use */ setEmoji(emoji: APIMessageComponentEmoji): this; /** - * Sets whether this button is disabled + * Sets whether this button is disabled. * * @param disabled - Whether to disable this button */ setDisabled(disabled?: boolean): this; /** - * Sets the label for this button + * Sets the label for this button. * - * @param label - The label to display on this button + * @param label - The label to use */ setLabel(label: string): this; /** @@ -778,47 +558,58 @@ declare class ButtonBuilder extends ComponentBuilder { toJSON(): APIButtonComponent; } -declare class BaseSelectMenuBuilder extends ComponentBuilder { +/** + * The base select menu builder that contains common symbols for select menu builders. + * + * @typeParam SelectMenuType - The type of select menu this would be instantiated for. + */ +declare abstract class BaseSelectMenuBuilder extends ComponentBuilder { /** - * Sets the placeholder for this select menu + * Sets the placeholder for this select menu. * - * @param placeholder - The placeholder to use for this select menu + * @param placeholder - The placeholder to use */ setPlaceholder(placeholder: string): this; /** - * Sets the minimum values that must be selected in the select menu + * Sets the minimum values that must be selected in the select menu. * * @param minValues - The minimum values that must be selected */ setMinValues(minValues: number): this; /** - * Sets the maximum values that must be selected in the select menu + * Sets the maximum values that must be selected in the select menu. * * @param maxValues - The maximum values that must be selected */ setMaxValues(maxValues: number): this; /** - * Sets the custom id for this select menu + * Sets the custom id for this select menu. * - * @param customId - The custom id to use for this select menu + * @param customId - The custom id to use */ setCustomId(customId: string): this; /** - * Sets whether this select menu is disabled + * Sets whether this select menu is disabled. * * @param disabled - Whether this select menu is disabled */ setDisabled(disabled?: boolean): this; + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON(): SelectMenuType; } +/** + * A builder that creates API-compatible JSON data for channel select menus. + */ declare class ChannelSelectMenuBuilder extends BaseSelectMenuBuilder { /** - * Creates a new select menu from API data + * Creates a new select menu from API data. * * @param data - The API data to create this select menu with * @example - * Creating a select menu from an API data object + * Creating a select menu from an API data object: * ```ts * const selectMenu = new ChannelSelectMenuBuilder({ * custom_id: 'a cool select menu', @@ -827,31 +618,44 @@ declare class ChannelSelectMenuBuilder extends BaseSelectMenuBuilder); + /** + * Adds channel types to this select menu. + * + * @param types - The channel types to use + */ addChannelTypes(...types: RestOrArray): this; + /** + * Sets channel types for this select menu. + * + * @param types - The channel types to use + */ setChannelTypes(...types: RestOrArray): this; /** - * {@inheritDoc ComponentBuilder.toJSON} + * {@inheritDoc BaseSelectMenuBuilder.toJSON} */ toJSON(): APIChannelSelectComponent; } +/** + * A builder that creates API-compatible JSON data for mentionable select menus. + */ declare class MentionableSelectMenuBuilder extends BaseSelectMenuBuilder { /** - * Creates a new select menu from API data + * Creates a new select menu from API data. * * @param data - The API data to create this select menu with * @example - * Creating a select menu from an API data object + * Creating a select menu from an API data object: * ```ts * const selectMenu = new MentionableSelectMenuBuilder({ * custom_id: 'a cool select menu', @@ -860,24 +664,27 @@ declare class MentionableSelectMenuBuilder extends BaseSelectMenuBuilder); } +/** + * A builder that creates API-compatible JSON data for role select menus. + */ declare class RoleSelectMenuBuilder extends BaseSelectMenuBuilder { /** - * Creates a new select menu from API data + * Creates a new select menu from API data. * * @param data - The API data to create this select menu with * @example - * Creating a select menu from an API data object + * Creating a select menu from an API data object: * ```ts * const selectMenu = new RoleSelectMenuBuilder({ * custom_id: 'a cool select menu', @@ -886,31 +693,31 @@ declare class RoleSelectMenuBuilder extends BaseSelectMenuBuilder); } /** - * Represents a string select menu component + * A builder that creates API-compatible JSON data for string select menus. */ declare class StringSelectMenuBuilder extends BaseSelectMenuBuilder { /** - * The options within this select menu + * The options within this select menu. */ readonly options: StringSelectMenuOptionBuilder[]; /** - * Creates a new select menu from API data + * Creates a new select menu from API data. * * @param data - The API data to create this select menu with * @example - * Creating a select menu from an API data object + * Creating a select menu from an API data object: * ```ts * const selectMenu = new StringSelectMenuBuilder({ * custom_id: 'a cool select menu', @@ -924,7 +731,7 @@ declare class StringSelectMenuBuilder extends BaseSelectMenuBuilder); /** - * Adds options to this select menu + * Adds options to this select menu. * - * @param options - The options to add to this select menu - * @returns + * @param options - The options to add */ addOptions(...options: RestOrArray): this; /** - * Sets the options on this select menu + * Sets the options for this select menu. * - * @param options - The options to set on this select menu + * @param options - The options to set */ setOptions(...options: RestOrArray): this; /** - * {@inheritDoc ComponentBuilder.toJSON} + * Removes, replaces, or inserts options for this select menu. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice()}. + * It's useful for modifying and adjusting the order of existing options. + * @example + * Remove the first option: + * ```ts + * selectMenu.spliceOptions(0, 1); + * ``` + * @example + * Remove the first n option: + * ```ts + * const n = 4; + * selectMenu.spliceOptions(0, n); + * ``` + * @example + * Remove the last option: + * ```ts + * selectMenu.spliceOptions(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of options to remove + * @param options - The replacing option objects or builders + */ + spliceOptions(index: number, deleteCount: number, ...options: RestOrArray): this; + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} */ toJSON(): APIStringSelectComponent; } +/** + * A builder that creates API-compatible JSON data for user select menus. + */ declare class UserSelectMenuBuilder extends BaseSelectMenuBuilder { /** - * Creates a new select menu from API data + * Creates a new select menu from API data. * * @param data - The API data to create this select menu with * @example - * Creating a select menu from an API data object + * Creating a select menu from an API data object: * ```ts * const selectMenu = new UserSelectMenuBuilder({ * custom_id: 'a cool select menu', @@ -971,24 +808,27 @@ declare class UserSelectMenuBuilder extends BaseSelectMenuBuilder); } +/** + * A builder that creates API-compatible JSON data for text inputs. + */ declare class TextInputBuilder extends ComponentBuilder implements Equatable> { /** - * Creates a new text input from API data + * Creates a new text input from API data. * * @param data - The API data to create this text input with * @example - * Creating a select menu option from an API data object + * Creating a select menu option from an API data object: * ```ts * const textInput = new TextInputBuilder({ * custom_id: 'a cool select menu', @@ -997,7 +837,7 @@ declare class TextInputBuilder extends ComponentBuilder i * }); * ``` * @example - * Creating a select menu option using setters and API data + * Creating a select menu option using setters and API data: * ```ts * const textInput = new TextInputBuilder({ * label: 'Type something else', @@ -1010,49 +850,49 @@ declare class TextInputBuilder extends ComponentBuilder i type?: ComponentType.TextInput; }); /** - * Sets the custom id for this text input + * Sets the custom id for this text input. * - * @param customId - The custom id of this text input + * @param customId - The custom id to use */ setCustomId(customId: string): this; /** - * Sets the label for this text input + * Sets the label for this text input. * - * @param label - The label for this text input + * @param label - The label to use */ setLabel(label: string): this; /** - * Sets the style for this text input + * Sets the style for this text input. * - * @param style - The style for this text input + * @param style - The style to use */ setStyle(style: TextInputStyle): this; /** - * Sets the minimum length of text for this text input + * Sets the minimum length of text for this text input. * * @param minLength - The minimum length of text for this text input */ setMinLength(minLength: number): this; /** - * Sets the maximum length of text for this text input + * Sets the maximum length of text for this text input. * * @param maxLength - The maximum length of text for this text input */ setMaxLength(maxLength: number): this; /** - * Sets the placeholder of this text input + * Sets the placeholder for this text input. * - * @param placeholder - The placeholder of this text input + * @param placeholder - The placeholder to use */ setPlaceholder(placeholder: string): this; /** - * Sets the value of this text input + * Sets the value for this text input. * - * @param value - The value for this text input + * @param value - The value to use */ setValue(value: string): this; /** - * Sets whether this text input is required + * Sets whether this text input is required. * * @param required - Whether this text input is required */ @@ -1067,27 +907,42 @@ declare class TextInputBuilder extends ComponentBuilder i equals(other: APITextInputComponent | JSONEncodable): boolean; } +/** + * The builders that may be used for messages. + */ type MessageComponentBuilder = ActionRowBuilder | MessageActionRowComponentBuilder; +/** + * The builders that may be used for modals. + */ type ModalComponentBuilder = ActionRowBuilder | ModalActionRowComponentBuilder; +/** + * The builders that may be used within an action row for messages. + */ type MessageActionRowComponentBuilder = ButtonBuilder | ChannelSelectMenuBuilder | MentionableSelectMenuBuilder | RoleSelectMenuBuilder | StringSelectMenuBuilder | UserSelectMenuBuilder; +/** + * The builders that may be used within an action row for modals. + */ type ModalActionRowComponentBuilder = TextInputBuilder; +/** + * Any builder. + */ type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalActionRowComponentBuilder; /** - * Represents an action row component + * A builder that creates API-compatible JSON data for action rows. * * @typeParam T - The types of components this action row holds */ declare class ActionRowBuilder extends ComponentBuilder> { /** - * The components within this action row + * The components within this action row. */ readonly components: T[]; /** - * Creates a new action row from API data + * Creates a new action row from API data. * * @param data - The API data to create this action row with * @example - * Creating an action row from an API data object + * Creating an action row from an API data object: * ```ts * const actionRow = new ActionRowBuilder({ * components: [ @@ -1101,7 +956,7 @@ declare class ActionRowBuilder extends ComponentB * }); * ``` * @example - * Creating an action row using setters and API data + * Creating an action row using setters and API data: * ```ts * const actionRow = new ActionRowBuilder({ * components: [ @@ -1120,13 +975,13 @@ declare class ActionRowBuilder extends ComponentB /** * Adds components to this action row. * - * @param components - The components to add to this action row. + * @param components - The components to add */ addComponents(...components: RestOrArray): this; /** - * Sets the components in this action row + * Sets components for this action row. * - * @param components - The components to set this row to + * @param components - The components to set */ setComponents(...components: RestOrArray): this; /** @@ -1135,24 +990,58 @@ declare class ActionRowBuilder extends ComponentB toJSON(): APIActionRowComponent>; } +/** + * Components here are mapped to their respective builder. + */ interface MappedComponentTypes { + /** + * The action row component type is associated with an {@link ActionRowBuilder}. + */ [ComponentType.ActionRow]: ActionRowBuilder; + /** + * The button component type is associated with an {@link ButtonBuilder}. + */ [ComponentType.Button]: ButtonBuilder; + /** + * The string select component type is associated with an {@link StringSelectMenuBuilder}. + */ [ComponentType.StringSelect]: StringSelectMenuBuilder; + /** + * The text inpiut component type is associated with an {@link TextInputBuilder}. + */ [ComponentType.TextInput]: TextInputBuilder; + /** + * The user select component type is associated with an {@link UserSelectMenuBuilder}. + */ [ComponentType.UserSelect]: UserSelectMenuBuilder; + /** + * The role select component type is associated with an {@link RoleSelectMenuBuilder}. + */ [ComponentType.RoleSelect]: RoleSelectMenuBuilder; + /** + * The mentionable select component type is associated with an {@link MentionableSelectMenuBuilder}. + */ [ComponentType.MentionableSelect]: MentionableSelectMenuBuilder; + /** + * The channel select component type is associated with an {@link ChannelSelectMenuBuilder}. + */ [ComponentType.ChannelSelect]: ChannelSelectMenuBuilder; } /** - * Factory for creating components from API data + * Factory for creating components from API data. * - * @param data - The api data to transform to a component class + * @typeParam T - The type of component to use + * @param data - The API data to transform to a component class */ declare function createComponentBuilder(data: (APIModalComponent | APIMessageComponent) & { type: T; }): MappedComponentTypes[T]; +/** + * Factory for creating components from API data. + * + * @typeParam C - The type of component to use + * @param data - The API data to transform to a component class + */ declare function createComponentBuilder(data: C): C; declare const textInputStyleValidator: _sapphire_shapeshift.NativeEnumValidator; @@ -1164,52 +1053,66 @@ declare const placeholderValidator: _sapphire_shapeshift.StringValidator declare const labelValidator: _sapphire_shapeshift.StringValidator; declare function validateRequiredParameters$3(customId?: string, style?: TextInputStyle, label?: string): void; -declare const Assertions$3_textInputStyleValidator: typeof textInputStyleValidator; -declare const Assertions$3_minLengthValidator: typeof minLengthValidator; +declare const Assertions$3_labelValidator: typeof labelValidator; declare const Assertions$3_maxLengthValidator: typeof maxLengthValidator; +declare const Assertions$3_minLengthValidator: typeof minLengthValidator; +declare const Assertions$3_placeholderValidator: typeof placeholderValidator; declare const Assertions$3_requiredValidator: typeof requiredValidator; +declare const Assertions$3_textInputStyleValidator: typeof textInputStyleValidator; declare const Assertions$3_valueValidator: typeof valueValidator; -declare const Assertions$3_placeholderValidator: typeof placeholderValidator; -declare const Assertions$3_labelValidator: typeof labelValidator; declare namespace Assertions$3 { export { - Assertions$3_textInputStyleValidator as textInputStyleValidator, - Assertions$3_minLengthValidator as minLengthValidator, + Assertions$3_labelValidator as labelValidator, Assertions$3_maxLengthValidator as maxLengthValidator, - Assertions$3_requiredValidator as requiredValidator, - Assertions$3_valueValidator as valueValidator, + Assertions$3_minLengthValidator as minLengthValidator, Assertions$3_placeholderValidator as placeholderValidator, - Assertions$3_labelValidator as labelValidator, + Assertions$3_requiredValidator as requiredValidator, + Assertions$3_textInputStyleValidator as textInputStyleValidator, validateRequiredParameters$3 as validateRequiredParameters, + Assertions$3_valueValidator as valueValidator, }; } +/** + * A builder that creates API-compatible JSON data for modals. + */ declare class ModalBuilder implements JSONEncodable { + /** + * The API data associated with this modal. + */ readonly data: Partial; + /** + * The components within this modal. + */ readonly components: ActionRowBuilder[]; + /** + * Creates a new modal from API data. + * + * @param data - The API data to create this modal with + */ constructor({ components, ...data }?: Partial); /** - * Sets the title of the modal + * Sets the title of this modal. * - * @param title - The title of the modal + * @param title - The title to use */ setTitle(title: string): this; /** - * Sets the custom id of the modal + * Sets the custom id of this modal. * - * @param customId - The custom id of this modal + * @param customId - The custom id to use */ setCustomId(customId: string): this; /** - * Adds components to this modal + * Adds components to this modal. * - * @param components - The components to add to this modal + * @param components - The components to add */ addComponents(...components: RestOrArray | APIActionRowComponent>): this; /** - * Sets the components in this modal + * Sets components for this modal. * - * @param components - The components to set this modal to + * @param components - The components to set */ setComponents(...components: RestOrArray>): this; /** @@ -1222,140 +1125,252 @@ declare const titleValidator: _sapphire_shapeshift.StringValidator; declare const componentsValidator: _sapphire_shapeshift.ArrayValidator<[ActionRowBuilder, ...ActionRowBuilder[]], ActionRowBuilder>; declare function validateRequiredParameters$2(customId?: string, title?: string, components?: ActionRowBuilder[]): void; -declare const Assertions$2_titleValidator: typeof titleValidator; declare const Assertions$2_componentsValidator: typeof componentsValidator; +declare const Assertions$2_titleValidator: typeof titleValidator; declare namespace Assertions$2 { export { - Assertions$2_titleValidator as titleValidator, Assertions$2_componentsValidator as componentsValidator, + Assertions$2_titleValidator as titleValidator, validateRequiredParameters$2 as validateRequiredParameters, }; } +/** + * This mixin holds name and description symbols for slash commands. + */ declare class SharedNameAndDescription { + /** + * The name of this command. + */ readonly name: string; + /** + * The name localizations of this command. + */ readonly name_localizations?: LocalizationMap; + /** + * The description of this command. + */ readonly description: string; + /** + * The description localizations of this command. + */ readonly description_localizations?: LocalizationMap; /** - * Sets the name + * Sets the name of this command. * - * @param name - The name + * @param name - The name to use */ setName(name: string): this; /** - * Sets the description + * Sets the description of this command. * - * @param description - The description + * @param description - The description to use */ setDescription(description: string): this; /** - * Sets a name localization + * SSets a name localization for this command. * - * @param locale - The locale to set a description for - * @param localizedName - The localized description for the given locale + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` */ setNameLocalization(locale: LocaleString, localizedName: string | null): this; /** - * Sets the name localizations + * Sets the name localizations for this command. * - * @param localizedNames - The dictionary of localized descriptions to set + * @param localizedNames - The object of localized names to set */ setNameLocalizations(localizedNames: LocalizationMap | null): this; /** - * Sets a description localization + * Sets a description localization for this command. * - * @param locale - The locale to set a description for + * @param locale - The locale to set * @param localizedDescription - The localized description for the given locale */ setDescriptionLocalization(locale: LocaleString, localizedDescription: string | null): this; /** - * Sets the description localizations + * Sets the description localizations for this command. * - * @param localizedDescriptions - The dictionary of localized descriptions to set + * @param localizedDescriptions - The object of localized descriptions to set */ setDescriptionLocalizations(localizedDescriptions: LocalizationMap | null): this; } +/** + * The base application command option builder that contains common symbols for application command builders. + */ declare abstract class ApplicationCommandOptionBase extends SharedNameAndDescription { + /** + * The type of this option. + */ abstract readonly type: ApplicationCommandOptionType; + /** + * Whether this option is required. + * + * @defaultValue `false` + */ readonly required: boolean; /** - * Marks the option as required + * Sets whether this option is required. * - * @param required - If this option should be required + * @param required - Whether this option should be required */ setRequired(required: boolean): this; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ abstract toJSON(): APIApplicationCommandBasicOption; + /** + * This method runs required validators on this builder. + */ protected runRequiredValidations(): void; } +/** + * A slash command attachment option. + */ declare class SlashCommandAttachmentOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.Attachment; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandAttachmentOption; } +/** + * A slash command boolean option. + */ declare class SlashCommandBooleanOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.Boolean; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandBooleanOption; } +/** + * The allowed channel types used for a channel option in a slash command builder. + * + * @privateRemarks This can't be dynamic because const enums are erased at runtime. + * @internal + */ declare const allowedChannelTypes: readonly [ChannelType.GuildText, ChannelType.GuildVoice, ChannelType.GuildCategory, ChannelType.GuildAnnouncement, ChannelType.AnnouncementThread, ChannelType.PublicThread, ChannelType.PrivateThread, ChannelType.GuildStageVoice, ChannelType.GuildForum]; -type ApplicationCommandOptionAllowedChannelTypes = typeof allowedChannelTypes[number]; +/** + * The type of allowed channel types used for a channel option. + */ +type ApplicationCommandOptionAllowedChannelTypes = (typeof allowedChannelTypes)[number]; +/** + * This mixin holds channel type symbols used for options. + */ declare class ApplicationCommandOptionChannelTypesMixin { + /** + * The channel types of this option. + */ readonly channel_types?: ApplicationCommandOptionAllowedChannelTypes[]; /** - * Adds channel types to this option + * Adds channel types to this option. * - * @param channelTypes - The channel types to add + * @param channelTypes - The channel types */ addChannelTypes(...channelTypes: ApplicationCommandOptionAllowedChannelTypes[]): this; } +/** + * A slash command channel option. + */ declare class SlashCommandChannelOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.Channel; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandChannelOption; } interface SlashCommandChannelOption extends ApplicationCommandOptionChannelTypesMixin { } +/** + * This mixin holds minimum and maximum symbols used for options. + */ declare abstract class ApplicationCommandNumericOptionMinMaxValueMixin { + /** + * The maximum value of this option. + */ readonly max_value?: number; + /** + * The minimum value of this option. + */ readonly min_value?: number; /** - * Sets the maximum number value of this option + * Sets the maximum number value of this option. * * @param max - The maximum value this option can be */ abstract setMaxValue(max: number): this; /** - * Sets the minimum number value of this option + * Sets the minimum number value of this option. * * @param min - The minimum value this option can be */ abstract setMinValue(min: number): this; } +/** + * This mixin holds choices and autocomplete symbols used for options. + */ declare class ApplicationCommandOptionWithChoicesAndAutocompleteMixin { + /** + * The choices of this option. + */ readonly choices?: APIApplicationCommandOptionChoice[]; + /** + * Whether this option utilizes autocomplete. + */ readonly autocomplete?: boolean; + /** + * The type of this option. + * + * @privateRemarks Since this is present and this is a mixin, this is needed. + */ readonly type: ApplicationCommandOptionType; /** - * Adds multiple choices for this option + * Adds multiple choices to this option. * * @param choices - The choices to add */ addChoices(...choices: APIApplicationCommandOptionChoice[]): this; + /** + * Sets multiple choices for this option. + * + * @param choices - The choices to set + */ setChoices[]>(...choices: Input): this; /** - * Marks the option as autocompletable + * Whether this option uses autocomplete. * - * @param autocomplete - If this option should be autocompletable + * @param autocomplete - Whether this option should use autocomplete */ setAutocomplete(autocomplete: boolean): this; } +/** + * A slash command integer option. + */ declare class SlashCommandIntegerOption extends ApplicationCommandOptionBase implements ApplicationCommandNumericOptionMinMaxValueMixin { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.Integer; /** * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} @@ -1365,17 +1380,35 @@ declare class SlashCommandIntegerOption extends ApplicationCommandOptionBase imp * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} */ setMinValue(min: number): this; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandIntegerOption; } interface SlashCommandIntegerOption extends ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin { } +/** + * A slash command mentionable option. + */ declare class SlashCommandMentionableOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.Mentionable; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandMentionableOption; } +/** + * A slash command number option. + */ declare class SlashCommandNumberOption extends ApplicationCommandOptionBase implements ApplicationCommandNumericOptionMinMaxValueMixin { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.Number; /** * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} @@ -1385,19 +1418,43 @@ declare class SlashCommandNumberOption extends ApplicationCommandOptionBase impl * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} */ setMinValue(min: number): this; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandNumberOption; } interface SlashCommandNumberOption extends ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin { } +/** + * A slash command role option. + */ declare class SlashCommandRoleOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.Role; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandRoleOption; } +/** + * A slash command string option. + */ declare class SlashCommandStringOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.String; + /** + * The maximum length of this option. + */ readonly max_length?: number; + /** + * The minimum length of this option. + */ readonly min_length?: number; /** * Sets the maximum length of this string option. @@ -1411,179 +1468,217 @@ declare class SlashCommandStringOption extends ApplicationCommandOptionBase { * @param min - The minimum length this option can be */ setMinLength(min: number): this; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandStringOption; } interface SlashCommandStringOption extends ApplicationCommandOptionWithChoicesAndAutocompleteMixin { } +/** + * A slash command user option. + */ declare class SlashCommandUserOption extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ readonly type: ApplicationCommandOptionType.User; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON(): APIApplicationCommandUserOption; } +/** + * This mixin holds symbols that can be shared in slash command options. + * + * @typeParam ShouldOmitSubcommandFunctions - Whether to omit subcommand functions. + */ declare class SharedSlashCommandOptions { readonly options: ToAPIApplicationCommandOptions[]; /** - * Adds a boolean option + * Adds a boolean option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addBooleanOption(input: SlashCommandBooleanOption | ((builder: SlashCommandBooleanOption) => SlashCommandBooleanOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; /** - * Adds a user option + * Adds a user option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addUserOption(input: SlashCommandUserOption | ((builder: SlashCommandUserOption) => SlashCommandUserOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; /** - * Adds a channel option + * Adds a channel option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addChannelOption(input: SlashCommandChannelOption | ((builder: SlashCommandChannelOption) => SlashCommandChannelOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; /** - * Adds a role option + * Adds a role option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addRoleOption(input: SlashCommandRoleOption | ((builder: SlashCommandRoleOption) => SlashCommandRoleOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; /** - * Adds an attachment option + * Adds an attachment option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addAttachmentOption(input: SlashCommandAttachmentOption | ((builder: SlashCommandAttachmentOption) => SlashCommandAttachmentOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; /** - * Adds a mentionable option + * Adds a mentionable option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addMentionableOption(input: SlashCommandMentionableOption | ((builder: SlashCommandMentionableOption) => SlashCommandMentionableOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; /** - * Adds a string option + * Adds a string option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addStringOption(input: Omit | Omit | SlashCommandStringOption | ((builder: SlashCommandStringOption) => Omit | Omit | SlashCommandStringOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; /** - * Adds an integer option + * Adds an integer option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addIntegerOption(input: Omit | Omit | SlashCommandIntegerOption | ((builder: SlashCommandIntegerOption) => Omit | Omit | SlashCommandIntegerOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; /** - * Adds a number option + * Adds a number option. * - * @param input - A function that returns an option builder, or an already built builder + * @param input - A function that returns an option builder or an already built builder */ addNumberOption(input: Omit | Omit | SlashCommandNumberOption | ((builder: SlashCommandNumberOption) => Omit | Omit | SlashCommandNumberOption)): ShouldOmitSubcommandFunctions extends true ? Omit : this; + /** + * Where the actual adding magic happens. ✨ + * + * @param input - The input. What else? + * @param Instance - The instance of whatever is being added + * @internal + */ private _sharedAddOptionMethod; } /** - * Represents a folder for subcommands + * Represents a folder for subcommands. * - * For more information, go to https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups + * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups} */ declare class SlashCommandSubcommandGroupBuilder implements ToAPIApplicationCommandOptions { /** - * The name of this subcommand group + * The name of this subcommand group. */ readonly name: string; /** - * The description of this subcommand group + * The description of this subcommand group. */ readonly description: string; /** - * The subcommands part of this subcommand group + * The subcommands within this subcommand group. */ readonly options: SlashCommandSubcommandBuilder[]; /** - * Adds a new subcommand to this group + * Adds a new subcommand to this group. * - * @param input - A function that returns a subcommand builder, or an already built builder + * @param input - A function that returns a subcommand builder or an already built builder */ addSubcommand(input: SlashCommandSubcommandBuilder | ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder)): this; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON(): APIApplicationCommandSubcommandGroupOption; } interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription { } /** - * Represents a subcommand + * A builder that creates API-compatible JSON data for slash command subcommands. * - * For more information, go to https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups + * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups} */ declare class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions { /** - * The name of this subcommand + * The name of this subcommand. */ readonly name: string; /** - * The description of this subcommand + * The description of this subcommand. */ readonly description: string; /** - * The options of this subcommand + * The options within this subcommand. */ readonly options: ApplicationCommandOptionBase[]; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON(): APIApplicationCommandSubcommandOption; } interface SlashCommandSubcommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions { } +/** + * A builder that creates API-compatible JSON data for slash commands. + */ declare class SlashCommandBuilder { /** - * The name of this slash command + * The name of this command. */ readonly name: string; /** - * The localized names for this command + * The name localizations of this command. */ readonly name_localizations?: LocalizationMap; /** - * The description of this slash command + * The description of this command. */ readonly description: string; /** - * The localized descriptions for this command + * The description localizations of this command. */ readonly description_localizations?: LocalizationMap; /** - * The options of this slash command + * The options of this command. */ readonly options: ToAPIApplicationCommandOptions[]; /** - * Whether the command is enabled by default when the app is added to a guild + * Whether this command is enabled by default when the application is added to a guild. * - * @deprecated This property is deprecated and will be removed in the future. - * You should use {@link (SlashCommandBuilder:class).setDefaultMemberPermissions} or {@link (SlashCommandBuilder:class).setDMPermission} instead. + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. */ readonly default_permission: boolean | undefined; /** - * Set of permissions represented as a bit set for the command + * The set of permissions represented as a bit set for the command. */ readonly default_member_permissions: Permissions | null | undefined; /** - * Indicates whether the command is available in DMs with the application, only for globally-scoped commands. - * By default, commands are visible. + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. */ readonly dm_permission: boolean | undefined; /** - * Returns the final data that should be sent to Discord. - * - * @remarks - * This method runs validations on the data before serializing it. - * As such, it may throw an error if the data is invalid. + * Whether this command is NSFW. */ - toJSON(): RESTPostAPIChatInputApplicationCommandsJSONBody; + readonly nsfw: boolean | undefined; /** * Sets whether the command is enabled by default when the application is added to a guild. * * @remarks * If set to `false`, you will have to later `PUT` the permissions for this command. * @param value - Whether or not to enable this command by default - * @see https://discord.com/developers/docs/interactions/application-commands#permissions - * @deprecated Use {@link (SlashCommandBuilder:class).setDefaultMemberPermissions} or {@link (SlashCommandBuilder:class).setDMPermission} instead. + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link SlashCommandBuilder.setDefaultMemberPermissions} or {@link SlashCommandBuilder.setDMPermission} instead. */ setDefaultPermission(value: boolean): this; /** @@ -1592,36 +1687,61 @@ declare class SlashCommandBuilder { * @remarks * You can set this to `'0'` to disable the command by default. * @param permissions - The permissions bit field to set - * @see https://discord.com/developers/docs/interactions/application-commands#permissions + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} */ setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined): this; /** - * Sets if the command is available in DMs with the application, only for globally-scoped commands. - * By default, commands are visible. + * Sets if the command is available in direct messages with the application. * - * @param enabled - If the command should be enabled in DMs - * @see https://discord.com/developers/docs/interactions/application-commands#permissions + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} */ setDMPermission(enabled: boolean | null | undefined): this; /** - * Adds a new subcommand group to this command + * Sets whether this command is NSFW. + * + * @param nsfw - Whether this command is NSFW + */ + setNSFW(nsfw?: boolean): this; + /** + * Adds a new subcommand group to this command. * - * @param input - A function that returns a subcommand group builder, or an already built builder + * @param input - A function that returns a subcommand group builder or an already built builder */ addSubcommandGroup(input: SlashCommandSubcommandGroupBuilder | ((subcommandGroup: SlashCommandSubcommandGroupBuilder) => SlashCommandSubcommandGroupBuilder)): SlashCommandSubcommandsOnlyBuilder; /** - * Adds a new subcommand to this command + * Adds a new subcommand to this command. * - * @param input - A function that returns a subcommand builder, or an already built builder + * @param input - A function that returns a subcommand builder or an already built builder */ addSubcommand(input: SlashCommandSubcommandBuilder | ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder)): SlashCommandSubcommandsOnlyBuilder; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON(): RESTPostAPIChatInputApplicationCommandsJSONBody; } interface SlashCommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions { } +/** + * An interface specifically for slash command subcommands. + */ interface SlashCommandSubcommandsOnlyBuilder extends Omit> { } +/** + * An interface specifically for slash command options. + */ interface SlashCommandOptionsOnlyBuilder extends SharedNameAndDescription, SharedSlashCommandOptions, Pick { } +/** + * An interface that ensures the `toJSON()` call will return something + * that can be serialized into API-compatible data. + */ interface ToAPIApplicationCommandOptions { toJSON(): APIApplicationCommandOption; } @@ -1635,76 +1755,87 @@ declare function validateDefaultPermission$1(value: unknown): asserts value is b declare function validateRequired(required: unknown): asserts required is boolean; declare function validateChoicesLength(amountAdding: number, choices?: APIApplicationCommandOptionChoice[]): void; declare function assertReturnOfBuilder(input: unknown, ExpectedInstanceOf: new () => T): asserts input is T; -declare const localizationMapPredicate: _sapphire_shapeshift.UnionValidator<_sapphire_shapeshift.UndefinedToOptional>> | null | undefined>; +declare const localizationMapPredicate: _sapphire_shapeshift.UnionValidator<_sapphire_shapeshift.UndefinedToOptional>> | null | undefined>; declare function validateLocalizationMap(value: unknown): asserts value is LocalizationMap; declare function validateDMPermission$1(value: unknown): asserts value is boolean | null | undefined; declare function validateDefaultMemberPermissions$1(permissions: unknown): string | null | undefined; +declare function validateNSFW(value: unknown): asserts value is boolean; +declare const Assertions$1_assertReturnOfBuilder: typeof assertReturnOfBuilder; +declare const Assertions$1_localizationMapPredicate: typeof localizationMapPredicate; +declare const Assertions$1_validateChoicesLength: typeof validateChoicesLength; declare const Assertions$1_validateDescription: typeof validateDescription; declare const Assertions$1_validateLocale: typeof validateLocale; +declare const Assertions$1_validateLocalizationMap: typeof validateLocalizationMap; declare const Assertions$1_validateMaxOptionsLength: typeof validateMaxOptionsLength; +declare const Assertions$1_validateNSFW: typeof validateNSFW; declare const Assertions$1_validateRequired: typeof validateRequired; -declare const Assertions$1_validateChoicesLength: typeof validateChoicesLength; -declare const Assertions$1_assertReturnOfBuilder: typeof assertReturnOfBuilder; -declare const Assertions$1_localizationMapPredicate: typeof localizationMapPredicate; -declare const Assertions$1_validateLocalizationMap: typeof validateLocalizationMap; declare namespace Assertions$1 { export { - validateName$1 as validateName, - Assertions$1_validateDescription as validateDescription, - Assertions$1_validateLocale as validateLocale, - Assertions$1_validateMaxOptionsLength as validateMaxOptionsLength, - validateRequiredParameters$1 as validateRequiredParameters, - validateDefaultPermission$1 as validateDefaultPermission, - Assertions$1_validateRequired as validateRequired, - Assertions$1_validateChoicesLength as validateChoicesLength, Assertions$1_assertReturnOfBuilder as assertReturnOfBuilder, Assertions$1_localizationMapPredicate as localizationMapPredicate, - Assertions$1_validateLocalizationMap as validateLocalizationMap, + Assertions$1_validateChoicesLength as validateChoicesLength, validateDMPermission$1 as validateDMPermission, validateDefaultMemberPermissions$1 as validateDefaultMemberPermissions, + validateDefaultPermission$1 as validateDefaultPermission, + Assertions$1_validateDescription as validateDescription, + Assertions$1_validateLocale as validateLocale, + Assertions$1_validateLocalizationMap as validateLocalizationMap, + Assertions$1_validateMaxOptionsLength as validateMaxOptionsLength, + Assertions$1_validateNSFW as validateNSFW, + validateName$1 as validateName, + Assertions$1_validateRequired as validateRequired, + validateRequiredParameters$1 as validateRequiredParameters, }; } +/** + * The type a context menu command can be. + */ +type ContextMenuCommandType = ApplicationCommandType.Message | ApplicationCommandType.User; +/** + * A builder that creates API-compatible JSON data for context menu commands. + */ declare class ContextMenuCommandBuilder { /** - * The name of this context menu command + * The name of this command. */ readonly name: string; /** - * The localized names for this command + * The name localizations of this command. */ readonly name_localizations?: LocalizationMap; /** - * The type of this context menu command + * The type of this command. */ readonly type: ContextMenuCommandType; /** - * Whether the command is enabled by default when the app is added to a guild + * Whether this command is enabled by default when the application is added to a guild. * - * @deprecated This property is deprecated and will be removed in the future. - * You should use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. */ readonly default_permission: boolean | undefined; /** - * Set of permissions represented as a bit set for the command + * The set of permissions represented as a bit set for the command. */ readonly default_member_permissions: Permissions | null | undefined; /** - * Indicates whether the command is available in DMs with the application, only for globally-scoped commands. - * By default, commands are visible. + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. */ readonly dm_permission: boolean | undefined; /** - * Sets the name + * Sets the name of this command. * - * @param name - The name + * @param name - The name to use */ setName(name: string): this; /** - * Sets the type + * Sets the type of this command. * - * @param type - The type + * @param type - The type to use */ setType(type: ContextMenuCommandType): this; /** @@ -1712,43 +1843,44 @@ declare class ContextMenuCommandBuilder { * * @remarks * If set to `false`, you will have to later `PUT` the permissions for this command. - * @param value - Whether or not to enable this command by default - * @see https://discord.com/developers/docs/interactions/application-commands#permissions + * @param value - Whether to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. */ setDefaultPermission(value: boolean): this; /** - * Sets the default permissions a member should have in order to run the command. + * Sets the default permissions a member should have in order to run this command. * * @remarks * You can set this to `'0'` to disable the command by default. * @param permissions - The permissions bit field to set - * @see https://discord.com/developers/docs/interactions/application-commands#permissions + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} */ setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined): this; /** - * Sets if the command is available in DMs with the application, only for globally-scoped commands. - * By default, commands are visible. + * Sets if the command is available in direct messages with the application. * - * @param enabled - If the command should be enabled in DMs - * @see https://discord.com/developers/docs/interactions/application-commands#permissions + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} */ setDMPermission(enabled: boolean | null | undefined): this; /** - * Sets a name localization + * Sets a name localization for this command. * - * @param locale - The locale to set a description for - * @param localizedName - The localized description for the given locale + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` */ setNameLocalization(locale: LocaleString, localizedName: string | null): this; /** - * Sets the name localizations + * Sets the name localizations for this command. * - * @param localizedNames - The dictionary of localized descriptions to set + * @param localizedNames - The object of localized names to set */ setNameLocalizations(localizedNames: LocalizationMap | null): this; /** - * Returns the final data that should be sent to Discord. + * Serializes this builder to API-compatible JSON data. * * @remarks * This method runs validations on the data before serializing it. @@ -1756,7 +1888,6 @@ declare class ContextMenuCommandBuilder { */ toJSON(): RESTPostAPIContextMenuApplicationCommandsJSONBody; } -type ContextMenuCommandType = ApplicationCommandType.Message | ApplicationCommandType.User; declare function validateDefaultPermission(value: unknown): asserts value is boolean; declare function validateName(name: unknown): asserts name is string; @@ -1765,33 +1896,53 @@ declare function validateRequiredParameters(name: string, type: number): void; declare function validateDMPermission(value: unknown): asserts value is boolean | null | undefined; declare function validateDefaultMemberPermissions(permissions: unknown): string | null | undefined; +declare const Assertions_validateDMPermission: typeof validateDMPermission; +declare const Assertions_validateDefaultMemberPermissions: typeof validateDefaultMemberPermissions; declare const Assertions_validateDefaultPermission: typeof validateDefaultPermission; declare const Assertions_validateName: typeof validateName; -declare const Assertions_validateType: typeof validateType; declare const Assertions_validateRequiredParameters: typeof validateRequiredParameters; -declare const Assertions_validateDMPermission: typeof validateDMPermission; -declare const Assertions_validateDefaultMemberPermissions: typeof validateDefaultMemberPermissions; +declare const Assertions_validateType: typeof validateType; declare namespace Assertions { export { + Assertions_validateDMPermission as validateDMPermission, + Assertions_validateDefaultMemberPermissions as validateDefaultMemberPermissions, Assertions_validateDefaultPermission as validateDefaultPermission, Assertions_validateName as validateName, - Assertions_validateType as validateType, Assertions_validateRequiredParameters as validateRequiredParameters, - Assertions_validateDMPermission as validateDMPermission, - Assertions_validateDefaultMemberPermissions as validateDefaultMemberPermissions, + Assertions_validateType as validateType, }; } +/** + * Calculates the length of the embed. + * + * @param data - The embed data to check + */ declare function embedLength(data: APIEmbed): number; -declare const enableValidators: () => boolean; -declare const disableValidators: () => boolean; -declare const isValidationEnabled: () => boolean; +/** + * Enables validators. + * + * @returns Whether validation is occurring. + */ +declare function enableValidators(): boolean; +/** + * Disables validators. + * + * @returns Whether validation is occurring. + */ +declare function disableValidators(): boolean; +/** + * Checks whether validation is occurring. + */ +declare function isValidationEnabled(): boolean; /** - * The {@link https://github.com/discordjs/discord.js/blob/main/packages/builders/#readme | @discordjs/builders} version + * The {@link https://github.com/discordjs/discord.js/blob/main/packages/builders#readme | @discordjs/builders} version * that you are currently using. + * + * @privateRemarks This needs to explicitly be `string` so it is not typed as a "const string" that gets injected by esbuild. */ declare const version: string; -export { ActionRowBuilder, AnyAPIActionRowComponent, AnyComponentBuilder, ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionAllowedChannelTypes, ApplicationCommandOptionBase, ApplicationCommandOptionChannelTypesMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin, BaseSelectMenuBuilder, ButtonBuilder, ChannelSelectMenuBuilder, Assertions$4 as ComponentAssertions, ComponentBuilder, Assertions as ContextMenuCommandAssertions, ContextMenuCommandBuilder, ContextMenuCommandType, Assertions$5 as EmbedAssertions, EmbedAuthorData, EmbedAuthorOptions, EmbedBuilder, EmbedFooterData, EmbedFooterOptions, EmbedImageData, Faces, IconData, MappedComponentTypes, MentionableSelectMenuBuilder, MessageActionRowComponentBuilder, MessageComponentBuilder, ModalActionRowComponentBuilder, Assertions$2 as ModalAssertions, ModalBuilder, ModalComponentBuilder, RGBTuple, RestOrArray, RoleSelectMenuBuilder, StringSelectMenuBuilder as SelectMenuBuilder, StringSelectMenuOptionBuilder as SelectMenuOptionBuilder, SharedNameAndDescription, SharedSlashCommandOptions, Assertions$1 as SlashCommandAssertions, SlashCommandAttachmentOption, SlashCommandBooleanOption, SlashCommandBuilder, SlashCommandChannelOption, SlashCommandIntegerOption, SlashCommandMentionableOption, SlashCommandNumberOption, SlashCommandOptionsOnlyBuilder, SlashCommandRoleOption, SlashCommandStringOption, SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder, SlashCommandSubcommandsOnlyBuilder, SlashCommandUserOption, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, Assertions$3 as TextInputAssertions, TextInputBuilder, TimestampStyles, TimestampStylesString, ToAPIApplicationCommandOptions, UserSelectMenuBuilder, blockQuote, bold, channelLink, channelMention, chatInputApplicationCommandMention, codeBlock, createComponentBuilder, disableValidators, embedLength, enableValidators, formatEmoji, hideLinkEmbed, hyperlink, inlineCode, isValidationEnabled, italic, messageLink, normalizeArray, quote, roleMention, spoiler, strikethrough, time, underscore, userMention, version }; +export { ActionRowBuilder, AnyAPIActionRowComponent, AnyComponentBuilder, ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionAllowedChannelTypes, ApplicationCommandOptionBase, ApplicationCommandOptionChannelTypesMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin, BaseSelectMenuBuilder, ButtonBuilder, ChannelSelectMenuBuilder, Assertions$4 as ComponentAssertions, ComponentBuilder, Assertions as ContextMenuCommandAssertions, ContextMenuCommandBuilder, ContextMenuCommandType, Assertions$5 as EmbedAssertions, EmbedAuthorData, EmbedAuthorOptions, EmbedBuilder, EmbedFooterData, EmbedFooterOptions, EmbedImageData, IconData, MappedComponentTypes, MentionableSelectMenuBuilder, MessageActionRowComponentBuilder, MessageComponentBuilder, ModalActionRowComponentBuilder, Assertions$2 as ModalAssertions, ModalBuilder, ModalComponentBuilder, RGBTuple, RestOrArray, RoleSelectMenuBuilder, StringSelectMenuBuilder as SelectMenuBuilder, StringSelectMenuOptionBuilder as SelectMenuOptionBuilder, SharedNameAndDescription, SharedSlashCommandOptions, Assertions$1 as SlashCommandAssertions, SlashCommandAttachmentOption, SlashCommandBooleanOption, SlashCommandBuilder, SlashCommandChannelOption, SlashCommandIntegerOption, SlashCommandMentionableOption, SlashCommandNumberOption, SlashCommandOptionsOnlyBuilder, SlashCommandRoleOption, SlashCommandStringOption, SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder, SlashCommandSubcommandsOnlyBuilder, SlashCommandUserOption, StringSelectMenuBuilder, StringSelectMenuOptionBuilder, Assertions$3 as TextInputAssertions, TextInputBuilder, ToAPIApplicationCommandOptions, UserSelectMenuBuilder, createComponentBuilder, disableValidators, embedLength, enableValidators, isValidationEnabled, normalizeArray, version }; diff --git a/node_modules/@discordjs/builders/dist/index.js b/node_modules/@discordjs/builders/dist/index.js index 8e6a442..456ed60 100644 --- a/node_modules/@discordjs/builders/dist/index.js +++ b/node_modules/@discordjs/builders/dist/index.js @@ -20,6 +20,10 @@ var __copyProps = (to, from, except, desc) => { }; var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default")); var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); @@ -51,7 +55,6 @@ __export(src_exports, { ContextMenuCommandBuilder: () => ContextMenuCommandBuilder, EmbedAssertions: () => Assertions_exports, EmbedBuilder: () => EmbedBuilder, - Faces: () => Faces, MentionableSelectMenuBuilder: () => MentionableSelectMenuBuilder, ModalAssertions: () => Assertions_exports4, ModalBuilder: () => ModalBuilder, @@ -77,33 +80,13 @@ __export(src_exports, { StringSelectMenuOptionBuilder: () => StringSelectMenuOptionBuilder, TextInputAssertions: () => Assertions_exports3, TextInputBuilder: () => TextInputBuilder, - TimestampStyles: () => TimestampStyles, UserSelectMenuBuilder: () => UserSelectMenuBuilder, - blockQuote: () => blockQuote, - bold: () => bold, - channelLink: () => channelLink, - channelMention: () => channelMention, - chatInputApplicationCommandMention: () => chatInputApplicationCommandMention, - codeBlock: () => codeBlock, createComponentBuilder: () => createComponentBuilder, disableValidators: () => disableValidators, embedLength: () => embedLength, enableValidators: () => enableValidators, - formatEmoji: () => formatEmoji, - hideLinkEmbed: () => hideLinkEmbed, - hyperlink: () => hyperlink, - inlineCode: () => inlineCode, isValidationEnabled: () => isValidationEnabled, - italic: () => italic, - messageLink: () => messageLink, normalizeArray: () => normalizeArray, - quote: () => quote, - roleMention: () => roleMention, - spoiler: () => spoiler, - strikethrough: () => strikethrough, - time: () => time, - underscore: () => underscore, - userMention: () => userMention, version: () => version }); module.exports = __toCommonJS(src_exports); @@ -134,9 +117,18 @@ var import_shapeshift = require("@sapphire/shapeshift"); // src/util/validation.ts var validate = true; -var enableValidators = /* @__PURE__ */ __name(() => validate = true, "enableValidators"); -var disableValidators = /* @__PURE__ */ __name(() => validate = false, "disableValidators"); -var isValidationEnabled = /* @__PURE__ */ __name(() => validate, "isValidationEnabled"); +function enableValidators() { + return validate = true; +} +__name(enableValidators, "enableValidators"); +function disableValidators() { + return validate = false; +} +__name(disableValidators, "disableValidators"); +function isValidationEnabled() { + return validate; +} +__name(isValidationEnabled, "isValidationEnabled"); // src/messages/embed/Assertions.ts var fieldNamePredicate = import_shapeshift.s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(256).setValidationEnabled(isValidationEnabled); @@ -186,22 +178,83 @@ __name(normalizeArray, "normalizeArray"); // src/messages/embed/Embed.ts var EmbedBuilder = class { + /** + * The API data associated with this embed. + */ data; + /** + * Creates a new embed from API data. + * + * @param data - The API data to create this embed with + */ constructor(data = {}) { this.data = { ...data }; if (data.timestamp) this.data.timestamp = new Date(data.timestamp).toISOString(); } + /** + * Appends fields to the embed. + * + * @remarks + * This method accepts either an array of fields or a variable number of field parameters. + * The maximum amount of fields that can be added is 25. + * @example + * Using an array: + * ```ts + * const fields: APIEmbedField[] = ...; + * const embed = new EmbedBuilder() + * .addFields(fields); + * ``` + * @example + * Using rest parameters (variadic): + * ```ts + * const embed = new EmbedBuilder() + * .addFields( + * { name: 'Field 1', value: 'Value 1' }, + * { name: 'Field 2', value: 'Value 2' }, + * ); + * ``` + * @param fields - The fields to add + */ addFields(...fields) { - fields = normalizeArray(fields); - validateFieldLength(fields.length, this.data.fields); - embedFieldsArrayPredicate.parse(fields); + const normalizedFields = normalizeArray(fields); + validateFieldLength(normalizedFields.length, this.data.fields); + embedFieldsArrayPredicate.parse(normalizedFields); if (this.data.fields) - this.data.fields.push(...fields); + this.data.fields.push(...normalizedFields); else - this.data.fields = fields; - return this; - } + this.data.fields = normalizedFields; + return this; + } + /** + * Removes, replaces, or inserts fields for this embed. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice | Array.prototype.splice()}. + * The maximum amount of fields that can be added is 25. + * + * It's useful for modifying and adjusting order of the already-existing fields of an embed. + * @example + * Remove the first field: + * ```ts + * embed.spliceFields(0, 1); + * ``` + * @example + * Remove the first n fields: + * ```ts + * const n = 4; + * embed.spliceFields(0, n); + * ``` + * @example + * Remove the last field: + * ```ts + * embed.spliceFields(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of fields to remove + * @param fields - The replacing field objects + */ spliceFields(index, deleteCount, ...fields) { validateFieldLength(fields.length - deleteCount, this.data.fields); embedFieldsArrayPredicate.parse(fields); @@ -211,10 +264,25 @@ var EmbedBuilder = class { this.data.fields = fields; return this; } + /** + * Sets the fields for this embed. + * + * @remarks + * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically, + * it splices the entire array of fields, replacing them with the provided fields. + * + * You can set a maximum of 25 fields. + * @param fields - The fields to set + */ setFields(...fields) { this.spliceFields(0, this.data.fields?.length ?? 0, ...normalizeArray(fields)); return this; } + /** + * Sets the author of this embed. + * + * @param options - The options to use + */ setAuthor(options) { if (options === null) { this.data.author = void 0; @@ -224,6 +292,11 @@ var EmbedBuilder = class { this.data.author = { name: options.name, url: options.url, icon_url: options.iconURL }; return this; } + /** + * Sets the color of this embed. + * + * @param color - The color to use + */ setColor(color) { colorPredicate.parse(color); if (Array.isArray(color)) { @@ -234,11 +307,21 @@ var EmbedBuilder = class { this.data.color = color ?? void 0; return this; } + /** + * Sets the description of this embed. + * + * @param description - The description to use + */ setDescription(description) { descriptionPredicate.parse(description); this.data.description = description ?? void 0; return this; } + /** + * Sets the footer of this embed. + * + * @param options - The footer to use + */ setFooter(options) { if (options === null) { this.data.footer = void 0; @@ -248,142 +331,71 @@ var EmbedBuilder = class { this.data.footer = { text: options.text, icon_url: options.iconURL }; return this; } + /** + * Sets the image of this embed. + * + * @param url - The image URL to use + */ setImage(url) { imageURLPredicate.parse(url); this.data.image = url ? { url } : void 0; return this; } + /** + * Sets the thumbnail of this embed. + * + * @param url - The thumbnail URL to use + */ setThumbnail(url) { imageURLPredicate.parse(url); this.data.thumbnail = url ? { url } : void 0; return this; } + /** + * Sets the timestamp of this embed. + * + * @param timestamp - The timestamp or date to use + */ setTimestamp(timestamp = Date.now()) { timestampPredicate.parse(timestamp); this.data.timestamp = timestamp ? new Date(timestamp).toISOString() : void 0; return this; } + /** + * Sets the title for this embed. + * + * @param title - The title to use + */ setTitle(title) { titlePredicate.parse(title); this.data.title = title ?? void 0; return this; } + /** + * Sets the URL of this embed. + * + * @param url - The URL to use + */ setURL(url) { urlPredicate.parse(url); this.data.url = url ?? void 0; return this; } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON() { return { ...this.data }; } }; __name(EmbedBuilder, "EmbedBuilder"); -// src/messages/formatters.ts -function codeBlock(language, content) { - return typeof content === "undefined" ? `\`\`\` -${language} -\`\`\`` : `\`\`\`${language} -${content} -\`\`\``; -} -__name(codeBlock, "codeBlock"); -function inlineCode(content) { - return `\`${content}\``; -} -__name(inlineCode, "inlineCode"); -function italic(content) { - return `_${content}_`; -} -__name(italic, "italic"); -function bold(content) { - return `**${content}**`; -} -__name(bold, "bold"); -function underscore(content) { - return `__${content}__`; -} -__name(underscore, "underscore"); -function strikethrough(content) { - return `~~${content}~~`; -} -__name(strikethrough, "strikethrough"); -function quote(content) { - return `> ${content}`; -} -__name(quote, "quote"); -function blockQuote(content) { - return `>>> ${content}`; -} -__name(blockQuote, "blockQuote"); -function hideLinkEmbed(url) { - return `<${url}>`; -} -__name(hideLinkEmbed, "hideLinkEmbed"); -function hyperlink(content, url, title) { - return title ? `[${content}](${url} "${title}")` : `[${content}](${url})`; -} -__name(hyperlink, "hyperlink"); -function spoiler(content) { - return `||${content}||`; -} -__name(spoiler, "spoiler"); -function userMention(userId) { - return `<@${userId}>`; -} -__name(userMention, "userMention"); -function channelMention(channelId) { - return `<#${channelId}>`; -} -__name(channelMention, "channelMention"); -function roleMention(roleId) { - return `<@&${roleId}>`; -} -__name(roleMention, "roleMention"); -function chatInputApplicationCommandMention(commandName, subcommandGroupName, subcommandName, commandId) { - if (typeof commandId !== "undefined") { - return ``; - } - if (typeof subcommandName !== "undefined") { - return ``; - } - return ``; -} -__name(chatInputApplicationCommandMention, "chatInputApplicationCommandMention"); -function formatEmoji(emojiId, animated = false) { - return `<${animated ? "a" : ""}:_:${emojiId}>`; -} -__name(formatEmoji, "formatEmoji"); -function channelLink(channelId, guildId) { - return `https://discord.com/channels/${guildId ?? "@me"}/${channelId}`; -} -__name(channelLink, "channelLink"); -function messageLink(channelId, messageId, guildId) { - return `${typeof guildId === "undefined" ? channelLink(channelId) : channelLink(channelId, guildId)}/${messageId}`; -} -__name(messageLink, "messageLink"); -function time(timeOrSeconds, style) { - if (typeof timeOrSeconds !== "number") { - timeOrSeconds = Math.floor((timeOrSeconds?.getTime() ?? Date.now()) / 1e3); - } - return typeof style === "string" ? `` : ``; -} -__name(time, "time"); -var TimestampStyles = { - ShortTime: "t", - LongTime: "T", - ShortDate: "d", - LongDate: "D", - ShortDateTime: "f", - LongDateTime: "F", - RelativeTime: "R" -}; -var Faces = /* @__PURE__ */ ((Faces2) => { - Faces2["Shrug"] = "\xAF\\_(\u30C4)\\_/\xAF"; - Faces2["Tableflip"] = "(\u256F\xB0\u25A1\xB0\uFF09\u256F\uFE35 \u253B\u2501\u253B"; - Faces2["Unflip"] = "\u252C\u2500\u252C \u30CE( \u309C-\u309C\u30CE)"; - return Faces2; -})(Faces || {}); +// src/index.ts +__reExport(src_exports, require("@discordjs/formatters"), module.exports); // src/components/Assertions.ts var Assertions_exports2 = {}; @@ -412,29 +424,79 @@ var import_v10 = require("discord-api-types/v10"); // src/components/selectMenu/StringSelectMenuOption.ts var StringSelectMenuOptionBuilder = class { + /** + * Creates a new string select menu option from API data. + * + * @param data - The API data to create this string select menu option with + * @example + * Creating a string select menu option from an API data object: + * ```ts + * const selectMenuOption = new SelectMenuOptionBuilder({ + * label: 'catchy label', + * value: '1', + * }); + * ``` + * @example + * Creating a string select menu option using setters and API data: + * ```ts + * const selectMenuOption = new SelectMenuOptionBuilder({ + * default: true, + * value: '1', + * }) + * .setLabel('woah'); + * ``` + */ constructor(data = {}) { this.data = data; } + /** + * Sets the label for this option. + * + * @param label - The label to use + */ setLabel(label) { this.data.label = labelValueDescriptionValidator.parse(label); return this; } + /** + * Sets the value for this option. + * + * @param value - The value to use + */ setValue(value) { this.data.value = labelValueDescriptionValidator.parse(value); return this; } + /** + * Sets the description for this option. + * + * @param description - The description to use + */ setDescription(description) { this.data.description = labelValueDescriptionValidator.parse(description); return this; } + /** + * Sets whether this option is selected by default. + * + * @param isDefault - Whether this option is selected by default + */ setDefault(isDefault = true) { this.data.default = defaultValidator.parse(isDefault); return this; } + /** + * Sets the emoji to display for this option. + * + * @param emoji - The emoji to use + */ setEmoji(emoji) { this.data.emoji = emojiValidator.parse(emoji); return this; } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ toJSON() { validateRequiredSelectMenuOptionParameters(this.data.label, this.data.value); return { @@ -504,7 +566,15 @@ var import_v1011 = require("discord-api-types/v10"); // src/components/Component.ts var ComponentBuilder = class { + /** + * The API data associated with this component. + */ data; + /** + * Constructs a new kind of component. + * + * @param data - The data to construct a component out of + */ constructor(data) { this.data = data; } @@ -517,33 +587,99 @@ var import_v1010 = require("discord-api-types/v10"); // src/components/button/Button.ts var import_v102 = require("discord-api-types/v10"); var ButtonBuilder = class extends ComponentBuilder { + /** + * Creates a new button from API data. + * + * @param data - The API data to create this button with + * @example + * Creating a button from an API data object: + * ```ts + * const button = new ButtonBuilder({ + * custom_id: 'a cool button', + * style: ButtonStyle.Primary, + * label: 'Click Me', + * emoji: { + * name: 'smile', + * id: '123456789012345678', + * }, + * }); + * ``` + * @example + * Creating a button using setters and API data: + * ```ts + * const button = new ButtonBuilder({ + * style: ButtonStyle.Secondary, + * label: 'Click Me', + * }) + * .setEmoji({ name: 'πŸ™‚' }) + * .setCustomId('another cool button'); + * ``` + */ constructor(data) { super({ type: import_v102.ComponentType.Button, ...data }); } + /** + * Sets the style of this button. + * + * @param style - The style to use + */ setStyle(style) { this.data.style = buttonStyleValidator.parse(style); return this; } + /** + * Sets the URL for this button. + * + * @remarks + * This method is only available to buttons using the `Link` button style. + * Only three types of URL schemes are currently supported: `https://`, `http://`, and `discord://`. + * @param url - The URL to use + */ setURL(url) { this.data.url = urlValidator.parse(url); return this; } + /** + * Sets the custom id for this button. + * + * @remarks + * This method is only applicable to buttons that are not using the `Link` button style. + * @param customId - The custom id to use + */ setCustomId(customId) { this.data.custom_id = customIdValidator.parse(customId); return this; } + /** + * Sets the emoji to display on this button. + * + * @param emoji - The emoji to use + */ setEmoji(emoji) { this.data.emoji = emojiValidator.parse(emoji); return this; } + /** + * Sets whether this button is disabled. + * + * @param disabled - Whether to disable this button + */ setDisabled(disabled = true) { this.data.disabled = disabledValidator.parse(disabled); return this; } + /** + * Sets the label for this button. + * + * @param label - The label to use + */ setLabel(label) { this.data.label = buttonLabelValidator.parse(label); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { validateRequiredButtonParameters( this.data.style, @@ -564,26 +700,54 @@ var import_v103 = require("discord-api-types/v10"); // src/components/selectMenu/BaseSelectMenu.ts var BaseSelectMenuBuilder = class extends ComponentBuilder { + /** + * Sets the placeholder for this select menu. + * + * @param placeholder - The placeholder to use + */ setPlaceholder(placeholder) { this.data.placeholder = placeholderValidator.parse(placeholder); return this; } + /** + * Sets the minimum values that must be selected in the select menu. + * + * @param minValues - The minimum values that must be selected + */ setMinValues(minValues) { this.data.min_values = minMaxValidator.parse(minValues); return this; } + /** + * Sets the maximum values that must be selected in the select menu. + * + * @param maxValues - The maximum values that must be selected + */ setMaxValues(maxValues) { this.data.max_values = minMaxValidator.parse(maxValues); return this; } + /** + * Sets the custom id for this select menu. + * + * @param customId - The custom id to use + */ setCustomId(customId) { this.data.custom_id = customIdValidator.parse(customId); return this; } + /** + * Sets whether this select menu is disabled. + * + * @param disabled - Whether this select menu is disabled + */ setDisabled(disabled = true) { this.data.disabled = disabledValidator.parse(disabled); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { customIdValidator.parse(this.data.custom_id); return { @@ -595,21 +759,57 @@ __name(BaseSelectMenuBuilder, "BaseSelectMenuBuilder"); // src/components/selectMenu/ChannelSelectMenu.ts var ChannelSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new ChannelSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new ChannelSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement) + * .setMinValues(2); + * ``` + */ constructor(data) { super({ ...data, type: import_v103.ComponentType.ChannelSelect }); } + /** + * Adds channel types to this select menu. + * + * @param types - The channel types to use + */ addChannelTypes(...types) { - types = normalizeArray(types); + const normalizedTypes = normalizeArray(types); this.data.channel_types ??= []; - this.data.channel_types.push(...channelTypesValidator.parse(types)); + this.data.channel_types.push(...channelTypesValidator.parse(normalizedTypes)); return this; } + /** + * Sets channel types for this select menu. + * + * @param types - The channel types to use + */ setChannelTypes(...types) { - types = normalizeArray(types); + const normalizedTypes = normalizeArray(types); this.data.channel_types ??= []; - this.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(types)); + this.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(normalizedTypes)); return this; } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ toJSON() { customIdValidator.parse(this.data.custom_id); return { @@ -622,6 +822,28 @@ __name(ChannelSelectMenuBuilder, "ChannelSelectMenuBuilder"); // src/components/selectMenu/MentionableSelectMenu.ts var import_v104 = require("discord-api-types/v10"); var MentionableSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new MentionableSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new MentionableSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ constructor(data) { super({ ...data, type: import_v104.ComponentType.MentionableSelect }); } @@ -631,6 +853,28 @@ __name(MentionableSelectMenuBuilder, "MentionableSelectMenuBuilder"); // src/components/selectMenu/RoleSelectMenu.ts var import_v105 = require("discord-api-types/v10"); var RoleSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new RoleSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new RoleSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ constructor(data) { super({ ...data, type: import_v105.ComponentType.RoleSelect }); } @@ -640,34 +884,113 @@ __name(RoleSelectMenuBuilder, "RoleSelectMenuBuilder"); // src/components/selectMenu/StringSelectMenu.ts var import_v106 = require("discord-api-types/v10"); var StringSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * The options within this select menu. + */ options; + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new StringSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * options: [ + * { label: 'option 1', value: '1' }, + * { label: 'option 2', value: '2' }, + * { label: 'option 3', value: '3' }, + * ], + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new StringSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1) + * .addOptions({ + * label: 'Catchy', + * value: 'catch', + * }); + * ``` + */ constructor(data) { const { options, ...initData } = data ?? {}; super({ ...initData, type: import_v106.ComponentType.StringSelect }); this.options = options?.map((option) => new StringSelectMenuOptionBuilder(option)) ?? []; } + /** + * Adds options to this select menu. + * + * @param options - The options to add + */ addOptions(...options) { - options = normalizeArray(options); - optionsLengthValidator.parse(this.options.length + options.length); + const normalizedOptions = normalizeArray(options); + optionsLengthValidator.parse(this.options.length + normalizedOptions.length); this.options.push( - ...options.map( - (option) => option instanceof StringSelectMenuOptionBuilder ? option : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)) + ...normalizedOptions.map( + (normalizedOption) => normalizedOption instanceof StringSelectMenuOptionBuilder ? normalizedOption : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)) ) ); return this; } + /** + * Sets the options for this select menu. + * + * @param options - The options to set + */ setOptions(...options) { - options = normalizeArray(options); - optionsLengthValidator.parse(options.length); - this.options.splice( - 0, - this.options.length, - ...options.map( - (option) => option instanceof StringSelectMenuOptionBuilder ? option : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)) + return this.spliceOptions(0, this.options.length, ...options); + } + /** + * Removes, replaces, or inserts options for this select menu. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice()}. + * It's useful for modifying and adjusting the order of existing options. + * @example + * Remove the first option: + * ```ts + * selectMenu.spliceOptions(0, 1); + * ``` + * @example + * Remove the first n option: + * ```ts + * const n = 4; + * selectMenu.spliceOptions(0, n); + * ``` + * @example + * Remove the last option: + * ```ts + * selectMenu.spliceOptions(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of options to remove + * @param options - The replacing option objects or builders + */ + spliceOptions(index, deleteCount, ...options) { + const normalizedOptions = normalizeArray(options); + const clone = [...this.options]; + clone.splice( + index, + deleteCount, + ...normalizedOptions.map( + (normalizedOption) => normalizedOption instanceof StringSelectMenuOptionBuilder ? normalizedOption : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)) ) ); + optionsLengthValidator.parse(clone.length); + this.options.splice(0, this.options.length, ...clone); return this; } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ toJSON() { validateRequiredSelectMenuParameters(this.options, this.data.custom_id); return { @@ -681,6 +1004,28 @@ __name(StringSelectMenuBuilder, "StringSelectMenuBuilder"); // src/components/selectMenu/UserSelectMenu.ts var import_v107 = require("discord-api-types/v10"); var UserSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new UserSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new UserSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ constructor(data) { super({ ...data, type: import_v107.ComponentType.UserSelect }); } @@ -722,47 +1067,116 @@ __name(validateRequiredParameters, "validateRequiredParameters"); // src/components/textInput/TextInput.ts var TextInputBuilder = class extends ComponentBuilder { + /** + * Creates a new text input from API data. + * + * @param data - The API data to create this text input with + * @example + * Creating a select menu option from an API data object: + * ```ts + * const textInput = new TextInputBuilder({ + * custom_id: 'a cool select menu', + * label: 'Type something', + * style: TextInputStyle.Short, + * }); + * ``` + * @example + * Creating a select menu option using setters and API data: + * ```ts + * const textInput = new TextInputBuilder({ + * label: 'Type something else', + * }) + * .setCustomId('woah') + * .setStyle(TextInputStyle.Paragraph); + * ``` + */ constructor(data) { super({ type: import_v109.ComponentType.TextInput, ...data }); } + /** + * Sets the custom id for this text input. + * + * @param customId - The custom id to use + */ setCustomId(customId) { this.data.custom_id = customIdValidator.parse(customId); return this; } + /** + * Sets the label for this text input. + * + * @param label - The label to use + */ setLabel(label) { this.data.label = labelValidator.parse(label); return this; } + /** + * Sets the style for this text input. + * + * @param style - The style to use + */ setStyle(style) { this.data.style = textInputStyleValidator.parse(style); return this; } + /** + * Sets the minimum length of text for this text input. + * + * @param minLength - The minimum length of text for this text input + */ setMinLength(minLength) { this.data.min_length = minLengthValidator.parse(minLength); return this; } + /** + * Sets the maximum length of text for this text input. + * + * @param maxLength - The maximum length of text for this text input + */ setMaxLength(maxLength) { this.data.max_length = maxLengthValidator.parse(maxLength); return this; } + /** + * Sets the placeholder for this text input. + * + * @param placeholder - The placeholder to use + */ setPlaceholder(placeholder) { this.data.placeholder = placeholderValidator2.parse(placeholder); return this; } + /** + * Sets the value for this text input. + * + * @param value - The value to use + */ setValue(value) { this.data.value = valueValidator.parse(value); return this; } + /** + * Sets whether this text input is required. + * + * @param required - Whether this text input is required + */ setRequired(required = true) { this.data.required = requiredValidator.parse(required); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { validateRequiredParameters(this.data.custom_id, this.data.style, this.data.label); return { ...this.data }; } + /** + * {@inheritDoc Equatable.equals} + */ equals(other) { if ((0, import_util.isJSONEncodable)(other)) { return (0, import_fast_deep_equal.default)(other.toJSON(), this.data); @@ -802,19 +1216,69 @@ __name(createComponentBuilder, "createComponentBuilder"); // src/components/ActionRow.ts var ActionRowBuilder = class extends ComponentBuilder { + /** + * The components within this action row. + */ components; + /** + * Creates a new action row from API data. + * + * @param data - The API data to create this action row with + * @example + * Creating an action row from an API data object: + * ```ts + * const actionRow = new ActionRowBuilder({ + * components: [ + * { + * custom_id: "custom id", + * label: "Type something", + * style: TextInputStyle.Short, + * type: ComponentType.TextInput, + * }, + * ], + * }); + * ``` + * @example + * Creating an action row using setters and API data: + * ```ts + * const actionRow = new ActionRowBuilder({ + * components: [ + * { + * custom_id: "custom id", + * label: "Click me", + * style: ButtonStyle.Primary, + * type: ComponentType.Button, + * }, + * ], + * }) + * .addComponents(button2, button3); + * ``` + */ constructor({ components, ...data } = {}) { super({ type: import_v1011.ComponentType.ActionRow, ...data }); this.components = components?.map((component) => createComponentBuilder(component)) ?? []; } + /** + * Adds components to this action row. + * + * @param components - The components to add + */ addComponents(...components) { this.components.push(...normalizeArray(components)); return this; } + /** + * Sets components for this action row. + * + * @param components - The components to set + */ setComponents(...components) { this.components.splice(0, this.components.length, ...normalizeArray(components)); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { return { ...this.data, @@ -843,20 +1307,46 @@ __name(validateRequiredParameters2, "validateRequiredParameters"); // src/interactions/modals/Modal.ts var ModalBuilder = class { + /** + * The API data associated with this modal. + */ data; + /** + * The components within this modal. + */ components = []; + /** + * Creates a new modal from API data. + * + * @param data - The API data to create this modal with + */ constructor({ components, ...data } = {}) { this.data = { ...data }; this.components = components?.map((component) => createComponentBuilder(component)) ?? []; } + /** + * Sets the title of this modal. + * + * @param title - The title to use + */ setTitle(title) { this.data.title = titleValidator.parse(title); return this; } + /** + * Sets the custom id of this modal. + * + * @param customId - The custom id to use + */ setCustomId(customId) { this.data.custom_id = customIdValidator.parse(customId); return this; } + /** + * Adds components to this modal. + * + * @param components - The components to add + */ addComponents(...components) { this.components.push( ...normalizeArray(components).map( @@ -865,10 +1355,18 @@ var ModalBuilder = class { ); return this; } + /** + * Sets components for this modal. + * + * @param components - The components to set + */ setComponents(...components) { this.components.splice(0, this.components.length, ...normalizeArray(components)); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { validateRequiredParameters2(this.data.custom_id, this.data.title, this.components); return { @@ -892,6 +1390,7 @@ __export(Assertions_exports5, { validateLocale: () => validateLocale, validateLocalizationMap: () => validateLocalizationMap, validateMaxOptionsLength: () => validateMaxOptionsLength, + validateNSFW: () => validateNSFW, validateName: () => validateName, validateRequired: () => validateRequired, validateRequiredParameters: () => validateRequiredParameters3 @@ -961,6 +1460,10 @@ function validateDefaultMemberPermissions(permissions) { return memberPermissionPredicate.parse(permissions); } __name(validateDefaultMemberPermissions, "validateDefaultMemberPermissions"); +function validateNSFW(value) { + booleanPredicate.parse(value); +} +__name(validateNSFW, "validateNSFW"); // src/interactions/slashCommands/SlashCommandBuilder.ts var import_ts_mixer6 = require("ts-mixer"); @@ -971,20 +1474,48 @@ var import_ts_mixer5 = require("ts-mixer"); // src/interactions/slashCommands/mixins/NameAndDescription.ts var SharedNameAndDescription = class { + /** + * The name of this command. + */ name; + /** + * The name localizations of this command. + */ name_localizations; + /** + * The description of this command. + */ description; + /** + * The description localizations of this command. + */ description_localizations; + /** + * Sets the name of this command. + * + * @param name - The name to use + */ setName(name) { validateName(name); Reflect.set(this, "name", name); return this; } + /** + * Sets the description of this command. + * + * @param description - The description to use + */ setDescription(description) { validateDescription(description); Reflect.set(this, "description", description); return this; } + /** + * SSets a name localization for this command. + * + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` + */ setNameLocalization(locale, localizedName) { if (!this.name_localizations) { Reflect.set(this, "name_localizations", {}); @@ -998,6 +1529,11 @@ var SharedNameAndDescription = class { this.name_localizations[parsedLocale] = localizedName; return this; } + /** + * Sets the name localizations for this command. + * + * @param localizedNames - The object of localized names to set + */ setNameLocalizations(localizedNames) { if (localizedNames === null) { Reflect.set(this, "name_localizations", null); @@ -1009,6 +1545,12 @@ var SharedNameAndDescription = class { } return this; } + /** + * Sets a description localization for this command. + * + * @param locale - The locale to set + * @param localizedDescription - The localized description for the given locale + */ setDescriptionLocalization(locale, localizedDescription) { if (!this.description_localizations) { Reflect.set(this, "description_localizations", {}); @@ -1022,6 +1564,11 @@ var SharedNameAndDescription = class { this.description_localizations[parsedLocale] = localizedDescription; return this; } + /** + * Sets the description localizations for this command. + * + * @param localizedDescriptions - The object of localized descriptions to set + */ setDescriptionLocalizations(localizedDescriptions) { if (localizedDescriptions === null) { Reflect.set(this, "description_localizations", null); @@ -1041,12 +1588,25 @@ var import_v1013 = require("discord-api-types/v10"); // src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts var ApplicationCommandOptionBase = class extends SharedNameAndDescription { + /** + * Whether this option is required. + * + * @defaultValue `false` + */ required = false; + /** + * Sets whether this option is required. + * + * @param required - Whether this option should be required + */ setRequired(required) { validateRequired(required); Reflect.set(this, "required", required); return this; } + /** + * This method runs required validators on this builder. + */ runRequiredValidations() { validateRequiredParameters3(this.name, this.description, []); validateLocalizationMap(this.name_localizations); @@ -1058,7 +1618,13 @@ __name(ApplicationCommandOptionBase, "ApplicationCommandOptionBase"); // src/interactions/slashCommands/options/attachment.ts var SlashCommandAttachmentOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1013.ApplicationCommandOptionType.Attachment; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1069,7 +1635,13 @@ __name(SlashCommandAttachmentOption, "SlashCommandAttachmentOption"); // src/interactions/slashCommands/options/boolean.ts var import_v1014 = require("discord-api-types/v10"); var SlashCommandBooleanOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1014.ApplicationCommandOptionType.Boolean; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1097,7 +1669,15 @@ var allowedChannelTypes = [ ]; var channelTypesPredicate = import_shapeshift6.s.array(import_shapeshift6.s.union(...allowedChannelTypes.map((type) => import_shapeshift6.s.literal(type)))); var ApplicationCommandOptionChannelTypesMixin = class { + /** + * The channel types of this option. + */ channel_types; + /** + * Adds channel types to this option. + * + * @param channelTypes - The channel types + */ addChannelTypes(...channelTypes) { if (this.channel_types === void 0) { Reflect.set(this, "channel_types", []); @@ -1110,7 +1690,13 @@ __name(ApplicationCommandOptionChannelTypesMixin, "ApplicationCommandOptionChann // src/interactions/slashCommands/options/channel.ts var SlashCommandChannelOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1016.ApplicationCommandOptionType.Channel; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1128,7 +1714,13 @@ var import_ts_mixer2 = require("ts-mixer"); // src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts var ApplicationCommandNumericOptionMinMaxValueMixin = class { + /** + * The maximum value of this option. + */ max_value; + /** + * The minimum value of this option. + */ min_value; }; __name(ApplicationCommandNumericOptionMinMaxValueMixin, "ApplicationCommandNumericOptionMinMaxValueMixin"); @@ -1145,9 +1737,25 @@ var choicesPredicate = import_shapeshift7.s.object({ }).array; var booleanPredicate2 = import_shapeshift7.s.boolean; var ApplicationCommandOptionWithChoicesAndAutocompleteMixin = class { + /** + * The choices of this option. + */ choices; + /** + * Whether this option utilizes autocomplete. + */ autocomplete; + /** + * The type of this option. + * + * @privateRemarks Since this is present and this is a mixin, this is needed. + */ type; + /** + * Adds multiple choices to this option. + * + * @param choices - The choices to add + */ addChoices(...choices) { if (choices.length > 0 && this.autocomplete) { throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); @@ -1167,6 +1775,11 @@ var ApplicationCommandOptionWithChoicesAndAutocompleteMixin = class { } return this; } + /** + * Sets multiple choices for this option. + * + * @param choices - The choices to set + */ setChoices(...choices) { if (choices.length > 0 && this.autocomplete) { throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); @@ -1176,6 +1789,11 @@ var ApplicationCommandOptionWithChoicesAndAutocompleteMixin = class { this.addChoices(...choices); return this; } + /** + * Whether this option uses autocomplete. + * + * @param autocomplete - Whether this option should use autocomplete + */ setAutocomplete(autocomplete) { booleanPredicate2.parse(autocomplete); if (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { @@ -1190,17 +1808,29 @@ __name(ApplicationCommandOptionWithChoicesAndAutocompleteMixin, "ApplicationComm // src/interactions/slashCommands/options/integer.ts var numberValidator = import_shapeshift8.s.number.int; var SlashCommandIntegerOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1018.ApplicationCommandOptionType.Integer; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ setMaxValue(max) { numberValidator.parse(max); Reflect.set(this, "max_value", max); return this; } + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ setMinValue(min) { numberValidator.parse(min); Reflect.set(this, "min_value", min); return this; } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { @@ -1217,7 +1847,13 @@ SlashCommandIntegerOption = __decorateClass([ // src/interactions/slashCommands/options/mentionable.ts var import_v1019 = require("discord-api-types/v10"); var SlashCommandMentionableOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1019.ApplicationCommandOptionType.Mentionable; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1231,17 +1867,29 @@ var import_v1020 = require("discord-api-types/v10"); var import_ts_mixer3 = require("ts-mixer"); var numberValidator2 = import_shapeshift9.s.number; var SlashCommandNumberOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1020.ApplicationCommandOptionType.Number; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ setMaxValue(max) { numberValidator2.parse(max); Reflect.set(this, "max_value", max); return this; } + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ setMinValue(min) { numberValidator2.parse(min); Reflect.set(this, "min_value", min); return this; } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { @@ -1258,7 +1906,13 @@ SlashCommandNumberOption = __decorateClass([ // src/interactions/slashCommands/options/role.ts var import_v1021 = require("discord-api-types/v10"); var SlashCommandRoleOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1021.ApplicationCommandOptionType.Role; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1273,19 +1927,41 @@ var import_ts_mixer4 = require("ts-mixer"); var minLengthValidator2 = import_shapeshift10.s.number.greaterThanOrEqual(0).lessThanOrEqual(6e3); var maxLengthValidator2 = import_shapeshift10.s.number.greaterThanOrEqual(1).lessThanOrEqual(6e3); var SlashCommandStringOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1022.ApplicationCommandOptionType.String; + /** + * The maximum length of this option. + */ max_length; + /** + * The minimum length of this option. + */ min_length; + /** + * Sets the maximum length of this string option. + * + * @param max - The maximum length this option can be + */ setMaxLength(max) { maxLengthValidator2.parse(max); Reflect.set(this, "max_length", max); return this; } + /** + * Sets the minimum length of this string option. + * + * @param min - The minimum length this option can be + */ setMinLength(min) { minLengthValidator2.parse(min); Reflect.set(this, "min_length", min); return this; } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { @@ -1302,7 +1978,13 @@ SlashCommandStringOption = __decorateClass([ // src/interactions/slashCommands/options/user.ts var import_v1023 = require("discord-api-types/v10"); var SlashCommandUserOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = import_v1023.ApplicationCommandOptionType.User; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1313,33 +1995,85 @@ __name(SlashCommandUserOption, "SlashCommandUserOption"); // src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts var SharedSlashCommandOptions = class { options; + /** + * Adds a boolean option. + * + * @param input - A function that returns an option builder or an already built builder + */ addBooleanOption(input) { return this._sharedAddOptionMethod(input, SlashCommandBooleanOption); } + /** + * Adds a user option. + * + * @param input - A function that returns an option builder or an already built builder + */ addUserOption(input) { return this._sharedAddOptionMethod(input, SlashCommandUserOption); } + /** + * Adds a channel option. + * + * @param input - A function that returns an option builder or an already built builder + */ addChannelOption(input) { return this._sharedAddOptionMethod(input, SlashCommandChannelOption); } + /** + * Adds a role option. + * + * @param input - A function that returns an option builder or an already built builder + */ addRoleOption(input) { return this._sharedAddOptionMethod(input, SlashCommandRoleOption); } + /** + * Adds an attachment option. + * + * @param input - A function that returns an option builder or an already built builder + */ addAttachmentOption(input) { return this._sharedAddOptionMethod(input, SlashCommandAttachmentOption); } + /** + * Adds a mentionable option. + * + * @param input - A function that returns an option builder or an already built builder + */ addMentionableOption(input) { return this._sharedAddOptionMethod(input, SlashCommandMentionableOption); } + /** + * Adds a string option. + * + * @param input - A function that returns an option builder or an already built builder + */ addStringOption(input) { return this._sharedAddOptionMethod(input, SlashCommandStringOption); } + /** + * Adds an integer option. + * + * @param input - A function that returns an option builder or an already built builder + */ addIntegerOption(input) { return this._sharedAddOptionMethod(input, SlashCommandIntegerOption); } + /** + * Adds a number option. + * + * @param input - A function that returns an option builder or an already built builder + */ addNumberOption(input) { return this._sharedAddOptionMethod(input, SlashCommandNumberOption); } + /** + * Where the actual adding magic happens. ✨ + * + * @param input - The input. What else? + * @param Instance - The instance of whatever is being added + * @internal + */ _sharedAddOptionMethod(input, Instance) { const { options } = this; validateMaxOptionsLength(options); @@ -1353,9 +2087,23 @@ __name(SharedSlashCommandOptions, "SharedSlashCommandOptions"); // src/interactions/slashCommands/SlashCommandSubcommands.ts var SlashCommandSubcommandGroupBuilder = class { + /** + * The name of this subcommand group. + */ name = void 0; + /** + * The description of this subcommand group. + */ description = void 0; + /** + * The subcommands within this subcommand group. + */ options = []; + /** + * Adds a new subcommand to this group. + * + * @param input - A function that returns a subcommand builder or an already built builder + */ addSubcommand(input) { const { options } = this; validateMaxOptionsLength(options); @@ -1364,6 +2112,13 @@ var SlashCommandSubcommandGroupBuilder = class { options.push(result); return this; } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON() { validateRequiredParameters3(this.name, this.description, this.options); return { @@ -1381,9 +2136,25 @@ SlashCommandSubcommandGroupBuilder = __decorateClass([ (0, import_ts_mixer5.mix)(SharedNameAndDescription) ], SlashCommandSubcommandGroupBuilder); var SlashCommandSubcommandBuilder = class { + /** + * The name of this subcommand. + */ name = void 0; + /** + * The description of this subcommand. + */ description = void 0; + /** + * The options within this subcommand. + */ options = []; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON() { validateRequiredParameters3(this.name, this.description, this.options); return { @@ -1403,38 +2174,102 @@ SlashCommandSubcommandBuilder = __decorateClass([ // src/interactions/slashCommands/SlashCommandBuilder.ts var SlashCommandBuilder = class { + /** + * The name of this command. + */ name = void 0; + /** + * The name localizations of this command. + */ name_localizations; + /** + * The description of this command. + */ description = void 0; + /** + * The description localizations of this command. + */ description_localizations; + /** + * The options of this command. + */ options = []; + /** + * Whether this command is enabled by default when the application is added to a guild. + * + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ default_permission = void 0; + /** + * The set of permissions represented as a bit set for the command. + */ default_member_permissions = void 0; + /** + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. + */ dm_permission = void 0; - toJSON() { - validateRequiredParameters3(this.name, this.description, this.options); - validateLocalizationMap(this.name_localizations); - validateLocalizationMap(this.description_localizations); - return { - ...this, - options: this.options.map((option) => option.toJSON()) - }; - } + /** + * Whether this command is NSFW. + */ + nsfw = void 0; + /** + * Sets whether the command is enabled by default when the application is added to a guild. + * + * @remarks + * If set to `false`, you will have to later `PUT` the permissions for this command. + * @param value - Whether or not to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link SlashCommandBuilder.setDefaultMemberPermissions} or {@link SlashCommandBuilder.setDMPermission} instead. + */ setDefaultPermission(value) { validateDefaultPermission(value); Reflect.set(this, "default_permission", value); return this; } + /** + * Sets the default permissions a member should have in order to run the command. + * + * @remarks + * You can set this to `'0'` to disable the command by default. + * @param permissions - The permissions bit field to set + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ setDefaultMemberPermissions(permissions) { const permissionValue = validateDefaultMemberPermissions(permissions); Reflect.set(this, "default_member_permissions", permissionValue); return this; } + /** + * Sets if the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ setDMPermission(enabled) { validateDMPermission(enabled); Reflect.set(this, "dm_permission", enabled); return this; } + /** + * Sets whether this command is NSFW. + * + * @param nsfw - Whether this command is NSFW + */ + setNSFW(nsfw = true) { + validateNSFW(nsfw); + Reflect.set(this, "nsfw", nsfw); + return this; + } + /** + * Adds a new subcommand group to this command. + * + * @param input - A function that returns a subcommand group builder or an already built builder + */ addSubcommandGroup(input) { const { options } = this; validateMaxOptionsLength(options); @@ -1443,6 +2278,11 @@ var SlashCommandBuilder = class { options.push(result); return this; } + /** + * Adds a new subcommand to this command. + * + * @param input - A function that returns a subcommand builder or an already built builder + */ addSubcommand(input) { const { options } = this; validateMaxOptionsLength(options); @@ -1451,6 +2291,22 @@ var SlashCommandBuilder = class { options.push(result); return this; } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON() { + validateRequiredParameters3(this.name, this.description, this.options); + validateLocalizationMap(this.name_localizations); + validateLocalizationMap(this.description_localizations); + return { + ...this, + options: this.options.map((option) => option.toJSON()) + }; + } }; __name(SlashCommandBuilder, "SlashCommandBuilder"); SlashCommandBuilder = __decorateClass([ @@ -1506,37 +2362,101 @@ __name(validateDefaultMemberPermissions2, "validateDefaultMemberPermissions"); // src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts var ContextMenuCommandBuilder = class { + /** + * The name of this command. + */ name = void 0; + /** + * The name localizations of this command. + */ name_localizations; + /** + * The type of this command. + */ type = void 0; + /** + * Whether this command is enabled by default when the application is added to a guild. + * + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ default_permission = void 0; + /** + * The set of permissions represented as a bit set for the command. + */ default_member_permissions = void 0; + /** + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. + */ dm_permission = void 0; + /** + * Sets the name of this command. + * + * @param name - The name to use + */ setName(name) { validateName2(name); Reflect.set(this, "name", name); return this; } + /** + * Sets the type of this command. + * + * @param type - The type to use + */ setType(type) { validateType(type); Reflect.set(this, "type", type); return this; } + /** + * Sets whether the command is enabled by default when the application is added to a guild. + * + * @remarks + * If set to `false`, you will have to later `PUT` the permissions for this command. + * @param value - Whether to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ setDefaultPermission(value) { validateDefaultPermission2(value); Reflect.set(this, "default_permission", value); return this; } + /** + * Sets the default permissions a member should have in order to run this command. + * + * @remarks + * You can set this to `'0'` to disable the command by default. + * @param permissions - The permissions bit field to set + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ setDefaultMemberPermissions(permissions) { const permissionValue = validateDefaultMemberPermissions2(permissions); Reflect.set(this, "default_member_permissions", permissionValue); return this; } + /** + * Sets if the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ setDMPermission(enabled) { validateDMPermission2(enabled); Reflect.set(this, "dm_permission", enabled); return this; } + /** + * Sets a name localization for this command. + * + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` + */ setNameLocalization(locale, localizedName) { if (!this.name_localizations) { Reflect.set(this, "name_localizations", {}); @@ -1550,6 +2470,11 @@ var ContextMenuCommandBuilder = class { this.name_localizations[parsedLocale] = localizedName; return this; } + /** + * Sets the name localizations for this command. + * + * @param localizedNames - The object of localized names to set + */ setNameLocalizations(localizedNames) { if (localizedNames === null) { Reflect.set(this, "name_localizations", null); @@ -1560,6 +2485,13 @@ var ContextMenuCommandBuilder = class { this.setNameLocalization(...args); return this; } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON() { validateRequiredParameters4(this.name, this.type); validateLocalizationMap(this.name_localizations); @@ -1575,8 +2507,7 @@ function embedLength(data) { __name(embedLength, "embedLength"); // src/index.ts -__reExport(src_exports, require("@discordjs/util"), module.exports); -var version = "1.4.0"; +var version = "1.6.3"; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { ActionRowBuilder, @@ -1593,7 +2524,6 @@ var version = "1.4.0"; ContextMenuCommandBuilder, EmbedAssertions, EmbedBuilder, - Faces, MentionableSelectMenuBuilder, ModalAssertions, ModalBuilder, @@ -1619,33 +2549,14 @@ var version = "1.4.0"; StringSelectMenuOptionBuilder, TextInputAssertions, TextInputBuilder, - TimestampStyles, UserSelectMenuBuilder, - blockQuote, - bold, - channelLink, - channelMention, - chatInputApplicationCommandMention, - codeBlock, createComponentBuilder, disableValidators, embedLength, enableValidators, - formatEmoji, - hideLinkEmbed, - hyperlink, - inlineCode, isValidationEnabled, - italic, - messageLink, normalizeArray, - quote, - roleMention, - spoiler, - strikethrough, - time, - underscore, - userMention, - version + version, + ...require("@discordjs/formatters") }); //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@discordjs/builders/dist/index.js.map b/node_modules/@discordjs/builders/dist/index.js.map index 0e76328..11b933a 100644 --- a/node_modules/@discordjs/builders/dist/index.js.map +++ b/node_modules/@discordjs/builders/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.ts","../src/messages/embed/Assertions.ts","../src/util/validation.ts","../src/util/normalizeArray.ts","../src/messages/embed/Embed.ts","../src/messages/formatters.ts","../src/components/Assertions.ts","../src/components/selectMenu/StringSelectMenuOption.ts","../src/components/ActionRow.ts","../src/components/Component.ts","../src/components/Components.ts","../src/components/button/Button.ts","../src/components/selectMenu/ChannelSelectMenu.ts","../src/components/selectMenu/BaseSelectMenu.ts","../src/components/selectMenu/MentionableSelectMenu.ts","../src/components/selectMenu/RoleSelectMenu.ts","../src/components/selectMenu/StringSelectMenu.ts","../src/components/selectMenu/UserSelectMenu.ts","../src/components/textInput/TextInput.ts","../src/components/textInput/Assertions.ts","../src/interactions/modals/Assertions.ts","../src/interactions/modals/Modal.ts","../src/interactions/slashCommands/Assertions.ts","../src/interactions/slashCommands/SlashCommandBuilder.ts","../src/interactions/slashCommands/SlashCommandSubcommands.ts","../src/interactions/slashCommands/mixins/NameAndDescription.ts","../src/interactions/slashCommands/options/attachment.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts","../src/interactions/slashCommands/options/boolean.ts","../src/interactions/slashCommands/options/channel.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.ts","../src/interactions/slashCommands/options/integer.ts","../src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.ts","../src/interactions/slashCommands/options/mentionable.ts","../src/interactions/slashCommands/options/number.ts","../src/interactions/slashCommands/options/role.ts","../src/interactions/slashCommands/options/string.ts","../src/interactions/slashCommands/options/user.ts","../src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts","../src/interactions/contextMenuCommands/Assertions.ts","../src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts","../src/util/componentUtil.ts"],"sourcesContent":["export * as EmbedAssertions from './messages/embed/Assertions.js';\nexport * from './messages/embed/Embed.js';\nexport * from './messages/formatters.js';\n\nexport * as ComponentAssertions from './components/Assertions.js';\nexport * from './components/ActionRow.js';\nexport * from './components/button/Button.js';\nexport * from './components/Component.js';\nexport * from './components/Components.js';\nexport * from './components/textInput/TextInput.js';\nexport * as TextInputAssertions from './components/textInput/Assertions.js';\nexport * from './interactions/modals/Modal.js';\nexport * as ModalAssertions from './interactions/modals/Assertions.js';\n\nexport * from './components/selectMenu/BaseSelectMenu.js';\nexport * from './components/selectMenu/ChannelSelectMenu.js';\nexport * from './components/selectMenu/MentionableSelectMenu.js';\nexport * from './components/selectMenu/RoleSelectMenu.js';\nexport * from './components/selectMenu/StringSelectMenu.js';\n// TODO: Remove those aliases in v2\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuBuilder} instead.\n\t */\n\tStringSelectMenuBuilder as SelectMenuBuilder,\n} from './components/selectMenu/StringSelectMenu.js';\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuOptionBuilder} instead.\n\t */\n\tStringSelectMenuOptionBuilder as SelectMenuOptionBuilder,\n} from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/UserSelectMenu.js';\n\nexport * as SlashCommandAssertions from './interactions/slashCommands/Assertions.js';\nexport * from './interactions/slashCommands/SlashCommandBuilder.js';\nexport * from './interactions/slashCommands/SlashCommandSubcommands.js';\nexport * from './interactions/slashCommands/options/boolean.js';\nexport * from './interactions/slashCommands/options/channel.js';\nexport * from './interactions/slashCommands/options/integer.js';\nexport * from './interactions/slashCommands/options/mentionable.js';\nexport * from './interactions/slashCommands/options/number.js';\nexport * from './interactions/slashCommands/options/role.js';\nexport * from './interactions/slashCommands/options/attachment.js';\nexport * from './interactions/slashCommands/options/string.js';\nexport * from './interactions/slashCommands/options/user.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionBase.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\nexport * from './interactions/slashCommands/mixins/NameAndDescription.js';\nexport * from './interactions/slashCommands/mixins/SharedSlashCommandOptions.js';\n\nexport * as ContextMenuCommandAssertions from './interactions/contextMenuCommands/Assertions.js';\nexport * from './interactions/contextMenuCommands/ContextMenuCommandBuilder.js';\n\nexport * from './util/componentUtil.js';\nexport * from './util/normalizeArray.js';\nexport * from './util/validation.js';\nexport * from '@discordjs/util';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/builders/#readme | @discordjs/builders} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const version: string = '1.4.0';\n","import { s } from '@sapphire/shapeshift';\nimport type { APIEmbedField } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const fieldNamePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(256)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldValuePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(1_024)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldInlinePredicate = s.boolean.optional;\n\nexport const embedFieldPredicate = s\n\t.object({\n\t\tname: fieldNamePredicate,\n\t\tvalue: fieldValuePredicate,\n\t\tinline: fieldInlinePredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const embedFieldsArrayPredicate = embedFieldPredicate.array.setValidationEnabled(isValidationEnabled);\n\nexport const fieldLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateFieldLength(amountAdding: number, fields?: APIEmbedField[]): void {\n\tfieldLengthPredicate.parse((fields?.length ?? 0) + amountAdding);\n}\n\nexport const authorNamePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const imageURLPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'attachment:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const urlPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const embedAuthorPredicate = s\n\t.object({\n\t\tname: authorNamePredicate,\n\t\ticonURL: imageURLPredicate,\n\t\turl: urlPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const RGBPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(255)\n\t.setValidationEnabled(isValidationEnabled);\nexport const colorPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(0xffffff)\n\t.or(s.tuple([RGBPredicate, RGBPredicate, RGBPredicate]))\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(4_096)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const footerTextPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(2_048)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const embedFooterPredicate = s\n\t.object({\n\t\ttext: footerTextPredicate,\n\t\ticonURL: imageURLPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const timestampPredicate = s.union(s.number, s.date).nullable.setValidationEnabled(isValidationEnabled);\n\nexport const titlePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n","let validate = true;\n\nexport const enableValidators = () => (validate = true);\nexport const disableValidators = () => (validate = false);\nexport const isValidationEnabled = () => validate;\n","export function normalizeArray(arr: RestOrArray): T[] {\n\tif (Array.isArray(arr[0])) return arr[0];\n\treturn arr as T[];\n}\n\nexport type RestOrArray = T[] | [T[]];\n","import type { APIEmbed, APIEmbedAuthor, APIEmbedField, APIEmbedFooter, APIEmbedImage } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport {\n\tcolorPredicate,\n\tdescriptionPredicate,\n\tembedAuthorPredicate,\n\tembedFieldsArrayPredicate,\n\tembedFooterPredicate,\n\timageURLPredicate,\n\ttimestampPredicate,\n\ttitlePredicate,\n\turlPredicate,\n\tvalidateFieldLength,\n} from './Assertions.js';\n\nexport type RGBTuple = [red: number, green: number, blue: number];\n\nexport interface IconData {\n\t/**\n\t * The URL of the icon\n\t */\n\ticonURL?: string;\n\t/**\n\t * The proxy URL of the icon\n\t */\n\tproxyIconURL?: string;\n}\n\nexport type EmbedAuthorData = IconData & Omit;\n\nexport type EmbedAuthorOptions = Omit;\n\nexport type EmbedFooterData = IconData & Omit;\n\nexport type EmbedFooterOptions = Omit;\n\nexport interface EmbedImageData extends Omit {\n\t/**\n\t * The proxy URL for the image\n\t */\n\tproxyURL?: string;\n}\n/**\n * Represents a embed in a message (image/video preview, rich embed, etc.)\n */\nexport class EmbedBuilder {\n\tpublic readonly data: APIEmbed;\n\n\tpublic constructor(data: APIEmbed = {}) {\n\t\tthis.data = { ...data };\n\t\tif (data.timestamp) this.data.timestamp = new Date(data.timestamp).toISOString();\n\t}\n\n\t/**\n\t * Appends fields to the embed\n\t *\n\t * @remarks\n\t * This method accepts either an array of fields or a variable number of field parameters.\n\t * The maximum amount of fields that can be added is 25.\n\t * @example\n\t * Using an array\n\t * ```ts\n\t * const fields: APIEmbedField[] = ...;\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(fields);\n\t * ```\n\t * @example\n\t * Using rest parameters (variadic)\n\t * ```ts\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(\n\t * \t\t{ name: 'Field 1', value: 'Value 1' },\n\t * \t\t{ name: 'Field 2', value: 'Value 2' },\n\t * \t);\n\t * ```\n\t * @param fields - The fields to add\n\t */\n\tpublic addFields(...fields: RestOrArray): this {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\tfields = normalizeArray(fields);\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(fields.length, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(fields);\n\n\t\tif (this.data.fields) this.data.fields.push(...fields);\n\t\telse this.data.fields = fields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts fields in the embed.\n\t *\n\t * @remarks\n\t * This method behaves similarly\n\t * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice}.\n\t * The maximum amount of fields that can be added is 25.\n\t *\n\t * It's useful for modifying and adjusting order of the already-existing fields of an embed.\n\t * @example\n\t * Remove the first field\n\t * ```ts\n\t * embed.spliceFields(0, 1);\n\t * ```\n\t * @example\n\t * Remove the first n fields\n\t * ```ts\n\t * const n = 4\n\t * embed.spliceFields(0, n);\n\t * ```\n\t * @example\n\t * Remove the last field\n\t * ```ts\n\t * embed.spliceFields(-1, 1);\n\t * ```\n\t * @param index - The index to start at\n\t * @param deleteCount - The number of fields to remove\n\t * @param fields - The replacing field objects\n\t */\n\tpublic spliceFields(index: number, deleteCount: number, ...fields: APIEmbedField[]): this {\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(fields.length - deleteCount, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(fields);\n\t\tif (this.data.fields) this.data.fields.splice(index, deleteCount, ...fields);\n\t\telse this.data.fields = fields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the embed's fields\n\t *\n\t * @remarks\n\t * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically,\n\t * it splices the entire array of fields, replacing them with the provided fields.\n\t *\n\t * You can set a maximum of 25 fields.\n\t * @param fields - The fields to set\n\t */\n\tpublic setFields(...fields: RestOrArray) {\n\t\tthis.spliceFields(0, this.data.fields?.length ?? 0, ...normalizeArray(fields));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the author of this embed\n\t *\n\t * @param options - The options for the author\n\t */\n\n\tpublic setAuthor(options: EmbedAuthorOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.author = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedAuthorPredicate.parse(options);\n\n\t\tthis.data.author = { name: options.name, url: options.url, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the color of this embed\n\t *\n\t * @param color - The color of the embed\n\t */\n\tpublic setColor(color: RGBTuple | number | null): this {\n\t\t// Data assertions\n\t\tcolorPredicate.parse(color);\n\n\t\tif (Array.isArray(color)) {\n\t\t\tconst [red, green, blue] = color;\n\t\t\tthis.data.color = (red << 16) + (green << 8) + blue;\n\t\t\treturn this;\n\t\t}\n\n\t\tthis.data.color = color ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this embed\n\t *\n\t * @param description - The description\n\t */\n\tpublic setDescription(description: string | null): this {\n\t\t// Data assertions\n\t\tdescriptionPredicate.parse(description);\n\n\t\tthis.data.description = description ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the footer of this embed\n\t *\n\t * @param options - The options for the footer\n\t */\n\tpublic setFooter(options: EmbedFooterOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.footer = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedFooterPredicate.parse(options);\n\n\t\tthis.data.footer = { text: options.text, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the image of this embed\n\t *\n\t * @param url - The URL of the image\n\t */\n\tpublic setImage(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.image = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the thumbnail of this embed\n\t *\n\t * @param url - The URL of the thumbnail\n\t */\n\tpublic setThumbnail(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.thumbnail = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the timestamp of this embed\n\t *\n\t * @param timestamp - The timestamp or date\n\t */\n\tpublic setTimestamp(timestamp: Date | number | null = Date.now()): this {\n\t\t// Data assertions\n\t\ttimestampPredicate.parse(timestamp);\n\n\t\tthis.data.timestamp = timestamp ? new Date(timestamp).toISOString() : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the title of this embed\n\t *\n\t * @param title - The title\n\t */\n\tpublic setTitle(title: string | null): this {\n\t\t// Data assertions\n\t\ttitlePredicate.parse(title);\n\n\t\tthis.data.title = title ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL of this embed\n\t *\n\t * @param url - The URL\n\t */\n\tpublic setURL(url: string | null): this {\n\t\t// Data assertions\n\t\turlPredicate.parse(url);\n\n\t\tthis.data.url = url ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Transforms the embed to a plain object\n\t */\n\tpublic toJSON(): APIEmbed {\n\t\treturn { ...this.data };\n\t}\n}\n","import type { URL } from 'node:url';\nimport type { Snowflake } from 'discord-api-types/globals';\n\n/**\n * Wraps the content inside a codeblock with no language\n *\n * @param content - The content to wrap\n */\nexport function codeBlock(content: C): `\\`\\`\\`\\n${C}\\n\\`\\`\\``;\n\n/**\n * Wraps the content inside a codeblock with the specified language\n *\n * @param language - The language for the codeblock\n * @param content - The content to wrap\n */\nexport function codeBlock(language: L, content: C): `\\`\\`\\`${L}\\n${C}\\n\\`\\`\\``;\nexport function codeBlock(language: string, content?: string): string {\n\treturn typeof content === 'undefined' ? `\\`\\`\\`\\n${language}\\n\\`\\`\\`` : `\\`\\`\\`${language}\\n${content}\\n\\`\\`\\``;\n}\n\n/**\n * Wraps the content inside \\`backticks\\`, which formats it as inline code\n *\n * @param content - The content to wrap\n */\nexport function inlineCode(content: C): `\\`${C}\\`` {\n\treturn `\\`${content}\\``;\n}\n\n/**\n * Formats the content into italic text\n *\n * @param content - The content to wrap\n */\nexport function italic(content: C): `_${C}_` {\n\treturn `_${content}_`;\n}\n\n/**\n * Formats the content into bold text\n *\n * @param content - The content to wrap\n */\nexport function bold(content: C): `**${C}**` {\n\treturn `**${content}**`;\n}\n\n/**\n * Formats the content into underscored text\n *\n * @param content - The content to wrap\n */\nexport function underscore(content: C): `__${C}__` {\n\treturn `__${content}__`;\n}\n\n/**\n * Formats the content into strike-through text\n *\n * @param content - The content to wrap\n */\nexport function strikethrough(content: C): `~~${C}~~` {\n\treturn `~~${content}~~`;\n}\n\n/**\n * Formats the content into a quote. This needs to be at the start of the line for Discord to format it\n *\n * @param content - The content to wrap\n */\nexport function quote(content: C): `> ${C}` {\n\treturn `> ${content}`;\n}\n\n/**\n * Formats the content into a block quote. This needs to be at the start of the line for Discord to format it\n *\n * @param content - The content to wrap\n */\nexport function blockQuote(content: C): `>>> ${C}` {\n\treturn `>>> ${content}`;\n}\n\n/**\n * Wraps the URL into `<>`, which stops it from embedding\n *\n * @param url - The URL to wrap\n */\nexport function hideLinkEmbed(url: C): `<${C}>`;\n\n/**\n * Wraps the URL into `<>`, which stops it from embedding\n *\n * @param url - The URL to wrap\n */\nexport function hideLinkEmbed(url: URL): `<${string}>`;\nexport function hideLinkEmbed(url: URL | string) {\n\treturn `<${url}>`;\n}\n\n/**\n * Formats the content and the URL into a masked URL\n *\n * @param content - The content to display\n * @param url - The URL the content links to\n */\nexport function hyperlink(content: C, url: URL): `[${C}](${string})`;\n\n/**\n * Formats the content and the URL into a masked URL\n *\n * @param content - The content to display\n * @param url - The URL the content links to\n */\nexport function hyperlink(content: C, url: U): `[${C}](${U})`;\n\n/**\n * Formats the content and the URL into a masked URL\n *\n * @param content - The content to display\n * @param url - The URL the content links to\n * @param title - The title shown when hovering on the masked link\n */\nexport function hyperlink(\n\tcontent: C,\n\turl: URL,\n\ttitle: T,\n): `[${C}](${string} \"${T}\")`;\n\n/**\n * Formats the content and the URL into a masked URL\n *\n * @param content - The content to display\n * @param url - The URL the content links to\n * @param title - The title shown when hovering on the masked link\n */\nexport function hyperlink(\n\tcontent: C,\n\turl: U,\n\ttitle: T,\n): `[${C}](${U} \"${T}\")`;\nexport function hyperlink(content: string, url: URL | string, title?: string) {\n\treturn title ? `[${content}](${url} \"${title}\")` : `[${content}](${url})`;\n}\n\n/**\n * Wraps the content inside spoiler (hidden text)\n *\n * @param content - The content to wrap\n */\nexport function spoiler(content: C): `||${C}||` {\n\treturn `||${content}||`;\n}\n\n/**\n * Formats a user ID into a user mention\n *\n * @param userId - The user ID to format\n */\nexport function userMention(userId: C): `<@${C}>` {\n\treturn `<@${userId}>`;\n}\n\n/**\n * Formats a channel ID into a channel mention\n *\n * @param channelId - The channel ID to format\n */\nexport function channelMention(channelId: C): `<#${C}>` {\n\treturn `<#${channelId}>`;\n}\n\n/**\n * Formats a role ID into a role mention\n *\n * @param roleId - The role ID to format\n */\nexport function roleMention(roleId: C): `<@&${C}>` {\n\treturn `<@&${roleId}>`;\n}\n\n/**\n * Formats an application command name, subcommand group name, subcommand name, and ID into an application command mention\n *\n * @param commandName - The application command name to format\n * @param subcommandGroupName - The subcommand group name to format\n * @param subcommandName - The subcommand name to format\n * @param commandId - The application command ID to format\n */\nexport function chatInputApplicationCommandMention<\n\tN extends string,\n\tG extends string,\n\tS extends string,\n\tI extends Snowflake,\n>(commandName: N, subcommandGroupName: G, subcommandName: S, commandId: I): ``;\n\n/**\n * Formats an application command name, subcommand name, and ID into an application command mention\n *\n * @param commandName - The application command name to format\n * @param subcommandName - The subcommand name to format\n * @param commandId - The application command ID to format\n */\nexport function chatInputApplicationCommandMention(\n\tcommandName: N,\n\tsubcommandName: S,\n\tcommandId: I,\n): ``;\n\n/**\n * Formats an application command name and ID into an application command mention\n *\n * @param commandName - The application command name to format\n * @param commandId - The application command ID to format\n */\nexport function chatInputApplicationCommandMention(\n\tcommandName: N,\n\tcommandId: I,\n): ``;\n\n/**\n * Formats an application command name, subcommand group name, subcommand name, and ID into an application command mention\n *\n * @param commandName - The application command name to format\n * @param subcommandGroupName - The subcommand group name to format\n * @param subcommandName - The subcommand name to format\n * @param commandId - The application command ID to format\n */\nexport function chatInputApplicationCommandMention<\n\tN extends string,\n\tG extends Snowflake | string,\n\tS extends Snowflake | string,\n\tI extends Snowflake,\n>(\n\tcommandName: N,\n\tsubcommandGroupName: G,\n\tsubcommandName?: S,\n\tcommandId?: I,\n): `` | `` | `` {\n\tif (typeof commandId !== 'undefined') {\n\t\treturn ``;\n\t}\n\n\tif (typeof subcommandName !== 'undefined') {\n\t\treturn ``;\n\t}\n\n\treturn ``;\n}\n\n/**\n * Formats an emoji ID into a fully qualified emoji identifier\n *\n * @param emojiId - The emoji ID to format\n */\nexport function formatEmoji(emojiId: C, animated?: false): `<:_:${C}>`;\n\n/**\n * Formats an emoji ID into a fully qualified emoji identifier\n *\n * @param emojiId - The emoji ID to format\n * @param animated - Whether the emoji is animated or not. Defaults to `false`\n */\nexport function formatEmoji(emojiId: C, animated?: true): ``;\n\n/**\n * Formats an emoji ID into a fully qualified emoji identifier\n *\n * @param emojiId - The emoji ID to format\n * @param animated - Whether the emoji is animated or not. Defaults to `false`\n */\nexport function formatEmoji(emojiId: C, animated?: boolean): `<:_:${C}>` | ``;\n\n/**\n * Formats an emoji ID into a fully qualified emoji identifier\n *\n * @param emojiId - The emoji ID to format\n * @param animated - Whether the emoji is animated or not. Defaults to `false`\n */\nexport function formatEmoji(emojiId: C, animated = false): `<:_:${C}>` | `` {\n\treturn `<${animated ? 'a' : ''}:_:${emojiId}>`;\n}\n\n/**\n * Formats a channel link for a direct message channel.\n *\n * @param channelId - The channel's id\n */\nexport function channelLink(channelId: C): `https://discord.com/channels/@me/${C}`;\n\n/**\n * Formats a channel link for a guild channel.\n *\n * @param channelId - The channel's id\n * @param guildId - The guild's id\n */\nexport function channelLink(\n\tchannelId: C,\n\tguildId: G,\n): `https://discord.com/channels/${G}/${C}`;\n\nexport function channelLink(\n\tchannelId: C,\n\tguildId?: G,\n): `https://discord.com/channels/@me/${C}` | `https://discord.com/channels/${G}/${C}` {\n\treturn `https://discord.com/channels/${guildId ?? '@me'}/${channelId}`;\n}\n\n/**\n * Formats a message link for a direct message channel.\n *\n * @param channelId - The channel's id\n * @param messageId - The message's id\n */\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n): `https://discord.com/channels/@me/${C}/${M}`;\n\n/**\n * Formats a message link for a guild channel.\n *\n * @param channelId - The channel's id\n * @param messageId - The message's id\n * @param guildId - The guild's id\n */\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n\tguildId: G,\n): `https://discord.com/channels/${G}/${C}/${M}`;\n\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n\tguildId?: G,\n): `https://discord.com/channels/@me/${C}/${M}` | `https://discord.com/channels/${G}/${C}/${M}` {\n\treturn `${typeof guildId === 'undefined' ? channelLink(channelId) : channelLink(channelId, guildId)}/${messageId}`;\n}\n\n/**\n * Formats a date into a short date-time string\n *\n * @param date - The date to format, defaults to the current time\n */\nexport function time(date?: Date): ``;\n\n/**\n * Formats a date given a format style\n *\n * @param date - The date to format\n * @param style - The style to use\n */\nexport function time(date: Date, style: S): ``;\n\n/**\n * Formats the given timestamp into a short date-time string\n *\n * @param seconds - The time to format, represents an UNIX timestamp in seconds\n */\nexport function time(seconds: C): ``;\n\n/**\n * Formats the given timestamp into a short date-time string\n *\n * @param seconds - The time to format, represents an UNIX timestamp in seconds\n * @param style - The style to use\n */\nexport function time(seconds: C, style: S): ``;\nexport function time(timeOrSeconds?: Date | number, style?: TimestampStylesString): string {\n\tif (typeof timeOrSeconds !== 'number') {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\ttimeOrSeconds = Math.floor((timeOrSeconds?.getTime() ?? Date.now()) / 1_000);\n\t}\n\n\treturn typeof style === 'string' ? `` : ``;\n}\n\n/**\n * The {@link https://discord.com/developers/docs/reference#message-formatting-timestamp-styles | message formatting timestamp styles} supported by Discord\n */\nexport const TimestampStyles = {\n\t/**\n\t * Short time format, consisting of hours and minutes, e.g. 16:20\n\t */\n\tShortTime: 't',\n\n\t/**\n\t * Long time format, consisting of hours, minutes, and seconds, e.g. 16:20:30\n\t */\n\tLongTime: 'T',\n\n\t/**\n\t * Short date format, consisting of day, month, and year, e.g. 20/04/2021\n\t */\n\tShortDate: 'd',\n\n\t/**\n\t * Long date format, consisting of day, month, and year, e.g. 20 April 2021\n\t */\n\tLongDate: 'D',\n\n\t/**\n\t * Short date-time format, consisting of short date and short time formats, e.g. 20 April 2021 16:20\n\t */\n\tShortDateTime: 'f',\n\n\t/**\n\t * Long date-time format, consisting of long date and short time formats, e.g. Tuesday, 20 April 2021 16:20\n\t */\n\tLongDateTime: 'F',\n\n\t/**\n\t * Relative time format, consisting of a relative duration format, e.g. 2 months ago\n\t */\n\tRelativeTime: 'R',\n} as const;\n\n/**\n * The possible values, see {@link TimestampStyles} for more information\n */\nexport type TimestampStylesString = typeof TimestampStyles[keyof typeof TimestampStyles];\n\n/**\n * An enum with all the available faces from Discord's native slash commands\n */\nexport enum Faces {\n\t/**\n\t * Β―\\\\_(ツ)\\\\_/Β―\n\t */\n\tShrug = 'Β―\\\\_(ツ)\\\\_/Β―',\n\n\t/**\n\t * (β•―Β°β–‘Β°οΌ‰β•―οΈ΅ ┻━┻\n\t */\n\tTableflip = '(β•―Β°β–‘Β°οΌ‰β•―οΈ΅ ┻━┻',\n\n\t/**\n\t * ┬─┬ γƒŽ( γ‚œ-γ‚œγƒŽ)\n\t */\n\tUnflip = '┬─┬ γƒŽ( γ‚œ-γ‚œγƒŽ)',\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ButtonStyle, ChannelType, type APIMessageComponentEmoji } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../util/validation.js';\nimport { StringSelectMenuOptionBuilder } from './selectMenu/StringSelectMenuOption.js';\n\nexport const customIdValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const emojiValidator = s\n\t.object({\n\t\tid: s.string,\n\t\tname: s.string,\n\t\tanimated: s.boolean,\n\t})\n\t.partial.strict.setValidationEnabled(isValidationEnabled);\n\nexport const disabledValidator = s.boolean;\n\nexport const buttonLabelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(80)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const buttonStyleValidator = s.nativeEnum(ButtonStyle);\n\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(150).setValidationEnabled(isValidationEnabled);\nexport const minMaxValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const labelValueDescriptionValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const jsonOptionValidator = s\n\t.object({\n\t\tlabel: labelValueDescriptionValidator,\n\t\tvalue: labelValueDescriptionValidator,\n\t\tdescription: labelValueDescriptionValidator.optional,\n\t\temoji: emojiValidator.optional,\n\t\tdefault: s.boolean.optional,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const optionValidator = s.instance(StringSelectMenuOptionBuilder).setValidationEnabled(isValidationEnabled);\n\nexport const optionsValidator = optionValidator.array\n\t.lengthGreaterThanOrEqual(0)\n\t.setValidationEnabled(isValidationEnabled);\nexport const optionsLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredSelectMenuParameters(options: StringSelectMenuOptionBuilder[], customId?: string) {\n\tcustomIdValidator.parse(customId);\n\toptionsValidator.parse(options);\n}\n\nexport const defaultValidator = s.boolean;\n\nexport function validateRequiredSelectMenuOptionParameters(label?: string, value?: string) {\n\tlabelValueDescriptionValidator.parse(label);\n\tlabelValueDescriptionValidator.parse(value);\n}\n\nexport const channelTypesValidator = s.nativeEnum(ChannelType).array.setValidationEnabled(isValidationEnabled);\n\nexport const urlValidator = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'discord:'],\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredButtonParameters(\n\tstyle?: ButtonStyle,\n\tlabel?: string,\n\temoji?: APIMessageComponentEmoji,\n\tcustomId?: string,\n\turl?: string,\n) {\n\tif (url && customId) {\n\t\tthrow new RangeError('URL and custom id are mutually exclusive');\n\t}\n\n\tif (!label && !emoji) {\n\t\tthrow new RangeError('Buttons must have a label and/or an emoji');\n\t}\n\n\tif (style === ButtonStyle.Link) {\n\t\tif (!url) {\n\t\t\tthrow new RangeError('Link buttons must have a url');\n\t\t}\n\t} else if (url) {\n\t\tthrow new RangeError('Non-link buttons cannot have a url');\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type { APIMessageComponentEmoji, APISelectMenuOption } from 'discord-api-types/v10';\nimport {\n\tdefaultValidator,\n\temojiValidator,\n\tlabelValueDescriptionValidator,\n\tvalidateRequiredSelectMenuOptionParameters,\n} from '../Assertions.js';\n\n/**\n * Represents an option within a string select menu component\n */\nexport class StringSelectMenuOptionBuilder implements JSONEncodable {\n\t/**\n\t * Creates a new string select menu option from API data\n\t *\n\t * @param data - The API data to create this string select menu option with\n\t * @example\n\t * Creating a string select menu option from an API data object\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tlabel: 'catchy label',\n\t * \tvalue: '1',\n\t * });\n\t * ```\n\t * @example\n\t * Creating a string select menu option using setters and API data\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tdefault: true,\n\t * \tvalue: '1',\n\t * })\n\t * \t.setLabel('woah')\n\t * ```\n\t */\n\tpublic constructor(public data: Partial = {}) {}\n\n\t/**\n\t * Sets the label of this option\n\t *\n\t * @param label - The label to show on this option\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValueDescriptionValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value of this option\n\t *\n\t * @param value - The value of this option\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = labelValueDescriptionValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this option\n\t *\n\t * @param description - The description of this option\n\t */\n\tpublic setDescription(description: string) {\n\t\tthis.data.description = labelValueDescriptionValidator.parse(description);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this option is selected by default\n\t *\n\t * @param isDefault - Whether this option is selected by default\n\t */\n\tpublic setDefault(isDefault = true) {\n\t\tthis.data.default = defaultValidator.parse(isDefault);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display on this option\n\t *\n\t * @param emoji - The emoji to display on this option\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APISelectMenuOption {\n\t\tvalidateRequiredSelectMenuOptionParameters(this.data.label, this.data.value);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APISelectMenuOption;\n\t}\n}\n","/* eslint-disable jsdoc/check-param-names */\n\nimport {\n\ttype APIActionRowComponent,\n\tComponentType,\n\ttype APIMessageActionRowComponent,\n\ttype APIModalActionRowComponent,\n\ttype APIActionRowComponentTypes,\n} from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../util/normalizeArray.js';\nimport { ComponentBuilder } from './Component.js';\nimport { createComponentBuilder } from './Components.js';\nimport type { ButtonBuilder } from './button/Button.js';\nimport type { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport type { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport type { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport type { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport type { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport type { TextInputBuilder } from './textInput/TextInput.js';\n\nexport type MessageComponentBuilder =\n\t| ActionRowBuilder\n\t| MessageActionRowComponentBuilder;\nexport type ModalComponentBuilder = ActionRowBuilder | ModalActionRowComponentBuilder;\nexport type MessageActionRowComponentBuilder =\n\t| ButtonBuilder\n\t| ChannelSelectMenuBuilder\n\t| MentionableSelectMenuBuilder\n\t| RoleSelectMenuBuilder\n\t| StringSelectMenuBuilder\n\t| UserSelectMenuBuilder;\nexport type ModalActionRowComponentBuilder = TextInputBuilder;\nexport type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalActionRowComponentBuilder;\n\n/**\n * Represents an action row component\n *\n * @typeParam T - The types of components this action row holds\n */\nexport class ActionRowBuilder extends ComponentBuilder<\n\tAPIActionRowComponent\n> {\n\t/**\n\t * The components within this action row\n\t */\n\tpublic readonly components: T[];\n\n\t/**\n\t * Creates a new action row from API data\n\t *\n\t * @param data - The API data to create this action row with\n\t * @example\n\t * Creating an action row from an API data object\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Type something\",\n\t * \t\t\tstyle: TextInputStyle.Short,\n\t * \t\t\ttype: ComponentType.TextInput,\n\t * \t\t},\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating an action row using setters and API data\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Click me\",\n\t * \t\t\tstyle: ButtonStyle.Primary,\n\t * \t\t\ttype: ComponentType.Button,\n\t * \t\t},\n\t * \t],\n\t * })\n\t * \t.addComponents(button2, button3);\n\t * ```\n\t */\n\tpublic constructor({ components, ...data }: Partial> = {}) {\n\t\tsuper({ type: ComponentType.ActionRow, ...data });\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ?? []) as T[];\n\t}\n\n\t/**\n\t * Adds components to this action row.\n\t *\n\t * @param components - The components to add to this action row.\n\t */\n\tpublic addComponents(...components: RestOrArray) {\n\t\tthis.components.push(...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the components in this action row\n\t *\n\t * @param components - The components to set this row to\n\t */\n\tpublic setComponents(...components: RestOrArray) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIActionRowComponent> {\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIActionRowComponent>;\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIActionRowComponentTypes,\n\tAPIBaseComponent,\n\tComponentType,\n} from 'discord-api-types/v10';\n\nexport type AnyAPIActionRowComponent = APIActionRowComponent | APIActionRowComponentTypes;\n\n/**\n * Represents a discord component\n *\n * @typeParam DataType - The type of internal API data that is stored within the component\n */\nexport abstract class ComponentBuilder<\n\tDataType extends Partial> = APIBaseComponent,\n> implements JSONEncodable\n{\n\t/**\n\t * The API data associated with this component\n\t */\n\tpublic readonly data: Partial;\n\n\t/**\n\t * Serializes this component to an API-compatible JSON object\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic abstract toJSON(): AnyAPIActionRowComponent;\n\n\tpublic constructor(data: Partial) {\n\t\tthis.data = data;\n\t}\n}\n","import { ComponentType, type APIMessageComponent, type APIModalComponent } from 'discord-api-types/v10';\nimport {\n\tActionRowBuilder,\n\ttype AnyComponentBuilder,\n\ttype MessageComponentBuilder,\n\ttype ModalComponentBuilder,\n} from './ActionRow.js';\nimport { ComponentBuilder } from './Component.js';\nimport { ButtonBuilder } from './button/Button.js';\nimport { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport { TextInputBuilder } from './textInput/TextInput.js';\n\nexport interface MappedComponentTypes {\n\t[ComponentType.ActionRow]: ActionRowBuilder;\n\t[ComponentType.Button]: ButtonBuilder;\n\t[ComponentType.StringSelect]: StringSelectMenuBuilder;\n\t[ComponentType.TextInput]: TextInputBuilder;\n\t[ComponentType.UserSelect]: UserSelectMenuBuilder;\n\t[ComponentType.RoleSelect]: RoleSelectMenuBuilder;\n\t[ComponentType.MentionableSelect]: MentionableSelectMenuBuilder;\n\t[ComponentType.ChannelSelect]: ChannelSelectMenuBuilder;\n}\n\n/**\n * Factory for creating components from API data\n *\n * @param data - The api data to transform to a component class\n */\nexport function createComponentBuilder(\n\t// eslint-disable-next-line @typescript-eslint/sort-type-union-intersection-members\n\tdata: (APIModalComponent | APIMessageComponent) & { type: T },\n): MappedComponentTypes[T];\nexport function createComponentBuilder(data: C): C;\nexport function createComponentBuilder(\n\tdata: APIMessageComponent | APIModalComponent | MessageComponentBuilder,\n): ComponentBuilder {\n\tif (data instanceof ComponentBuilder) {\n\t\treturn data;\n\t}\n\n\tswitch (data.type) {\n\t\tcase ComponentType.ActionRow:\n\t\t\treturn new ActionRowBuilder(data);\n\t\tcase ComponentType.Button:\n\t\t\treturn new ButtonBuilder(data);\n\t\tcase ComponentType.StringSelect:\n\t\t\treturn new StringSelectMenuBuilder(data);\n\t\tcase ComponentType.TextInput:\n\t\t\treturn new TextInputBuilder(data);\n\t\tcase ComponentType.UserSelect:\n\t\t\treturn new UserSelectMenuBuilder(data);\n\t\tcase ComponentType.RoleSelect:\n\t\t\treturn new RoleSelectMenuBuilder(data);\n\t\tcase ComponentType.MentionableSelect:\n\t\t\treturn new MentionableSelectMenuBuilder(data);\n\t\tcase ComponentType.ChannelSelect:\n\t\t\treturn new ChannelSelectMenuBuilder(data);\n\t\tdefault:\n\t\t\t// @ts-expect-error: This case can still occur if we get a newer unsupported component type\n\t\t\tthrow new Error(`Cannot properly serialize component type: ${data.type}`);\n\t}\n}\n","import {\n\tComponentType,\n\ttype APIMessageComponentEmoji,\n\ttype APIButtonComponent,\n\ttype APIButtonComponentWithURL,\n\ttype APIButtonComponentWithCustomId,\n\ttype ButtonStyle,\n} from 'discord-api-types/v10';\nimport {\n\tbuttonLabelValidator,\n\tbuttonStyleValidator,\n\tcustomIdValidator,\n\tdisabledValidator,\n\temojiValidator,\n\turlValidator,\n\tvalidateRequiredButtonParameters,\n} from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\n/**\n * Represents a button component\n */\nexport class ButtonBuilder extends ComponentBuilder {\n\t/**\n\t * Creates a new button from API data\n\t *\n\t * @param data - The API data to create this button with\n\t * @example\n\t * Creating a button from an API data object\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tcustom_id: 'a cool button',\n\t * \tstyle: ButtonStyle.Primary,\n\t * \tlabel: 'Click Me',\n\t * \temoji: {\n\t * \t\tname: 'smile',\n\t * \t\tid: '123456789012345678',\n\t * \t},\n\t * });\n\t * ```\n\t * @example\n\t * Creating a button using setters and API data\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tstyle: ButtonStyle.Secondary,\n\t * \tlabel: 'Click Me',\n\t * })\n\t * \t.setEmoji({ name: 'πŸ™‚' })\n\t * \t.setCustomId('another cool button');\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ type: ComponentType.Button, ...data });\n\t}\n\n\t/**\n\t * Sets the style of this button\n\t *\n\t * @param style - The style of the button\n\t */\n\tpublic setStyle(style: ButtonStyle) {\n\t\tthis.data.style = buttonStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL for this button\n\t *\n\t * @remarks\n\t * This method is only available to buttons using the `Link` button style.\n\t * Only three types of URL schemes are currently supported: `https://`, `http://` and `discord://`\n\t * @param url - The URL to open when this button is clicked\n\t */\n\tpublic setURL(url: string) {\n\t\t(this.data as APIButtonComponentWithURL).url = urlValidator.parse(url);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this button\n\t *\n\t * @remarks\n\t * This method is only applicable to buttons that are not using the `Link` button style.\n\t * @param customId - The custom id to use for this button\n\t */\n\tpublic setCustomId(customId: string) {\n\t\t(this.data as APIButtonComponentWithCustomId).custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display on this button\n\t *\n\t * @param emoji - The emoji to display on this button\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this button is disabled\n\t *\n\t * @param disabled - Whether to disable this button\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this button\n\t *\n\t * @param label - The label to display on this button\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = buttonLabelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIButtonComponent {\n\t\tvalidateRequiredButtonParameters(\n\t\t\tthis.data.style,\n\t\t\tthis.data.label,\n\t\t\tthis.data.emoji,\n\t\t\t(this.data as APIButtonComponentWithCustomId).custom_id,\n\t\t\t(this.data as APIButtonComponentWithURL).url,\n\t\t);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIButtonComponent;\n\t}\n}\n","import type { APIChannelSelectComponent, ChannelType } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { channelTypesValidator, customIdValidator } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\nexport class ChannelSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement)\n\t * \t.setMinValues(2)\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.ChannelSelect });\n\t}\n\n\tpublic addChannelTypes(...types: RestOrArray) {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\ttypes = normalizeArray(types);\n\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.push(...channelTypesValidator.parse(types));\n\t\treturn this;\n\t}\n\n\tpublic setChannelTypes(...types: RestOrArray) {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\ttypes = normalizeArray(types);\n\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(types));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIChannelSelectComponent {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIChannelSelectComponent;\n\t}\n}\n","import type { APISelectMenuComponent } from 'discord-api-types/v10';\nimport { customIdValidator, disabledValidator, minMaxValidator, placeholderValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\nexport class BaseSelectMenuBuilder<\n\tSelectMenuType extends APISelectMenuComponent,\n> extends ComponentBuilder {\n\t/**\n\t * Sets the placeholder for this select menu\n\t *\n\t * @param placeholder - The placeholder to use for this select menu\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum values that must be selected in the select menu\n\t *\n\t * @param minValues - The minimum values that must be selected\n\t */\n\tpublic setMinValues(minValues: number) {\n\t\tthis.data.min_values = minMaxValidator.parse(minValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum values that must be selected in the select menu\n\t *\n\t * @param maxValues - The maximum values that must be selected\n\t */\n\tpublic setMaxValues(maxValues: number) {\n\t\tthis.data.max_values = minMaxValidator.parse(maxValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this select menu\n\t *\n\t * @param customId - The custom id to use for this select menu\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this select menu is disabled\n\t *\n\t * @param disabled - Whether this select menu is disabled\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): SelectMenuType {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as SelectMenuType;\n\t}\n}\n","import type { APIMentionableSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\nexport class MentionableSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.MentionableSelect });\n\t}\n}\n","import type { APIRoleSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\nexport class RoleSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.RoleSelect });\n\t}\n}\n","import type { APIStringSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType, type APISelectMenuOption } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { jsonOptionValidator, optionsLengthValidator, validateRequiredSelectMenuParameters } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\nimport { StringSelectMenuOptionBuilder } from './StringSelectMenuOption.js';\n\n/**\n * Represents a string select menu component\n */\nexport class StringSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * The options within this select menu\n\t */\n\tpublic readonly options: StringSelectMenuOptionBuilder[];\n\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * \toptions: [\n\t * \t\t{ label: 'option 1', value: '1' },\n\t * \t\t{ label: 'option 2', value: '2' },\n\t * \t\t{ label: 'option 3', value: '3' },\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * \t.addOptions({\n\t * \t\tlabel: 'Catchy',\n\t * \t\tvalue: 'catch',\n\t * \t});\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tconst { options, ...initData } = data ?? {};\n\t\tsuper({ ...initData, type: ComponentType.StringSelect });\n\t\tthis.options = options?.map((option: APISelectMenuOption) => new StringSelectMenuOptionBuilder(option)) ?? [];\n\t}\n\n\t/**\n\t * Adds options to this select menu\n\t *\n\t * @param options - The options to add to this select menu\n\t * @returns\n\t */\n\tpublic addOptions(...options: RestOrArray) {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\toptions = normalizeArray(options);\n\t\toptionsLengthValidator.parse(this.options.length + options.length);\n\t\tthis.options.push(\n\t\t\t...options.map((option) =>\n\t\t\t\toption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? option\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the options on this select menu\n\t *\n\t * @param options - The options to set on this select menu\n\t */\n\tpublic setOptions(...options: RestOrArray) {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\toptions = normalizeArray(options);\n\t\toptionsLengthValidator.parse(options.length);\n\t\tthis.options.splice(\n\t\t\t0,\n\t\t\tthis.options.length,\n\t\t\t...options.map((option) =>\n\t\t\t\toption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? option\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIStringSelectComponent {\n\t\tvalidateRequiredSelectMenuParameters(this.options, this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t} as APIStringSelectComponent;\n\t}\n}\n","import type { APIUserSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\nexport class UserSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.UserSelect });\n\t}\n}\n","import { isJSONEncodable, type Equatable, type JSONEncodable } from '@discordjs/util';\nimport { ComponentType, type TextInputStyle, type APITextInputComponent } from 'discord-api-types/v10';\nimport isEqual from 'fast-deep-equal';\nimport { customIdValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\nimport {\n\tmaxLengthValidator,\n\tminLengthValidator,\n\tplaceholderValidator,\n\trequiredValidator,\n\tvalueValidator,\n\tvalidateRequiredParameters,\n\tlabelValidator,\n\ttextInputStyleValidator,\n} from './Assertions.js';\n\nexport class TextInputBuilder\n\textends ComponentBuilder\n\timplements Equatable>\n{\n\t/**\n\t * Creates a new text input from API data\n\t *\n\t * @param data - The API data to create this text input with\n\t * @example\n\t * Creating a select menu option from an API data object\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tlabel: 'Type something',\n\t * \tstyle: TextInputStyle.Short,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu option using setters and API data\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tlabel: 'Type something else',\n\t * })\n\t * \t.setCustomId('woah')\n\t * \t.setStyle(TextInputStyle.Paragraph);\n\t * ```\n\t */\n\tpublic constructor(data?: APITextInputComponent & { type?: ComponentType.TextInput }) {\n\t\tsuper({ type: ComponentType.TextInput, ...data });\n\t}\n\n\t/**\n\t * Sets the custom id for this text input\n\t *\n\t * @param customId - The custom id of this text input\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this text input\n\t *\n\t * @param label - The label for this text input\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the style for this text input\n\t *\n\t * @param style - The style for this text input\n\t */\n\tpublic setStyle(style: TextInputStyle) {\n\t\tthis.data.style = textInputStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of text for this text input\n\t *\n\t * @param minLength - The minimum length of text for this text input\n\t */\n\tpublic setMinLength(minLength: number) {\n\t\tthis.data.min_length = minLengthValidator.parse(minLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum length of text for this text input\n\t *\n\t * @param maxLength - The maximum length of text for this text input\n\t */\n\tpublic setMaxLength(maxLength: number) {\n\t\tthis.data.max_length = maxLengthValidator.parse(maxLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the placeholder of this text input\n\t *\n\t * @param placeholder - The placeholder of this text input\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value of this text input\n\t *\n\t * @param value - The value for this text input\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = valueValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this text input is required\n\t *\n\t * @param required - Whether this text input is required\n\t */\n\tpublic setRequired(required = true) {\n\t\tthis.data.required = requiredValidator.parse(required);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APITextInputComponent {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.style, this.data.label);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APITextInputComponent;\n\t}\n\n\t/**\n\t * {@inheritDoc Equatable.equals}\n\t */\n\tpublic equals(other: APITextInputComponent | JSONEncodable): boolean {\n\t\tif (isJSONEncodable(other)) {\n\t\t\treturn isEqual(other.toJSON(), this.data);\n\t\t}\n\n\t\treturn isEqual(other, this.data);\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { TextInputStyle } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport { customIdValidator } from '../Assertions.js';\n\nexport const textInputStyleValidator = s.nativeEnum(TextInputStyle);\nexport const minLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const maxLengthValidator = s.number.int\n\t.greaterThanOrEqual(1)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const requiredValidator = s.boolean;\nexport const valueValidator = s.string.lengthLessThanOrEqual(4_000).setValidationEnabled(isValidationEnabled);\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled);\nexport const labelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(customId?: string, style?: TextInputStyle, label?: string) {\n\tcustomIdValidator.parse(customId);\n\ttextInputStyleValidator.parse(style);\n\tlabelValidator.parse(label);\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const titleValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\nexport const componentsValidator = s\n\t.instance(ActionRowBuilder)\n\t.array.lengthGreaterThanOrEqual(1)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(\n\tcustomId?: string,\n\ttitle?: string,\n\tcomponents?: ActionRowBuilder[],\n) {\n\tcustomIdValidator.parse(customId);\n\ttitleValidator.parse(title);\n\tcomponentsValidator.parse(components);\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIModalActionRowComponent,\n\tAPIModalInteractionResponseCallbackData,\n} from 'discord-api-types/v10';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { createComponentBuilder } from '../../components/Components.js';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { titleValidator, validateRequiredParameters } from './Assertions.js';\n\nexport class ModalBuilder implements JSONEncodable {\n\tpublic readonly data: Partial;\n\n\tpublic readonly components: ActionRowBuilder[] = [];\n\n\tpublic constructor({ components, ...data }: Partial = {}) {\n\t\tthis.data = { ...data };\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ??\n\t\t\t[]) as ActionRowBuilder[];\n\t}\n\n\t/**\n\t * Sets the title of the modal\n\t *\n\t * @param title - The title of the modal\n\t */\n\tpublic setTitle(title: string) {\n\t\tthis.data.title = titleValidator.parse(title);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id of the modal\n\t *\n\t * @param customId - The custom id of this modal\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds components to this modal\n\t *\n\t * @param components - The components to add to this modal\n\t */\n\tpublic addComponents(\n\t\t...components: RestOrArray<\n\t\t\tActionRowBuilder | APIActionRowComponent\n\t\t>\n\t) {\n\t\tthis.components.push(\n\t\t\t...normalizeArray(components).map((component) =>\n\t\t\t\tcomponent instanceof ActionRowBuilder\n\t\t\t\t\t? component\n\t\t\t\t\t: new ActionRowBuilder(component),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the components in this modal\n\t *\n\t * @param components - The components to set this modal to\n\t */\n\tpublic setComponents(...components: RestOrArray>) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIModalInteractionResponseCallbackData {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.title, this.components);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIModalInteractionResponseCallbackData;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { Locale, type APIApplicationCommandOptionChoice, type LocalizationMap } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t.regex(/^[\\p{Ll}\\p{Lm}\\p{Lo}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}_-]+$/u)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nconst descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\nconst localePredicate = s.nativeEnum(Locale);\n\nexport function validateDescription(description: unknown): asserts description is string {\n\tdescriptionPredicate.parse(description);\n}\n\nconst maxArrayLengthPredicate = s.unknown.array.lengthLessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\nexport function validateLocale(locale: unknown) {\n\treturn localePredicate.parse(locale);\n}\n\nexport function validateMaxOptionsLength(options: unknown): asserts options is ToAPIApplicationCommandOptions[] {\n\tmaxArrayLengthPredicate.parse(options);\n}\n\nexport function validateRequiredParameters(\n\tname: string,\n\tdescription: string,\n\toptions: ToAPIApplicationCommandOptions[],\n) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert description conditions\n\tvalidateDescription(description);\n\n\t// Assert options conditions\n\tvalidateMaxOptionsLength(options);\n}\n\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateRequired(required: unknown): asserts required is boolean {\n\tbooleanPredicate.parse(required);\n}\n\nconst choicesLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateChoicesLength(amountAdding: number, choices?: APIApplicationCommandOptionChoice[]): void {\n\tchoicesLengthPredicate.parse((choices?.length ?? 0) + amountAdding);\n}\n\nexport function assertReturnOfBuilder<\n\tT extends ApplicationCommandOptionBase | SlashCommandSubcommandBuilder | SlashCommandSubcommandGroupBuilder,\n>(input: unknown, ExpectedInstanceOf: new () => T): asserts input is T {\n\ts.instance(ExpectedInstanceOf).parse(input);\n}\n\nexport const localizationMapPredicate = s\n\t.object(Object.fromEntries(Object.values(Locale).map((locale) => [locale, s.string.nullish])))\n\t.strict.nullish.setValidationEnabled(isValidationEnabled);\n\nexport function validateLocalizationMap(value: unknown): asserts value is LocalizationMap {\n\tlocalizationMapPredicate.parse(value);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n","import type {\n\tAPIApplicationCommandOption,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIChatInputApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport {\n\tassertReturnOfBuilder,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDefaultPermission,\n\tvalidateLocalizationMap,\n\tvalidateDMPermission,\n\tvalidateMaxOptionsLength,\n\tvalidateRequiredParameters,\n} from './Assertions.js';\nimport { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n@mix(SharedSlashCommandOptions, SharedNameAndDescription)\nexport class SlashCommandBuilder {\n\t/**\n\t * The name of this slash command\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The localized names for this command\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The description of this slash command\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The localized descriptions for this command\n\t */\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * The options of this slash command\n\t */\n\tpublic readonly options: ToAPIApplicationCommandOptions[] = [];\n\n\t/**\n\t * Whether the command is enabled by default when the app is added to a guild\n\t *\n\t * @deprecated This property is deprecated and will be removed in the future.\n\t * You should use {@link (SlashCommandBuilder:class).setDefaultMemberPermissions} or {@link (SlashCommandBuilder:class).setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Set of permissions represented as a bit set for the command\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in DMs with the application, only for globally-scoped commands.\n\t * By default, commands are visible.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Returns the final data that should be sent to Discord.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIChatInputApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\treturn {\n\t\t\t...this,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether or not to enable this command by default\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t * @deprecated Use {@link (SlashCommandBuilder:class).setDefaultMemberPermissions} or {@link (SlashCommandBuilder:class).setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run the command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in DMs with the application, only for globally-scoped commands.\n\t * By default, commands are visible.\n\t *\n\t * @param enabled - If the command should be enabled in DMs\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand group to this command\n\t *\n\t * @param input - A function that returns a subcommand group builder, or an already built builder\n\t */\n\tpublic addSubcommandGroup(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandGroupBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandGroupBuilder) => SlashCommandSubcommandGroupBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandGroupBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandGroupBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand to this command\n\t *\n\t * @param input - A function that returns a subcommand builder, or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n}\n\nexport interface SlashCommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n\nexport interface SlashCommandSubcommandsOnlyBuilder\n\textends Omit> {}\n\nexport interface SlashCommandOptionsOnlyBuilder\n\textends SharedNameAndDescription,\n\t\tSharedSlashCommandOptions,\n\t\tPick {}\n\nexport interface ToAPIApplicationCommandOptions {\n\ttoJSON(): APIApplicationCommandOption;\n}\n","import {\n\tApplicationCommandOptionType,\n\ttype APIApplicationCommandSubcommandGroupOption,\n\ttype APIApplicationCommandSubcommandOption,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { assertReturnOfBuilder, validateMaxOptionsLength, validateRequiredParameters } from './Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n/**\n * Represents a folder for subcommands\n *\n * For more information, go to https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups\n */\n@mix(SharedNameAndDescription)\nexport class SlashCommandSubcommandGroupBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand group\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand group\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The subcommands part of this subcommand group\n\t */\n\tpublic readonly options: SlashCommandSubcommandBuilder[] = [];\n\n\t/**\n\t * Adds a new subcommand to this group\n\t *\n\t * @param input - A function that returns a subcommand builder, or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t) {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): APIApplicationCommandSubcommandGroupOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.SubcommandGroup,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription {}\n\n/**\n * Represents a subcommand\n *\n * For more information, go to https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups\n */\n@mix(SharedNameAndDescription, SharedSlashCommandOptions)\nexport class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The options of this subcommand\n\t */\n\tpublic readonly options: ApplicationCommandOptionBase[] = [];\n\n\tpublic toJSON(): APIApplicationCommandSubcommandOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.Subcommand,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n","import type { LocaleString, LocalizationMap } from 'discord-api-types/v10';\nimport { validateDescription, validateLocale, validateName } from '../Assertions.js';\n\nexport class SharedNameAndDescription {\n\tpublic readonly name!: string;\n\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\tpublic readonly description!: string;\n\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * Sets the name\n\t *\n\t * @param name - The name\n\t */\n\tpublic setName(name: string): this {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description\n\t *\n\t * @param description - The description\n\t */\n\tpublic setDescription(description: string) {\n\t\t// Assert the description matches the conditions\n\t\tvalidateDescription(description);\n\n\t\tReflect.set(this, 'description', description);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a name localization\n\t *\n\t * @param locale - The locale to set a description for\n\t * @param localizedName - The localized description for the given locale\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations\n\t *\n\t * @param localizedNames - The dictionary of localized descriptions to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames)) {\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a description localization\n\t *\n\t * @param locale - The locale to set a description for\n\t * @param localizedDescription - The localized description for the given locale\n\t */\n\tpublic setDescriptionLocalization(locale: LocaleString, localizedDescription: string | null) {\n\t\tif (!this.description_localizations) {\n\t\t\tReflect.set(this, 'description_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedDescription === null) {\n\t\t\tthis.description_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateDescription(localizedDescription);\n\n\t\tthis.description_localizations![parsedLocale] = localizedDescription;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description localizations\n\t *\n\t * @param localizedDescriptions - The dictionary of localized descriptions to set\n\t */\n\tpublic setDescriptionLocalizations(localizedDescriptions: LocalizationMap | null) {\n\t\tif (localizedDescriptions === null) {\n\t\t\tReflect.set(this, 'description_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'description_localizations', {});\n\t\tfor (const args of Object.entries(localizedDescriptions)) {\n\t\t\tthis.setDescriptionLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandAttachmentOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandAttachmentOption extends ApplicationCommandOptionBase {\n\tpublic override readonly type = ApplicationCommandOptionType.Attachment as const;\n\n\tpublic toJSON(): APIApplicationCommandAttachmentOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import type { APIApplicationCommandBasicOption, ApplicationCommandOptionType } from 'discord-api-types/v10';\nimport { validateRequiredParameters, validateRequired, validateLocalizationMap } from '../Assertions.js';\nimport { SharedNameAndDescription } from './NameAndDescription.js';\n\nexport abstract class ApplicationCommandOptionBase extends SharedNameAndDescription {\n\tpublic abstract readonly type: ApplicationCommandOptionType;\n\n\tpublic readonly required: boolean = false;\n\n\t/**\n\t * Marks the option as required\n\t *\n\t * @param required - If this option should be required\n\t */\n\tpublic setRequired(required: boolean) {\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(required);\n\n\t\tReflect.set(this, 'required', required);\n\n\t\treturn this;\n\t}\n\n\tpublic abstract toJSON(): APIApplicationCommandBasicOption;\n\n\tprotected runRequiredValidations() {\n\t\tvalidateRequiredParameters(this.name, this.description, []);\n\n\t\t// Validate localizations\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(this.required);\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandBooleanOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandBooleanOption extends ApplicationCommandOptionBase {\n\tpublic readonly type = ApplicationCommandOptionType.Boolean as const;\n\n\tpublic toJSON(): APIApplicationCommandBooleanOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandChannelOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionChannelTypesMixin } from '../mixins/ApplicationCommandOptionChannelTypesMixin.js';\n\n@mix(ApplicationCommandOptionChannelTypesMixin)\nexport class SlashCommandChannelOption extends ApplicationCommandOptionBase {\n\tpublic override readonly type = ApplicationCommandOptionType.Channel as const;\n\n\tpublic toJSON(): APIApplicationCommandChannelOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandChannelOption extends ApplicationCommandOptionChannelTypesMixin {}\n","import { s } from '@sapphire/shapeshift';\nimport { ChannelType } from 'discord-api-types/v10';\n\n// Only allow valid channel types to be used. (This can't be dynamic because const enums are erased at runtime)\nconst allowedChannelTypes = [\n\tChannelType.GuildText,\n\tChannelType.GuildVoice,\n\tChannelType.GuildCategory,\n\tChannelType.GuildAnnouncement,\n\tChannelType.AnnouncementThread,\n\tChannelType.PublicThread,\n\tChannelType.PrivateThread,\n\tChannelType.GuildStageVoice,\n\tChannelType.GuildForum,\n] as const;\n\nexport type ApplicationCommandOptionAllowedChannelTypes = typeof allowedChannelTypes[number];\n\nconst channelTypesPredicate = s.array(s.union(...allowedChannelTypes.map((type) => s.literal(type))));\n\nexport class ApplicationCommandOptionChannelTypesMixin {\n\tpublic readonly channel_types?: ApplicationCommandOptionAllowedChannelTypes[];\n\n\t/**\n\t * Adds channel types to this option\n\t *\n\t * @param channelTypes - The channel types to add\n\t */\n\tpublic addChannelTypes(...channelTypes: ApplicationCommandOptionAllowedChannelTypes[]) {\n\t\tif (this.channel_types === undefined) {\n\t\t\tReflect.set(this, 'channel_types', []);\n\t\t}\n\n\t\tthis.channel_types!.push(...channelTypesPredicate.parse(channelTypes));\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandIntegerOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number.int;\n\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandIntegerOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\tpublic readonly type = ApplicationCommandOptionType.Integer as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): APIApplicationCommandIntegerOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandIntegerOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","export abstract class ApplicationCommandNumericOptionMinMaxValueMixin {\n\tpublic readonly max_value?: number;\n\n\tpublic readonly min_value?: number;\n\n\t/**\n\t * Sets the maximum number value of this option\n\t *\n\t * @param max - The maximum value this option can be\n\t */\n\tpublic abstract setMaxValue(max: number): this;\n\n\t/**\n\t * Sets the minimum number value of this option\n\t *\n\t * @param min - The minimum value this option can be\n\t */\n\tpublic abstract setMinValue(min: number): this;\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandOptionChoice } from 'discord-api-types/v10';\nimport { localizationMapPredicate, validateChoicesLength } from '../Assertions.js';\n\nconst stringPredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100);\nconst numberPredicate = s.number.greaterThan(Number.NEGATIVE_INFINITY).lessThan(Number.POSITIVE_INFINITY);\nconst choicesPredicate = s.object({\n\tname: stringPredicate,\n\tname_localizations: localizationMapPredicate,\n\tvalue: s.union(stringPredicate, numberPredicate),\n}).array;\nconst booleanPredicate = s.boolean;\n\nexport class ApplicationCommandOptionWithChoicesAndAutocompleteMixin {\n\tpublic readonly choices?: APIApplicationCommandOptionChoice[];\n\n\tpublic readonly autocomplete?: boolean;\n\n\t// Since this is present and this is a mixin, this is needed\n\tpublic readonly type!: ApplicationCommandOptionType;\n\n\t/**\n\t * Adds multiple choices for this option\n\t *\n\t * @param choices - The choices to add\n\t */\n\tpublic addChoices(...choices: APIApplicationCommandOptionChoice[]): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tif (this.choices === undefined) {\n\t\t\tReflect.set(this, 'choices', []);\n\t\t}\n\n\t\tvalidateChoicesLength(choices.length, this.choices);\n\n\t\tfor (const { name, name_localizations, value } of choices) {\n\t\t\t// Validate the value\n\t\t\tif (this.type === ApplicationCommandOptionType.String) {\n\t\t\t\tstringPredicate.parse(value);\n\t\t\t} else {\n\t\t\t\tnumberPredicate.parse(value);\n\t\t\t}\n\n\t\t\tthis.choices!.push({ name, name_localizations, value });\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tpublic setChoices[]>(...choices: Input): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tReflect.set(this, 'choices', []);\n\t\tthis.addChoices(...choices);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Marks the option as autocompletable\n\t *\n\t * @param autocomplete - If this option should be autocompletable\n\t */\n\tpublic setAutocomplete(autocomplete: boolean): this {\n\t\t// Assert that you actually passed a boolean\n\t\tbooleanPredicate.parse(autocomplete);\n\n\t\tif (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tReflect.set(this, 'autocomplete', autocomplete);\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandMentionableOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandMentionableOption extends ApplicationCommandOptionBase {\n\tpublic readonly type = ApplicationCommandOptionType.Mentionable as const;\n\n\tpublic toJSON(): APIApplicationCommandMentionableOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandNumberOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number;\n\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandNumberOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\tpublic readonly type = ApplicationCommandOptionType.Number as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): APIApplicationCommandNumberOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandNumberOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandRoleOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandRoleOption extends ApplicationCommandOptionBase {\n\tpublic override readonly type = ApplicationCommandOptionType.Role as const;\n\n\tpublic toJSON(): APIApplicationCommandRoleOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandStringOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst minLengthValidator = s.number.greaterThanOrEqual(0).lessThanOrEqual(6_000);\nconst maxLengthValidator = s.number.greaterThanOrEqual(1).lessThanOrEqual(6_000);\n\n@mix(ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandStringOption extends ApplicationCommandOptionBase {\n\tpublic readonly type = ApplicationCommandOptionType.String as const;\n\n\tpublic readonly max_length?: number;\n\n\tpublic readonly min_length?: number;\n\n\t/**\n\t * Sets the maximum length of this string option.\n\t *\n\t * @param max - The maximum length this option can be\n\t */\n\tpublic setMaxLength(max: number): this {\n\t\tmaxLengthValidator.parse(max);\n\n\t\tReflect.set(this, 'max_length', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of this string option.\n\t *\n\t * @param min - The minimum length this option can be\n\t */\n\tpublic setMinLength(min: number): this {\n\t\tminLengthValidator.parse(min);\n\n\t\tReflect.set(this, 'min_length', min);\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): APIApplicationCommandStringOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandStringOption extends ApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandUserOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandUserOption extends ApplicationCommandOptionBase {\n\tpublic readonly type = ApplicationCommandOptionType.User as const;\n\n\tpublic toJSON(): APIApplicationCommandUserOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { assertReturnOfBuilder, validateMaxOptionsLength } from '../Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from '../SlashCommandBuilder';\nimport { SlashCommandAttachmentOption } from '../options/attachment.js';\nimport { SlashCommandBooleanOption } from '../options/boolean.js';\nimport { SlashCommandChannelOption } from '../options/channel.js';\nimport { SlashCommandIntegerOption } from '../options/integer.js';\nimport { SlashCommandMentionableOption } from '../options/mentionable.js';\nimport { SlashCommandNumberOption } from '../options/number.js';\nimport { SlashCommandRoleOption } from '../options/role.js';\nimport { SlashCommandStringOption } from '../options/string.js';\nimport { SlashCommandUserOption } from '../options/user.js';\nimport type { ApplicationCommandOptionBase } from './ApplicationCommandOptionBase.js';\n\nexport class SharedSlashCommandOptions {\n\tpublic readonly options!: ToAPIApplicationCommandOptions[];\n\n\t/**\n\t * Adds a boolean option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addBooleanOption(\n\t\tinput: SlashCommandBooleanOption | ((builder: SlashCommandBooleanOption) => SlashCommandBooleanOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandBooleanOption);\n\t}\n\n\t/**\n\t * Adds a user option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addUserOption(input: SlashCommandUserOption | ((builder: SlashCommandUserOption) => SlashCommandUserOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandUserOption);\n\t}\n\n\t/**\n\t * Adds a channel option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addChannelOption(\n\t\tinput: SlashCommandChannelOption | ((builder: SlashCommandChannelOption) => SlashCommandChannelOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandChannelOption);\n\t}\n\n\t/**\n\t * Adds a role option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addRoleOption(input: SlashCommandRoleOption | ((builder: SlashCommandRoleOption) => SlashCommandRoleOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandRoleOption);\n\t}\n\n\t/**\n\t * Adds an attachment option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addAttachmentOption(\n\t\tinput: SlashCommandAttachmentOption | ((builder: SlashCommandAttachmentOption) => SlashCommandAttachmentOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandAttachmentOption);\n\t}\n\n\t/**\n\t * Adds a mentionable option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addMentionableOption(\n\t\tinput: SlashCommandMentionableOption | ((builder: SlashCommandMentionableOption) => SlashCommandMentionableOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandMentionableOption);\n\t}\n\n\t/**\n\t * Adds a string option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addStringOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandStringOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandStringOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandStringOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandStringOption);\n\t}\n\n\t/**\n\t * Adds an integer option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addIntegerOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandIntegerOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandIntegerOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandIntegerOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandIntegerOption);\n\t}\n\n\t/**\n\t * Adds a number option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addNumberOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandNumberOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandNumberOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandNumberOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandNumberOption);\n\t}\n\n\tprivate _sharedAddOptionMethod(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| T\n\t\t\t| ((builder: T) => Omit | Omit | T),\n\t\tInstance: new () => T,\n\t): ShouldOmitSubcommandFunctions extends true ? Omit : this {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new Instance()) : input;\n\n\t\tassertReturnOfBuilder(result, Instance);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandType } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ContextMenuCommandType } from './ContextMenuCommandBuilder.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t// eslint-disable-next-line prefer-named-capture-group, unicorn/no-unsafe-regex\n\t.regex(/^( *[\\p{P}\\p{L}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}]+ *)+$/u)\n\t.setValidationEnabled(isValidationEnabled);\nconst typePredicate = s\n\t.union(s.literal(ApplicationCommandType.User), s.literal(ApplicationCommandType.Message))\n\t.setValidationEnabled(isValidationEnabled);\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nexport function validateType(type: unknown): asserts type is ContextMenuCommandType {\n\ttypePredicate.parse(type);\n}\n\nexport function validateRequiredParameters(name: string, type: number) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert type is valid\n\tvalidateType(type);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n","import type {\n\tApplicationCommandType,\n\tLocaleString,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIContextMenuApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { validateLocale, validateLocalizationMap } from '../slashCommands/Assertions.js';\nimport {\n\tvalidateRequiredParameters,\n\tvalidateName,\n\tvalidateType,\n\tvalidateDefaultPermission,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDMPermission,\n} from './Assertions.js';\n\nexport class ContextMenuCommandBuilder {\n\t/**\n\t * The name of this context menu command\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The localized names for this command\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The type of this context menu command\n\t */\n\tpublic readonly type: ContextMenuCommandType = undefined!;\n\n\t/**\n\t * Whether the command is enabled by default when the app is added to a guild\n\t *\n\t * @deprecated This property is deprecated and will be removed in the future.\n\t * You should use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Set of permissions represented as a bit set for the command\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in DMs with the application, only for globally-scoped commands.\n\t * By default, commands are visible.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Sets the name\n\t *\n\t * @param name - The name\n\t */\n\tpublic setName(name: string) {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the type\n\t *\n\t * @param type - The type\n\t */\n\tpublic setType(type: ContextMenuCommandType) {\n\t\t// Assert the type is valid\n\t\tvalidateType(type);\n\n\t\tReflect.set(this, 'type', type);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether or not to enable this command by default\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run the command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in DMs with the application, only for globally-scoped commands.\n\t * By default, commands are visible.\n\t *\n\t * @param enabled - If the command should be enabled in DMs\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a name localization\n\t *\n\t * @param locale - The locale to set a description for\n\t * @param localizedName - The localized description for the given locale\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations\n\t *\n\t * @param localizedNames - The dictionary of localized descriptions to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames))\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Returns the final data that should be sent to Discord.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIContextMenuApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.type);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\n\t\treturn { ...this };\n\t}\n}\n\nexport type ContextMenuCommandType = ApplicationCommandType.Message | ApplicationCommandType.User;\n","import type { APIEmbed } from 'discord-api-types/v10';\n\nexport function embedLength(data: APIEmbed) {\n\treturn (\n\t\t(data.title?.length ?? 0) +\n\t\t(data.description?.length ?? 0) +\n\t\t(data.fields?.reduce((prev, curr) => prev + curr.name.length + curr.value.length, 0) ?? 0) +\n\t\t(data.footer?.text.length ?? 0) +\n\t\t(data.author?.name.length ?? 0)\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;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AA,EACR;AAAA,EAQO,oBAAoB,QAAsB,eAA8B;AAC9E,QAAI,CAAC,KAAK,oBAAoB;AAC7B,cAAQ,IAAI,MAAM,sBAAsB,CAAC,CAAC;AAAA,IAC3C;AAEA,UAAM,eAAe,eAAe,MAAM;AAE1C,QAAI,kBAAkB,MAAM;AAC3B,WAAK,mBAAoB,gBAAgB;AACzC,aAAO;AAAA,IACR;AAEA,IAAAH,cAAa,aAAa;AAE1B,SAAK,mBAAoB,gBAAgB;AACzC,WAAO;AAAA,EACR;AAAA,EAOO,qBAAqB,gBAAwC;AACnE,QAAI,mBAAmB,MAAM;AAC5B,cAAQ,IAAI,MAAM,sBAAsB,IAAI;AAC5C,aAAO;AAAA,IACR;AAEA,YAAQ,IAAI,MAAM,sBAAsB,CAAC,CAAC;AAE1C,eAAW,QAAQ,OAAO,QAAQ,cAAc;AAC/C,WAAK,oBAAoB,GAAI,IAAsC;AACpE,WAAO;AAAA,EACR;AAAA,EASO,SAA4D;AAClE,IAAAI,4BAA2B,KAAK,MAAM,KAAK,IAAI;AAE/C,4BAAwB,KAAK,kBAAkB;AAE/C,WAAO,EAAE,GAAG,KAAK;AAAA,EAClB;AACD;AA1Ka;;;ACfN,SAAS,YAAY,MAAgB;AAC3C,UACE,KAAK,OAAO,UAAU,MACtB,KAAK,aAAa,UAAU,MAC5B,KAAK,QAAQ,OAAO,CAAC,MAAM,SAAS,OAAO,KAAK,KAAK,SAAS,KAAK,MAAM,QAAQ,CAAC,KAAK,MACvF,KAAK,QAAQ,KAAK,UAAU,MAC5B,KAAK,QAAQ,KAAK,UAAU;AAE/B;AARgB;;;A1C0DhB,wBAAc,4BA5Dd;AAoEO,IAAM,UAAkB;","names":["Assertions_exports","Faces","Assertions_exports","import_shapeshift","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","Assertions_exports","placeholderValidator","import_shapeshift","import_v10","placeholderValidator","placeholderValidator","isEqual","Assertions_exports","validateRequiredParameters","import_shapeshift","validateRequiredParameters","validateRequiredParameters","Assertions_exports","validateRequiredParameters","import_shapeshift","import_v10","descriptionPredicate","validateRequiredParameters","import_ts_mixer","import_v10","import_ts_mixer","import_v10","validateRequiredParameters","import_v10","import_v10","import_shapeshift","import_v10","import_shapeshift","import_v10","import_ts_mixer","import_shapeshift","import_v10","booleanPredicate","import_v10","import_shapeshift","import_v10","import_ts_mixer","numberValidator","import_v10","import_shapeshift","import_v10","import_ts_mixer","minLengthValidator","maxLengthValidator","import_v10","validateRequiredParameters","validateRequiredParameters","Assertions_exports","validateDMPermission","validateDefaultMemberPermissions","validateDefaultPermission","validateName","validateRequiredParameters","import_shapeshift","import_v10","namePredicate","booleanPredicate","validateDefaultPermission","validateName","validateRequiredParameters","dmPermissionPredicate","validateDMPermission","memberPermissionPredicate","validateDefaultMemberPermissions","validateName","validateDefaultPermission","validateDefaultMemberPermissions","validateDMPermission","validateRequiredParameters"]} \ No newline at end of file +{"version":3,"sources":["../src/index.ts","../src/messages/embed/Assertions.ts","../src/util/validation.ts","../src/util/normalizeArray.ts","../src/messages/embed/Embed.ts","../src/components/Assertions.ts","../src/components/selectMenu/StringSelectMenuOption.ts","../src/components/ActionRow.ts","../src/components/Component.ts","../src/components/Components.ts","../src/components/button/Button.ts","../src/components/selectMenu/ChannelSelectMenu.ts","../src/components/selectMenu/BaseSelectMenu.ts","../src/components/selectMenu/MentionableSelectMenu.ts","../src/components/selectMenu/RoleSelectMenu.ts","../src/components/selectMenu/StringSelectMenu.ts","../src/components/selectMenu/UserSelectMenu.ts","../src/components/textInput/TextInput.ts","../src/components/textInput/Assertions.ts","../src/interactions/modals/Assertions.ts","../src/interactions/modals/Modal.ts","../src/interactions/slashCommands/Assertions.ts","../src/interactions/slashCommands/SlashCommandBuilder.ts","../src/interactions/slashCommands/SlashCommandSubcommands.ts","../src/interactions/slashCommands/mixins/NameAndDescription.ts","../src/interactions/slashCommands/options/attachment.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts","../src/interactions/slashCommands/options/boolean.ts","../src/interactions/slashCommands/options/channel.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.ts","../src/interactions/slashCommands/options/integer.ts","../src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.ts","../src/interactions/slashCommands/options/mentionable.ts","../src/interactions/slashCommands/options/number.ts","../src/interactions/slashCommands/options/role.ts","../src/interactions/slashCommands/options/string.ts","../src/interactions/slashCommands/options/user.ts","../src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts","../src/interactions/contextMenuCommands/Assertions.ts","../src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts","../src/util/componentUtil.ts"],"sourcesContent":["export * as EmbedAssertions from './messages/embed/Assertions.js';\nexport * from './messages/embed/Embed.js';\n// TODO: Consider removing this dep in the next major version\nexport * from '@discordjs/formatters';\n\nexport * as ComponentAssertions from './components/Assertions.js';\nexport * from './components/ActionRow.js';\nexport * from './components/button/Button.js';\nexport * from './components/Component.js';\nexport * from './components/Components.js';\nexport * from './components/textInput/TextInput.js';\nexport * as TextInputAssertions from './components/textInput/Assertions.js';\nexport * from './interactions/modals/Modal.js';\nexport * as ModalAssertions from './interactions/modals/Assertions.js';\n\nexport * from './components/selectMenu/BaseSelectMenu.js';\nexport * from './components/selectMenu/ChannelSelectMenu.js';\nexport * from './components/selectMenu/MentionableSelectMenu.js';\nexport * from './components/selectMenu/RoleSelectMenu.js';\nexport * from './components/selectMenu/StringSelectMenu.js';\n// TODO: Remove those aliases in v2\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuBuilder} instead.\n\t */\n\tStringSelectMenuBuilder as SelectMenuBuilder,\n} from './components/selectMenu/StringSelectMenu.js';\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuOptionBuilder} instead.\n\t */\n\tStringSelectMenuOptionBuilder as SelectMenuOptionBuilder,\n} from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/UserSelectMenu.js';\n\nexport * as SlashCommandAssertions from './interactions/slashCommands/Assertions.js';\nexport * from './interactions/slashCommands/SlashCommandBuilder.js';\nexport * from './interactions/slashCommands/SlashCommandSubcommands.js';\nexport * from './interactions/slashCommands/options/boolean.js';\nexport * from './interactions/slashCommands/options/channel.js';\nexport * from './interactions/slashCommands/options/integer.js';\nexport * from './interactions/slashCommands/options/mentionable.js';\nexport * from './interactions/slashCommands/options/number.js';\nexport * from './interactions/slashCommands/options/role.js';\nexport * from './interactions/slashCommands/options/attachment.js';\nexport * from './interactions/slashCommands/options/string.js';\nexport * from './interactions/slashCommands/options/user.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionBase.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\nexport * from './interactions/slashCommands/mixins/NameAndDescription.js';\nexport * from './interactions/slashCommands/mixins/SharedSlashCommandOptions.js';\n\nexport * as ContextMenuCommandAssertions from './interactions/contextMenuCommands/Assertions.js';\nexport * from './interactions/contextMenuCommands/ContextMenuCommandBuilder.js';\n\nexport * from './util/componentUtil.js';\nexport * from './util/normalizeArray.js';\nexport * from './util/validation.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/builders#readme | @discordjs/builders} version\n * that you are currently using.\n *\n * @privateRemarks This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild.\n */\nexport const version = '1.6.3' as string;\n","import { s } from '@sapphire/shapeshift';\nimport type { APIEmbedField } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const fieldNamePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(256)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldValuePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(1_024)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldInlinePredicate = s.boolean.optional;\n\nexport const embedFieldPredicate = s\n\t.object({\n\t\tname: fieldNamePredicate,\n\t\tvalue: fieldValuePredicate,\n\t\tinline: fieldInlinePredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const embedFieldsArrayPredicate = embedFieldPredicate.array.setValidationEnabled(isValidationEnabled);\n\nexport const fieldLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateFieldLength(amountAdding: number, fields?: APIEmbedField[]): void {\n\tfieldLengthPredicate.parse((fields?.length ?? 0) + amountAdding);\n}\n\nexport const authorNamePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const imageURLPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'attachment:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const urlPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const embedAuthorPredicate = s\n\t.object({\n\t\tname: authorNamePredicate,\n\t\ticonURL: imageURLPredicate,\n\t\turl: urlPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const RGBPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(255)\n\t.setValidationEnabled(isValidationEnabled);\nexport const colorPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(0xffffff)\n\t.or(s.tuple([RGBPredicate, RGBPredicate, RGBPredicate]))\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(4_096)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const footerTextPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(2_048)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const embedFooterPredicate = s\n\t.object({\n\t\ttext: footerTextPredicate,\n\t\ticonURL: imageURLPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const timestampPredicate = s.union(s.number, s.date).nullable.setValidationEnabled(isValidationEnabled);\n\nexport const titlePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n","let validate = true;\n\n/**\n * Enables validators.\n *\n * @returns Whether validation is occurring.\n */\nexport function enableValidators() {\n\treturn (validate = true);\n}\n\n/**\n * Disables validators.\n *\n * @returns Whether validation is occurring.\n */\nexport function disableValidators() {\n\treturn (validate = false);\n}\n\n/**\n * Checks whether validation is occurring.\n */\nexport function isValidationEnabled() {\n\treturn validate;\n}\n","/**\n * Normalizes data that is a rest parameter or an array into an array with a depth of 1.\n *\n * @typeParam T - The data that must satisfy {@link RestOrArray}.\n * @param arr - The (possibly variadic) data to normalize\n */\nexport function normalizeArray(arr: RestOrArray): T[] {\n\tif (Array.isArray(arr[0])) return arr[0];\n\treturn arr as T[];\n}\n\n/**\n * Represents data that may be an array or came from a rest parameter.\n *\n * @remarks\n * This type is used throughout builders to ensure both an array and variadic arguments\n * may be used. It is normalized with {@link normalizeArray}.\n */\nexport type RestOrArray = T[] | [T[]];\n","import type { APIEmbed, APIEmbedAuthor, APIEmbedField, APIEmbedFooter, APIEmbedImage } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport {\n\tcolorPredicate,\n\tdescriptionPredicate,\n\tembedAuthorPredicate,\n\tembedFieldsArrayPredicate,\n\tembedFooterPredicate,\n\timageURLPredicate,\n\ttimestampPredicate,\n\ttitlePredicate,\n\turlPredicate,\n\tvalidateFieldLength,\n} from './Assertions.js';\n\n/**\n * A tuple satisfying the RGB color model.\n *\n * @see {@link https://developer.mozilla.org/docs/Glossary/RGB}\n */\nexport type RGBTuple = [red: number, green: number, blue: number];\n\n/**\n * The base icon data typically used in payloads.\n */\nexport interface IconData {\n\t/**\n\t * The URL of the icon.\n\t */\n\ticonURL?: string;\n\t/**\n\t * The proxy URL of the icon.\n\t */\n\tproxyIconURL?: string;\n}\n\n/**\n * Represents the author data of an embed.\n */\nexport type EmbedAuthorData = IconData & Omit;\n\n/**\n * Represents the author options of an embed.\n */\nexport type EmbedAuthorOptions = Omit;\n\n/**\n * Represents the footer data of an embed.\n */\nexport type EmbedFooterData = IconData & Omit;\n\n/**\n * Represents the footer options of an embed.\n */\nexport type EmbedFooterOptions = Omit;\n\n/**\n * Represents the image data of an embed.\n */\nexport interface EmbedImageData extends Omit {\n\t/**\n\t * The proxy URL for the image.\n\t */\n\tproxyURL?: string;\n}\n\n/**\n * A builder that creates API-compatible JSON data for embeds.\n */\nexport class EmbedBuilder {\n\t/**\n\t * The API data associated with this embed.\n\t */\n\tpublic readonly data: APIEmbed;\n\n\t/**\n\t * Creates a new embed from API data.\n\t *\n\t * @param data - The API data to create this embed with\n\t */\n\tpublic constructor(data: APIEmbed = {}) {\n\t\tthis.data = { ...data };\n\t\tif (data.timestamp) this.data.timestamp = new Date(data.timestamp).toISOString();\n\t}\n\n\t/**\n\t * Appends fields to the embed.\n\t *\n\t * @remarks\n\t * This method accepts either an array of fields or a variable number of field parameters.\n\t * The maximum amount of fields that can be added is 25.\n\t * @example\n\t * Using an array:\n\t * ```ts\n\t * const fields: APIEmbedField[] = ...;\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(fields);\n\t * ```\n\t * @example\n\t * Using rest parameters (variadic):\n\t * ```ts\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(\n\t * \t\t{ name: 'Field 1', value: 'Value 1' },\n\t * \t\t{ name: 'Field 2', value: 'Value 2' },\n\t * \t);\n\t * ```\n\t * @param fields - The fields to add\n\t */\n\tpublic addFields(...fields: RestOrArray): this {\n\t\tconst normalizedFields = normalizeArray(fields);\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(normalizedFields.length, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(normalizedFields);\n\n\t\tif (this.data.fields) this.data.fields.push(...normalizedFields);\n\t\telse this.data.fields = normalizedFields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts fields for this embed.\n\t *\n\t * @remarks\n\t * This method behaves similarly\n\t * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice | Array.prototype.splice()}.\n\t * The maximum amount of fields that can be added is 25.\n\t *\n\t * It's useful for modifying and adjusting order of the already-existing fields of an embed.\n\t * @example\n\t * Remove the first field:\n\t * ```ts\n\t * embed.spliceFields(0, 1);\n\t * ```\n\t * @example\n\t * Remove the first n fields:\n\t * ```ts\n\t * const n = 4;\n\t * embed.spliceFields(0, n);\n\t * ```\n\t * @example\n\t * Remove the last field:\n\t * ```ts\n\t * embed.spliceFields(-1, 1);\n\t * ```\n\t * @param index - The index to start at\n\t * @param deleteCount - The number of fields to remove\n\t * @param fields - The replacing field objects\n\t */\n\tpublic spliceFields(index: number, deleteCount: number, ...fields: APIEmbedField[]): this {\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(fields.length - deleteCount, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(fields);\n\t\tif (this.data.fields) this.data.fields.splice(index, deleteCount, ...fields);\n\t\telse this.data.fields = fields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the fields for this embed.\n\t *\n\t * @remarks\n\t * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically,\n\t * it splices the entire array of fields, replacing them with the provided fields.\n\t *\n\t * You can set a maximum of 25 fields.\n\t * @param fields - The fields to set\n\t */\n\tpublic setFields(...fields: RestOrArray) {\n\t\tthis.spliceFields(0, this.data.fields?.length ?? 0, ...normalizeArray(fields));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the author of this embed.\n\t *\n\t * @param options - The options to use\n\t */\n\n\tpublic setAuthor(options: EmbedAuthorOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.author = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedAuthorPredicate.parse(options);\n\n\t\tthis.data.author = { name: options.name, url: options.url, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the color of this embed.\n\t *\n\t * @param color - The color to use\n\t */\n\tpublic setColor(color: RGBTuple | number | null): this {\n\t\t// Data assertions\n\t\tcolorPredicate.parse(color);\n\n\t\tif (Array.isArray(color)) {\n\t\t\tconst [red, green, blue] = color;\n\t\t\tthis.data.color = (red << 16) + (green << 8) + blue;\n\t\t\treturn this;\n\t\t}\n\n\t\tthis.data.color = color ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this embed.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string | null): this {\n\t\t// Data assertions\n\t\tdescriptionPredicate.parse(description);\n\n\t\tthis.data.description = description ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the footer of this embed.\n\t *\n\t * @param options - The footer to use\n\t */\n\tpublic setFooter(options: EmbedFooterOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.footer = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedFooterPredicate.parse(options);\n\n\t\tthis.data.footer = { text: options.text, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the image of this embed.\n\t *\n\t * @param url - The image URL to use\n\t */\n\tpublic setImage(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.image = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the thumbnail of this embed.\n\t *\n\t * @param url - The thumbnail URL to use\n\t */\n\tpublic setThumbnail(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.thumbnail = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the timestamp of this embed.\n\t *\n\t * @param timestamp - The timestamp or date to use\n\t */\n\tpublic setTimestamp(timestamp: Date | number | null = Date.now()): this {\n\t\t// Data assertions\n\t\ttimestampPredicate.parse(timestamp);\n\n\t\tthis.data.timestamp = timestamp ? new Date(timestamp).toISOString() : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the title for this embed.\n\t *\n\t * @param title - The title to use\n\t */\n\tpublic setTitle(title: string | null): this {\n\t\t// Data assertions\n\t\ttitlePredicate.parse(title);\n\n\t\tthis.data.title = title ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL of this embed.\n\t *\n\t * @param url - The URL to use\n\t */\n\tpublic setURL(url: string | null): this {\n\t\t// Data assertions\n\t\turlPredicate.parse(url);\n\n\t\tthis.data.url = url ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIEmbed {\n\t\treturn { ...this.data };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ButtonStyle, ChannelType, type APIMessageComponentEmoji } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../util/validation.js';\nimport { StringSelectMenuOptionBuilder } from './selectMenu/StringSelectMenuOption.js';\n\nexport const customIdValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const emojiValidator = s\n\t.object({\n\t\tid: s.string,\n\t\tname: s.string,\n\t\tanimated: s.boolean,\n\t})\n\t.partial.strict.setValidationEnabled(isValidationEnabled);\n\nexport const disabledValidator = s.boolean;\n\nexport const buttonLabelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(80)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const buttonStyleValidator = s.nativeEnum(ButtonStyle);\n\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(150).setValidationEnabled(isValidationEnabled);\nexport const minMaxValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const labelValueDescriptionValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const jsonOptionValidator = s\n\t.object({\n\t\tlabel: labelValueDescriptionValidator,\n\t\tvalue: labelValueDescriptionValidator,\n\t\tdescription: labelValueDescriptionValidator.optional,\n\t\temoji: emojiValidator.optional,\n\t\tdefault: s.boolean.optional,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const optionValidator = s.instance(StringSelectMenuOptionBuilder).setValidationEnabled(isValidationEnabled);\n\nexport const optionsValidator = optionValidator.array\n\t.lengthGreaterThanOrEqual(0)\n\t.setValidationEnabled(isValidationEnabled);\nexport const optionsLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredSelectMenuParameters(options: StringSelectMenuOptionBuilder[], customId?: string) {\n\tcustomIdValidator.parse(customId);\n\toptionsValidator.parse(options);\n}\n\nexport const defaultValidator = s.boolean;\n\nexport function validateRequiredSelectMenuOptionParameters(label?: string, value?: string) {\n\tlabelValueDescriptionValidator.parse(label);\n\tlabelValueDescriptionValidator.parse(value);\n}\n\nexport const channelTypesValidator = s.nativeEnum(ChannelType).array.setValidationEnabled(isValidationEnabled);\n\nexport const urlValidator = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'discord:'],\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredButtonParameters(\n\tstyle?: ButtonStyle,\n\tlabel?: string,\n\temoji?: APIMessageComponentEmoji,\n\tcustomId?: string,\n\turl?: string,\n) {\n\tif (url && customId) {\n\t\tthrow new RangeError('URL and custom id are mutually exclusive');\n\t}\n\n\tif (!label && !emoji) {\n\t\tthrow new RangeError('Buttons must have a label and/or an emoji');\n\t}\n\n\tif (style === ButtonStyle.Link) {\n\t\tif (!url) {\n\t\t\tthrow new RangeError('Link buttons must have a url');\n\t\t}\n\t} else if (url) {\n\t\tthrow new RangeError('Non-link buttons cannot have a url');\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type { APIMessageComponentEmoji, APISelectMenuOption } from 'discord-api-types/v10';\nimport {\n\tdefaultValidator,\n\temojiValidator,\n\tlabelValueDescriptionValidator,\n\tvalidateRequiredSelectMenuOptionParameters,\n} from '../Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for string select menu options.\n */\nexport class StringSelectMenuOptionBuilder implements JSONEncodable {\n\t/**\n\t * Creates a new string select menu option from API data.\n\t *\n\t * @param data - The API data to create this string select menu option with\n\t * @example\n\t * Creating a string select menu option from an API data object:\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tlabel: 'catchy label',\n\t * \tvalue: '1',\n\t * });\n\t * ```\n\t * @example\n\t * Creating a string select menu option using setters and API data:\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tdefault: true,\n\t * \tvalue: '1',\n\t * })\n\t * \t.setLabel('woah');\n\t * ```\n\t */\n\tpublic constructor(public data: Partial = {}) {}\n\n\t/**\n\t * Sets the label for this option.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValueDescriptionValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value for this option.\n\t *\n\t * @param value - The value to use\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = labelValueDescriptionValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description for this option.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string) {\n\t\tthis.data.description = labelValueDescriptionValidator.parse(description);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this option is selected by default.\n\t *\n\t * @param isDefault - Whether this option is selected by default\n\t */\n\tpublic setDefault(isDefault = true) {\n\t\tthis.data.default = defaultValidator.parse(isDefault);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display for this option.\n\t *\n\t * @param emoji - The emoji to use\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic toJSON(): APISelectMenuOption {\n\t\tvalidateRequiredSelectMenuOptionParameters(this.data.label, this.data.value);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APISelectMenuOption;\n\t}\n}\n","/* eslint-disable jsdoc/check-param-names */\n\nimport {\n\ttype APIActionRowComponent,\n\tComponentType,\n\ttype APIMessageActionRowComponent,\n\ttype APIModalActionRowComponent,\n\ttype APIActionRowComponentTypes,\n} from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../util/normalizeArray.js';\nimport { ComponentBuilder } from './Component.js';\nimport { createComponentBuilder } from './Components.js';\nimport type { ButtonBuilder } from './button/Button.js';\nimport type { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport type { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport type { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport type { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport type { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport type { TextInputBuilder } from './textInput/TextInput.js';\n\n/**\n * The builders that may be used for messages.\n */\nexport type MessageComponentBuilder =\n\t| ActionRowBuilder\n\t| MessageActionRowComponentBuilder;\n\n/**\n * The builders that may be used for modals.\n */\nexport type ModalComponentBuilder = ActionRowBuilder | ModalActionRowComponentBuilder;\n\n/**\n * The builders that may be used within an action row for messages.\n */\nexport type MessageActionRowComponentBuilder =\n\t| ButtonBuilder\n\t| ChannelSelectMenuBuilder\n\t| MentionableSelectMenuBuilder\n\t| RoleSelectMenuBuilder\n\t| StringSelectMenuBuilder\n\t| UserSelectMenuBuilder;\n\n/**\n * The builders that may be used within an action row for modals.\n */\nexport type ModalActionRowComponentBuilder = TextInputBuilder;\n\n/**\n * Any builder.\n */\nexport type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalActionRowComponentBuilder;\n\n/**\n * A builder that creates API-compatible JSON data for action rows.\n *\n * @typeParam T - The types of components this action row holds\n */\nexport class ActionRowBuilder extends ComponentBuilder<\n\tAPIActionRowComponent\n> {\n\t/**\n\t * The components within this action row.\n\t */\n\tpublic readonly components: T[];\n\n\t/**\n\t * Creates a new action row from API data.\n\t *\n\t * @param data - The API data to create this action row with\n\t * @example\n\t * Creating an action row from an API data object:\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Type something\",\n\t * \t\t\tstyle: TextInputStyle.Short,\n\t * \t\t\ttype: ComponentType.TextInput,\n\t * \t\t},\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating an action row using setters and API data:\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Click me\",\n\t * \t\t\tstyle: ButtonStyle.Primary,\n\t * \t\t\ttype: ComponentType.Button,\n\t * \t\t},\n\t * \t],\n\t * })\n\t * \t.addComponents(button2, button3);\n\t * ```\n\t */\n\tpublic constructor({ components, ...data }: Partial> = {}) {\n\t\tsuper({ type: ComponentType.ActionRow, ...data });\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ?? []) as T[];\n\t}\n\n\t/**\n\t * Adds components to this action row.\n\t *\n\t * @param components - The components to add\n\t */\n\tpublic addComponents(...components: RestOrArray) {\n\t\tthis.components.push(...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets components for this action row.\n\t *\n\t * @param components - The components to set\n\t */\n\tpublic setComponents(...components: RestOrArray) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIActionRowComponent> {\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIActionRowComponent>;\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIActionRowComponentTypes,\n\tAPIBaseComponent,\n\tComponentType,\n} from 'discord-api-types/v10';\n\n/**\n * Any action row component data represented as an object.\n */\nexport type AnyAPIActionRowComponent = APIActionRowComponent | APIActionRowComponentTypes;\n\n/**\n * The base component builder that contains common symbols for all sorts of components.\n *\n * @typeParam DataType - The type of internal API data that is stored within the component\n */\nexport abstract class ComponentBuilder<\n\tDataType extends Partial> = APIBaseComponent,\n> implements JSONEncodable\n{\n\t/**\n\t * The API data associated with this component.\n\t */\n\tpublic readonly data: Partial;\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic abstract toJSON(): AnyAPIActionRowComponent;\n\n\t/**\n\t * Constructs a new kind of component.\n\t *\n\t * @param data - The data to construct a component out of\n\t */\n\tpublic constructor(data: Partial) {\n\t\tthis.data = data;\n\t}\n}\n","import { ComponentType, type APIMessageComponent, type APIModalComponent } from 'discord-api-types/v10';\nimport {\n\tActionRowBuilder,\n\ttype AnyComponentBuilder,\n\ttype MessageComponentBuilder,\n\ttype ModalComponentBuilder,\n} from './ActionRow.js';\nimport { ComponentBuilder } from './Component.js';\nimport { ButtonBuilder } from './button/Button.js';\nimport { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport { TextInputBuilder } from './textInput/TextInput.js';\n\n/**\n * Components here are mapped to their respective builder.\n */\nexport interface MappedComponentTypes {\n\t/**\n\t * The action row component type is associated with an {@link ActionRowBuilder}.\n\t */\n\t[ComponentType.ActionRow]: ActionRowBuilder;\n\t/**\n\t * The button component type is associated with an {@link ButtonBuilder}.\n\t */\n\t[ComponentType.Button]: ButtonBuilder;\n\t/**\n\t * The string select component type is associated with an {@link StringSelectMenuBuilder}.\n\t */\n\t[ComponentType.StringSelect]: StringSelectMenuBuilder;\n\t/**\n\t * The text inpiut component type is associated with an {@link TextInputBuilder}.\n\t */\n\t[ComponentType.TextInput]: TextInputBuilder;\n\t/**\n\t * The user select component type is associated with an {@link UserSelectMenuBuilder}.\n\t */\n\t[ComponentType.UserSelect]: UserSelectMenuBuilder;\n\t/**\n\t * The role select component type is associated with an {@link RoleSelectMenuBuilder}.\n\t */\n\t[ComponentType.RoleSelect]: RoleSelectMenuBuilder;\n\t/**\n\t * The mentionable select component type is associated with an {@link MentionableSelectMenuBuilder}.\n\t */\n\t[ComponentType.MentionableSelect]: MentionableSelectMenuBuilder;\n\t/**\n\t * The channel select component type is associated with an {@link ChannelSelectMenuBuilder}.\n\t */\n\t[ComponentType.ChannelSelect]: ChannelSelectMenuBuilder;\n}\n\n/**\n * Factory for creating components from API data.\n *\n * @typeParam T - The type of component to use\n * @param data - The API data to transform to a component class\n */\nexport function createComponentBuilder(\n\t// eslint-disable-next-line @typescript-eslint/sort-type-union-intersection-members\n\tdata: (APIModalComponent | APIMessageComponent) & { type: T },\n): MappedComponentTypes[T];\n\n/**\n * Factory for creating components from API data.\n *\n * @typeParam C - The type of component to use\n * @param data - The API data to transform to a component class\n */\nexport function createComponentBuilder(data: C): C;\n\nexport function createComponentBuilder(\n\tdata: APIMessageComponent | APIModalComponent | MessageComponentBuilder,\n): ComponentBuilder {\n\tif (data instanceof ComponentBuilder) {\n\t\treturn data;\n\t}\n\n\tswitch (data.type) {\n\t\tcase ComponentType.ActionRow:\n\t\t\treturn new ActionRowBuilder(data);\n\t\tcase ComponentType.Button:\n\t\t\treturn new ButtonBuilder(data);\n\t\tcase ComponentType.StringSelect:\n\t\t\treturn new StringSelectMenuBuilder(data);\n\t\tcase ComponentType.TextInput:\n\t\t\treturn new TextInputBuilder(data);\n\t\tcase ComponentType.UserSelect:\n\t\t\treturn new UserSelectMenuBuilder(data);\n\t\tcase ComponentType.RoleSelect:\n\t\t\treturn new RoleSelectMenuBuilder(data);\n\t\tcase ComponentType.MentionableSelect:\n\t\t\treturn new MentionableSelectMenuBuilder(data);\n\t\tcase ComponentType.ChannelSelect:\n\t\t\treturn new ChannelSelectMenuBuilder(data);\n\t\tdefault:\n\t\t\t// @ts-expect-error This case can still occur if we get a newer unsupported component type\n\t\t\tthrow new Error(`Cannot properly serialize component type: ${data.type}`);\n\t}\n}\n","import {\n\tComponentType,\n\ttype APIMessageComponentEmoji,\n\ttype APIButtonComponent,\n\ttype APIButtonComponentWithURL,\n\ttype APIButtonComponentWithCustomId,\n\ttype ButtonStyle,\n} from 'discord-api-types/v10';\nimport {\n\tbuttonLabelValidator,\n\tbuttonStyleValidator,\n\tcustomIdValidator,\n\tdisabledValidator,\n\temojiValidator,\n\turlValidator,\n\tvalidateRequiredButtonParameters,\n} from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\n/**\n * A builder that creates API-compatible JSON data for buttons.\n */\nexport class ButtonBuilder extends ComponentBuilder {\n\t/**\n\t * Creates a new button from API data.\n\t *\n\t * @param data - The API data to create this button with\n\t * @example\n\t * Creating a button from an API data object:\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tcustom_id: 'a cool button',\n\t * \tstyle: ButtonStyle.Primary,\n\t * \tlabel: 'Click Me',\n\t * \temoji: {\n\t * \t\tname: 'smile',\n\t * \t\tid: '123456789012345678',\n\t * \t},\n\t * });\n\t * ```\n\t * @example\n\t * Creating a button using setters and API data:\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tstyle: ButtonStyle.Secondary,\n\t * \tlabel: 'Click Me',\n\t * })\n\t * \t.setEmoji({ name: 'πŸ™‚' })\n\t * \t.setCustomId('another cool button');\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ type: ComponentType.Button, ...data });\n\t}\n\n\t/**\n\t * Sets the style of this button.\n\t *\n\t * @param style - The style to use\n\t */\n\tpublic setStyle(style: ButtonStyle) {\n\t\tthis.data.style = buttonStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL for this button.\n\t *\n\t * @remarks\n\t * This method is only available to buttons using the `Link` button style.\n\t * Only three types of URL schemes are currently supported: `https://`, `http://`, and `discord://`.\n\t * @param url - The URL to use\n\t */\n\tpublic setURL(url: string) {\n\t\t(this.data as APIButtonComponentWithURL).url = urlValidator.parse(url);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this button.\n\t *\n\t * @remarks\n\t * This method is only applicable to buttons that are not using the `Link` button style.\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\t(this.data as APIButtonComponentWithCustomId).custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display on this button.\n\t *\n\t * @param emoji - The emoji to use\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this button is disabled.\n\t *\n\t * @param disabled - Whether to disable this button\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this button.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = buttonLabelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIButtonComponent {\n\t\tvalidateRequiredButtonParameters(\n\t\t\tthis.data.style,\n\t\t\tthis.data.label,\n\t\t\tthis.data.emoji,\n\t\t\t(this.data as APIButtonComponentWithCustomId).custom_id,\n\t\t\t(this.data as APIButtonComponentWithURL).url,\n\t\t);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIButtonComponent;\n\t}\n}\n","import type { APIChannelSelectComponent, ChannelType } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { channelTypesValidator, customIdValidator } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for channel select menus.\n */\nexport class ChannelSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement)\n\t * \t.setMinValues(2);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.ChannelSelect });\n\t}\n\n\t/**\n\t * Adds channel types to this select menu.\n\t *\n\t * @param types - The channel types to use\n\t */\n\tpublic addChannelTypes(...types: RestOrArray) {\n\t\tconst normalizedTypes = normalizeArray(types);\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.push(...channelTypesValidator.parse(normalizedTypes));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets channel types for this select menu.\n\t *\n\t * @param types - The channel types to use\n\t */\n\tpublic setChannelTypes(...types: RestOrArray) {\n\t\tconst normalizedTypes = normalizeArray(types);\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(normalizedTypes));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIChannelSelectComponent {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIChannelSelectComponent;\n\t}\n}\n","import type { APISelectMenuComponent } from 'discord-api-types/v10';\nimport { customIdValidator, disabledValidator, minMaxValidator, placeholderValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\n/**\n * The base select menu builder that contains common symbols for select menu builders.\n *\n * @typeParam SelectMenuType - The type of select menu this would be instantiated for.\n */\nexport abstract class BaseSelectMenuBuilder<\n\tSelectMenuType extends APISelectMenuComponent,\n> extends ComponentBuilder {\n\t/**\n\t * Sets the placeholder for this select menu.\n\t *\n\t * @param placeholder - The placeholder to use\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum values that must be selected in the select menu.\n\t *\n\t * @param minValues - The minimum values that must be selected\n\t */\n\tpublic setMinValues(minValues: number) {\n\t\tthis.data.min_values = minMaxValidator.parse(minValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum values that must be selected in the select menu.\n\t *\n\t * @param maxValues - The maximum values that must be selected\n\t */\n\tpublic setMaxValues(maxValues: number) {\n\t\tthis.data.max_values = minMaxValidator.parse(maxValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this select menu.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this select menu is disabled.\n\t *\n\t * @param disabled - Whether this select menu is disabled\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): SelectMenuType {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as SelectMenuType;\n\t}\n}\n","import type { APIMentionableSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for mentionable select menus.\n */\nexport class MentionableSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.MentionableSelect });\n\t}\n}\n","import type { APIRoleSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for role select menus.\n */\nexport class RoleSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.RoleSelect });\n\t}\n}\n","import { ComponentType } from 'discord-api-types/v10';\nimport type { APIStringSelectComponent, APISelectMenuOption } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { jsonOptionValidator, optionsLengthValidator, validateRequiredSelectMenuParameters } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\nimport { StringSelectMenuOptionBuilder } from './StringSelectMenuOption.js';\n\n/**\n * A builder that creates API-compatible JSON data for string select menus.\n */\nexport class StringSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * The options within this select menu.\n\t */\n\tpublic readonly options: StringSelectMenuOptionBuilder[];\n\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * \toptions: [\n\t * \t\t{ label: 'option 1', value: '1' },\n\t * \t\t{ label: 'option 2', value: '2' },\n\t * \t\t{ label: 'option 3', value: '3' },\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * \t.addOptions({\n\t * \t\tlabel: 'Catchy',\n\t * \t\tvalue: 'catch',\n\t * \t});\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tconst { options, ...initData } = data ?? {};\n\t\tsuper({ ...initData, type: ComponentType.StringSelect });\n\t\tthis.options = options?.map((option: APISelectMenuOption) => new StringSelectMenuOptionBuilder(option)) ?? [];\n\t}\n\n\t/**\n\t * Adds options to this select menu.\n\t *\n\t * @param options - The options to add\n\t */\n\tpublic addOptions(...options: RestOrArray) {\n\t\tconst normalizedOptions = normalizeArray(options);\n\t\toptionsLengthValidator.parse(this.options.length + normalizedOptions.length);\n\t\tthis.options.push(\n\t\t\t...normalizedOptions.map((normalizedOption) =>\n\t\t\t\tnormalizedOption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? normalizedOption\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the options for this select menu.\n\t *\n\t * @param options - The options to set\n\t */\n\tpublic setOptions(...options: RestOrArray) {\n\t\treturn this.spliceOptions(0, this.options.length, ...options);\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts options for this select menu.\n\t *\n\t * @remarks\n\t * This method behaves similarly\n\t * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice()}.\n\t * It's useful for modifying and adjusting the order of existing options.\n\t * @example\n\t * Remove the first option:\n\t * ```ts\n\t * selectMenu.spliceOptions(0, 1);\n\t * ```\n\t * @example\n\t * Remove the first n option:\n\t * ```ts\n\t * const n = 4;\n\t * selectMenu.spliceOptions(0, n);\n\t * ```\n\t * @example\n\t * Remove the last option:\n\t * ```ts\n\t * selectMenu.spliceOptions(-1, 1);\n\t * ```\n\t * @param index - The index to start at\n\t * @param deleteCount - The number of options to remove\n\t * @param options - The replacing option objects or builders\n\t */\n\tpublic spliceOptions(\n\t\tindex: number,\n\t\tdeleteCount: number,\n\t\t...options: RestOrArray\n\t) {\n\t\tconst normalizedOptions = normalizeArray(options);\n\n\t\tconst clone = [...this.options];\n\n\t\tclone.splice(\n\t\t\tindex,\n\t\t\tdeleteCount,\n\t\t\t...normalizedOptions.map((normalizedOption) =>\n\t\t\t\tnormalizedOption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? normalizedOption\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)),\n\t\t\t),\n\t\t);\n\n\t\toptionsLengthValidator.parse(clone.length);\n\t\tthis.options.splice(0, this.options.length, ...clone);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIStringSelectComponent {\n\t\tvalidateRequiredSelectMenuParameters(this.options, this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t} as APIStringSelectComponent;\n\t}\n}\n","import type { APIUserSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for user select menus.\n */\nexport class UserSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.UserSelect });\n\t}\n}\n","import { isJSONEncodable, type Equatable, type JSONEncodable } from '@discordjs/util';\nimport { ComponentType, type TextInputStyle, type APITextInputComponent } from 'discord-api-types/v10';\nimport isEqual from 'fast-deep-equal';\nimport { customIdValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\nimport {\n\tmaxLengthValidator,\n\tminLengthValidator,\n\tplaceholderValidator,\n\trequiredValidator,\n\tvalueValidator,\n\tvalidateRequiredParameters,\n\tlabelValidator,\n\ttextInputStyleValidator,\n} from './Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for text inputs.\n */\nexport class TextInputBuilder\n\textends ComponentBuilder\n\timplements Equatable>\n{\n\t/**\n\t * Creates a new text input from API data.\n\t *\n\t * @param data - The API data to create this text input with\n\t * @example\n\t * Creating a select menu option from an API data object:\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tlabel: 'Type something',\n\t * \tstyle: TextInputStyle.Short,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu option using setters and API data:\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tlabel: 'Type something else',\n\t * })\n\t * \t.setCustomId('woah')\n\t * \t.setStyle(TextInputStyle.Paragraph);\n\t * ```\n\t */\n\tpublic constructor(data?: APITextInputComponent & { type?: ComponentType.TextInput }) {\n\t\tsuper({ type: ComponentType.TextInput, ...data });\n\t}\n\n\t/**\n\t * Sets the custom id for this text input.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this text input.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the style for this text input.\n\t *\n\t * @param style - The style to use\n\t */\n\tpublic setStyle(style: TextInputStyle) {\n\t\tthis.data.style = textInputStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of text for this text input.\n\t *\n\t * @param minLength - The minimum length of text for this text input\n\t */\n\tpublic setMinLength(minLength: number) {\n\t\tthis.data.min_length = minLengthValidator.parse(minLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum length of text for this text input.\n\t *\n\t * @param maxLength - The maximum length of text for this text input\n\t */\n\tpublic setMaxLength(maxLength: number) {\n\t\tthis.data.max_length = maxLengthValidator.parse(maxLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the placeholder for this text input.\n\t *\n\t * @param placeholder - The placeholder to use\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value for this text input.\n\t *\n\t * @param value - The value to use\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = valueValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this text input is required.\n\t *\n\t * @param required - Whether this text input is required\n\t */\n\tpublic setRequired(required = true) {\n\t\tthis.data.required = requiredValidator.parse(required);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APITextInputComponent {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.style, this.data.label);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APITextInputComponent;\n\t}\n\n\t/**\n\t * {@inheritDoc Equatable.equals}\n\t */\n\tpublic equals(other: APITextInputComponent | JSONEncodable): boolean {\n\t\tif (isJSONEncodable(other)) {\n\t\t\treturn isEqual(other.toJSON(), this.data);\n\t\t}\n\n\t\treturn isEqual(other, this.data);\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { TextInputStyle } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport { customIdValidator } from '../Assertions.js';\n\nexport const textInputStyleValidator = s.nativeEnum(TextInputStyle);\nexport const minLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const maxLengthValidator = s.number.int\n\t.greaterThanOrEqual(1)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const requiredValidator = s.boolean;\nexport const valueValidator = s.string.lengthLessThanOrEqual(4_000).setValidationEnabled(isValidationEnabled);\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled);\nexport const labelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(customId?: string, style?: TextInputStyle, label?: string) {\n\tcustomIdValidator.parse(customId);\n\ttextInputStyleValidator.parse(style);\n\tlabelValidator.parse(label);\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const titleValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\nexport const componentsValidator = s\n\t.instance(ActionRowBuilder)\n\t.array.lengthGreaterThanOrEqual(1)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(\n\tcustomId?: string,\n\ttitle?: string,\n\tcomponents?: ActionRowBuilder[],\n) {\n\tcustomIdValidator.parse(customId);\n\ttitleValidator.parse(title);\n\tcomponentsValidator.parse(components);\n}\n","/* eslint-disable jsdoc/check-param-names */\n\nimport type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIModalActionRowComponent,\n\tAPIModalInteractionResponseCallbackData,\n} from 'discord-api-types/v10';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { createComponentBuilder } from '../../components/Components.js';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { titleValidator, validateRequiredParameters } from './Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for modals.\n */\nexport class ModalBuilder implements JSONEncodable {\n\t/**\n\t * The API data associated with this modal.\n\t */\n\tpublic readonly data: Partial;\n\n\t/**\n\t * The components within this modal.\n\t */\n\tpublic readonly components: ActionRowBuilder[] = [];\n\n\t/**\n\t * Creates a new modal from API data.\n\t *\n\t * @param data - The API data to create this modal with\n\t */\n\tpublic constructor({ components, ...data }: Partial = {}) {\n\t\tthis.data = { ...data };\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ??\n\t\t\t[]) as ActionRowBuilder[];\n\t}\n\n\t/**\n\t * Sets the title of this modal.\n\t *\n\t * @param title - The title to use\n\t */\n\tpublic setTitle(title: string) {\n\t\tthis.data.title = titleValidator.parse(title);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id of this modal.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds components to this modal.\n\t *\n\t * @param components - The components to add\n\t */\n\tpublic addComponents(\n\t\t...components: RestOrArray<\n\t\t\tActionRowBuilder | APIActionRowComponent\n\t\t>\n\t) {\n\t\tthis.components.push(\n\t\t\t...normalizeArray(components).map((component) =>\n\t\t\t\tcomponent instanceof ActionRowBuilder\n\t\t\t\t\t? component\n\t\t\t\t\t: new ActionRowBuilder(component),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets components for this modal.\n\t *\n\t * @param components - The components to set\n\t */\n\tpublic setComponents(...components: RestOrArray>) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIModalInteractionResponseCallbackData {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.title, this.components);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIModalInteractionResponseCallbackData;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { Locale, type APIApplicationCommandOptionChoice, type LocalizationMap } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t.regex(/^[\\p{Ll}\\p{Lm}\\p{Lo}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}_-]+$/u)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nconst descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\nconst localePredicate = s.nativeEnum(Locale);\n\nexport function validateDescription(description: unknown): asserts description is string {\n\tdescriptionPredicate.parse(description);\n}\n\nconst maxArrayLengthPredicate = s.unknown.array.lengthLessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\nexport function validateLocale(locale: unknown) {\n\treturn localePredicate.parse(locale);\n}\n\nexport function validateMaxOptionsLength(options: unknown): asserts options is ToAPIApplicationCommandOptions[] {\n\tmaxArrayLengthPredicate.parse(options);\n}\n\nexport function validateRequiredParameters(\n\tname: string,\n\tdescription: string,\n\toptions: ToAPIApplicationCommandOptions[],\n) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert description conditions\n\tvalidateDescription(description);\n\n\t// Assert options conditions\n\tvalidateMaxOptionsLength(options);\n}\n\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateRequired(required: unknown): asserts required is boolean {\n\tbooleanPredicate.parse(required);\n}\n\nconst choicesLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateChoicesLength(amountAdding: number, choices?: APIApplicationCommandOptionChoice[]): void {\n\tchoicesLengthPredicate.parse((choices?.length ?? 0) + amountAdding);\n}\n\nexport function assertReturnOfBuilder<\n\tT extends ApplicationCommandOptionBase | SlashCommandSubcommandBuilder | SlashCommandSubcommandGroupBuilder,\n>(input: unknown, ExpectedInstanceOf: new () => T): asserts input is T {\n\ts.instance(ExpectedInstanceOf).parse(input);\n}\n\nexport const localizationMapPredicate = s\n\t.object(Object.fromEntries(Object.values(Locale).map((locale) => [locale, s.string.nullish])))\n\t.strict.nullish.setValidationEnabled(isValidationEnabled);\n\nexport function validateLocalizationMap(value: unknown): asserts value is LocalizationMap {\n\tlocalizationMapPredicate.parse(value);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n\nexport function validateNSFW(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n","import type {\n\tAPIApplicationCommandOption,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIChatInputApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport {\n\tassertReturnOfBuilder,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDefaultPermission,\n\tvalidateLocalizationMap,\n\tvalidateDMPermission,\n\tvalidateMaxOptionsLength,\n\tvalidateRequiredParameters,\n\tvalidateNSFW,\n} from './Assertions.js';\nimport { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n/**\n * A builder that creates API-compatible JSON data for slash commands.\n */\n@mix(SharedSlashCommandOptions, SharedNameAndDescription)\nexport class SlashCommandBuilder {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The description of this command.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The description localizations of this command.\n\t */\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * The options of this command.\n\t */\n\tpublic readonly options: ToAPIApplicationCommandOptions[] = [];\n\n\t/**\n\t * Whether this command is enabled by default when the application is added to a guild.\n\t *\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * The set of permissions represented as a bit set for the command.\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This property is only for global commands.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Whether this command is NSFW.\n\t */\n\tpublic readonly nsfw: boolean | undefined = undefined;\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether or not to enable this command by default\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t * @deprecated Use {@link SlashCommandBuilder.setDefaultMemberPermissions} or {@link SlashCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run the command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This method is only for global commands.\n\t * @param enabled - Whether the command should be enabled in direct messages\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this command is NSFW.\n\t *\n\t * @param nsfw - Whether this command is NSFW\n\t */\n\tpublic setNSFW(nsfw = true) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateNSFW(nsfw);\n\t\tReflect.set(this, 'nsfw', nsfw);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand group to this command.\n\t *\n\t * @param input - A function that returns a subcommand group builder or an already built builder\n\t */\n\tpublic addSubcommandGroup(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandGroupBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandGroupBuilder) => SlashCommandSubcommandGroupBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandGroupBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandGroupBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand to this command.\n\t *\n\t * @param input - A function that returns a subcommand builder or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIChatInputApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\treturn {\n\t\t\t...this,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n\n/**\n * An interface specifically for slash command subcommands.\n */\nexport interface SlashCommandSubcommandsOnlyBuilder\n\textends Omit> {}\n\n/**\n * An interface specifically for slash command options.\n */\nexport interface SlashCommandOptionsOnlyBuilder\n\textends SharedNameAndDescription,\n\t\tSharedSlashCommandOptions,\n\t\tPick {}\n\n/**\n * An interface that ensures the `toJSON()` call will return something\n * that can be serialized into API-compatible data.\n */\nexport interface ToAPIApplicationCommandOptions {\n\ttoJSON(): APIApplicationCommandOption;\n}\n","import {\n\tApplicationCommandOptionType,\n\ttype APIApplicationCommandSubcommandGroupOption,\n\ttype APIApplicationCommandSubcommandOption,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { assertReturnOfBuilder, validateMaxOptionsLength, validateRequiredParameters } from './Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n/**\n * Represents a folder for subcommands.\n *\n * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups}\n */\n@mix(SharedNameAndDescription)\nexport class SlashCommandSubcommandGroupBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand group.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand group.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The subcommands within this subcommand group.\n\t */\n\tpublic readonly options: SlashCommandSubcommandBuilder[] = [];\n\n\t/**\n\t * Adds a new subcommand to this group.\n\t *\n\t * @param input - A function that returns a subcommand builder or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t) {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIApplicationCommandSubcommandGroupOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.SubcommandGroup,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription {}\n\n/**\n * A builder that creates API-compatible JSON data for slash command subcommands.\n *\n * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups}\n */\n@mix(SharedNameAndDescription, SharedSlashCommandOptions)\nexport class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The options within this subcommand.\n\t */\n\tpublic readonly options: ApplicationCommandOptionBase[] = [];\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIApplicationCommandSubcommandOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.Subcommand,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n","import type { LocaleString, LocalizationMap } from 'discord-api-types/v10';\nimport { validateDescription, validateLocale, validateName } from '../Assertions.js';\n\n/**\n * This mixin holds name and description symbols for slash commands.\n */\nexport class SharedNameAndDescription {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name!: string;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The description of this command.\n\t */\n\tpublic readonly description!: string;\n\n\t/**\n\t * The description localizations of this command.\n\t */\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * Sets the name of this command.\n\t *\n\t * @param name - The name to use\n\t */\n\tpublic setName(name: string): this {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this command.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string) {\n\t\t// Assert the description matches the conditions\n\t\tvalidateDescription(description);\n\n\t\tReflect.set(this, 'description', description);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * SSets a name localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedName - The localized name for the given `locale`\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations for this command.\n\t *\n\t * @param localizedNames - The object of localized names to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames)) {\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a description localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedDescription - The localized description for the given locale\n\t */\n\tpublic setDescriptionLocalization(locale: LocaleString, localizedDescription: string | null) {\n\t\tif (!this.description_localizations) {\n\t\t\tReflect.set(this, 'description_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedDescription === null) {\n\t\t\tthis.description_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateDescription(localizedDescription);\n\n\t\tthis.description_localizations![parsedLocale] = localizedDescription;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description localizations for this command.\n\t *\n\t * @param localizedDescriptions - The object of localized descriptions to set\n\t */\n\tpublic setDescriptionLocalizations(localizedDescriptions: LocalizationMap | null) {\n\t\tif (localizedDescriptions === null) {\n\t\t\tReflect.set(this, 'description_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'description_localizations', {});\n\t\tfor (const args of Object.entries(localizedDescriptions)) {\n\t\t\tthis.setDescriptionLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandAttachmentOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command attachment option.\n */\nexport class SlashCommandAttachmentOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Attachment as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandAttachmentOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import type { APIApplicationCommandBasicOption, ApplicationCommandOptionType } from 'discord-api-types/v10';\nimport { validateRequiredParameters, validateRequired, validateLocalizationMap } from '../Assertions.js';\nimport { SharedNameAndDescription } from './NameAndDescription.js';\n\n/**\n * The base application command option builder that contains common symbols for application command builders.\n */\nexport abstract class ApplicationCommandOptionBase extends SharedNameAndDescription {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic abstract readonly type: ApplicationCommandOptionType;\n\n\t/**\n\t * Whether this option is required.\n\t *\n\t * @defaultValue `false`\n\t */\n\tpublic readonly required: boolean = false;\n\n\t/**\n\t * Sets whether this option is required.\n\t *\n\t * @param required - Whether this option should be required\n\t */\n\tpublic setRequired(required: boolean) {\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(required);\n\n\t\tReflect.set(this, 'required', required);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic abstract toJSON(): APIApplicationCommandBasicOption;\n\n\t/**\n\t * This method runs required validators on this builder.\n\t */\n\tprotected runRequiredValidations() {\n\t\tvalidateRequiredParameters(this.name, this.description, []);\n\n\t\t// Validate localizations\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(this.required);\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandBooleanOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command boolean option.\n */\nexport class SlashCommandBooleanOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Boolean as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandBooleanOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandChannelOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionChannelTypesMixin } from '../mixins/ApplicationCommandOptionChannelTypesMixin.js';\n\n/**\n * A slash command channel option.\n */\n@mix(ApplicationCommandOptionChannelTypesMixin)\nexport class SlashCommandChannelOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Channel as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandChannelOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandChannelOption extends ApplicationCommandOptionChannelTypesMixin {}\n","import { s } from '@sapphire/shapeshift';\nimport { ChannelType } from 'discord-api-types/v10';\n\n/**\n * The allowed channel types used for a channel option in a slash command builder.\n *\n * @privateRemarks This can't be dynamic because const enums are erased at runtime.\n * @internal\n */\nconst allowedChannelTypes = [\n\tChannelType.GuildText,\n\tChannelType.GuildVoice,\n\tChannelType.GuildCategory,\n\tChannelType.GuildAnnouncement,\n\tChannelType.AnnouncementThread,\n\tChannelType.PublicThread,\n\tChannelType.PrivateThread,\n\tChannelType.GuildStageVoice,\n\tChannelType.GuildForum,\n] as const;\n\n/**\n * The type of allowed channel types used for a channel option.\n */\nexport type ApplicationCommandOptionAllowedChannelTypes = (typeof allowedChannelTypes)[number];\n\nconst channelTypesPredicate = s.array(s.union(...allowedChannelTypes.map((type) => s.literal(type))));\n\n/**\n * This mixin holds channel type symbols used for options.\n */\nexport class ApplicationCommandOptionChannelTypesMixin {\n\t/**\n\t * The channel types of this option.\n\t */\n\tpublic readonly channel_types?: ApplicationCommandOptionAllowedChannelTypes[];\n\n\t/**\n\t * Adds channel types to this option.\n\t *\n\t * @param channelTypes - The channel types\n\t */\n\tpublic addChannelTypes(...channelTypes: ApplicationCommandOptionAllowedChannelTypes[]) {\n\t\tif (this.channel_types === undefined) {\n\t\t\tReflect.set(this, 'channel_types', []);\n\t\t}\n\n\t\tthis.channel_types!.push(...channelTypesPredicate.parse(channelTypes));\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandIntegerOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number.int;\n\n/**\n * A slash command integer option.\n */\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandIntegerOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Integer as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandIntegerOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandIntegerOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","/**\n * This mixin holds minimum and maximum symbols used for options.\n */\nexport abstract class ApplicationCommandNumericOptionMinMaxValueMixin {\n\t/**\n\t * The maximum value of this option.\n\t */\n\tpublic readonly max_value?: number;\n\n\t/**\n\t * The minimum value of this option.\n\t */\n\tpublic readonly min_value?: number;\n\n\t/**\n\t * Sets the maximum number value of this option.\n\t *\n\t * @param max - The maximum value this option can be\n\t */\n\tpublic abstract setMaxValue(max: number): this;\n\n\t/**\n\t * Sets the minimum number value of this option.\n\t *\n\t * @param min - The minimum value this option can be\n\t */\n\tpublic abstract setMinValue(min: number): this;\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandOptionChoice } from 'discord-api-types/v10';\nimport { localizationMapPredicate, validateChoicesLength } from '../Assertions.js';\n\nconst stringPredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100);\nconst numberPredicate = s.number.greaterThan(Number.NEGATIVE_INFINITY).lessThan(Number.POSITIVE_INFINITY);\nconst choicesPredicate = s.object({\n\tname: stringPredicate,\n\tname_localizations: localizationMapPredicate,\n\tvalue: s.union(stringPredicate, numberPredicate),\n}).array;\nconst booleanPredicate = s.boolean;\n\n/**\n * This mixin holds choices and autocomplete symbols used for options.\n */\nexport class ApplicationCommandOptionWithChoicesAndAutocompleteMixin {\n\t/**\n\t * The choices of this option.\n\t */\n\tpublic readonly choices?: APIApplicationCommandOptionChoice[];\n\n\t/**\n\t * Whether this option utilizes autocomplete.\n\t */\n\tpublic readonly autocomplete?: boolean;\n\n\t/**\n\t * The type of this option.\n\t *\n\t * @privateRemarks Since this is present and this is a mixin, this is needed.\n\t */\n\tpublic readonly type!: ApplicationCommandOptionType;\n\n\t/**\n\t * Adds multiple choices to this option.\n\t *\n\t * @param choices - The choices to add\n\t */\n\tpublic addChoices(...choices: APIApplicationCommandOptionChoice[]): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tif (this.choices === undefined) {\n\t\t\tReflect.set(this, 'choices', []);\n\t\t}\n\n\t\tvalidateChoicesLength(choices.length, this.choices);\n\n\t\tfor (const { name, name_localizations, value } of choices) {\n\t\t\t// Validate the value\n\t\t\tif (this.type === ApplicationCommandOptionType.String) {\n\t\t\t\tstringPredicate.parse(value);\n\t\t\t} else {\n\t\t\t\tnumberPredicate.parse(value);\n\t\t\t}\n\n\t\t\tthis.choices!.push({ name, name_localizations, value });\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets multiple choices for this option.\n\t *\n\t * @param choices - The choices to set\n\t */\n\tpublic setChoices[]>(...choices: Input): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tReflect.set(this, 'choices', []);\n\t\tthis.addChoices(...choices);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Whether this option uses autocomplete.\n\t *\n\t * @param autocomplete - Whether this option should use autocomplete\n\t */\n\tpublic setAutocomplete(autocomplete: boolean): this {\n\t\t// Assert that you actually passed a boolean\n\t\tbooleanPredicate.parse(autocomplete);\n\n\t\tif (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tReflect.set(this, 'autocomplete', autocomplete);\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandMentionableOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command mentionable option.\n */\nexport class SlashCommandMentionableOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Mentionable as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandMentionableOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandNumberOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number;\n\n/**\n * A slash command number option.\n */\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandNumberOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Number as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandNumberOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandNumberOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandRoleOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command role option.\n */\nexport class SlashCommandRoleOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Role as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandRoleOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandStringOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst minLengthValidator = s.number.greaterThanOrEqual(0).lessThanOrEqual(6_000);\nconst maxLengthValidator = s.number.greaterThanOrEqual(1).lessThanOrEqual(6_000);\n\n/**\n * A slash command string option.\n */\n@mix(ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandStringOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.String as const;\n\n\t/**\n\t * The maximum length of this option.\n\t */\n\tpublic readonly max_length?: number;\n\n\t/**\n\t * The minimum length of this option.\n\t */\n\tpublic readonly min_length?: number;\n\n\t/**\n\t * Sets the maximum length of this string option.\n\t *\n\t * @param max - The maximum length this option can be\n\t */\n\tpublic setMaxLength(max: number): this {\n\t\tmaxLengthValidator.parse(max);\n\n\t\tReflect.set(this, 'max_length', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of this string option.\n\t *\n\t * @param min - The minimum length this option can be\n\t */\n\tpublic setMinLength(min: number): this {\n\t\tminLengthValidator.parse(min);\n\n\t\tReflect.set(this, 'min_length', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandStringOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandStringOption extends ApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandUserOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command user option.\n */\nexport class SlashCommandUserOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.User as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandUserOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { assertReturnOfBuilder, validateMaxOptionsLength } from '../Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from '../SlashCommandBuilder';\nimport { SlashCommandAttachmentOption } from '../options/attachment.js';\nimport { SlashCommandBooleanOption } from '../options/boolean.js';\nimport { SlashCommandChannelOption } from '../options/channel.js';\nimport { SlashCommandIntegerOption } from '../options/integer.js';\nimport { SlashCommandMentionableOption } from '../options/mentionable.js';\nimport { SlashCommandNumberOption } from '../options/number.js';\nimport { SlashCommandRoleOption } from '../options/role.js';\nimport { SlashCommandStringOption } from '../options/string.js';\nimport { SlashCommandUserOption } from '../options/user.js';\nimport type { ApplicationCommandOptionBase } from './ApplicationCommandOptionBase.js';\n\n/**\n * This mixin holds symbols that can be shared in slash command options.\n *\n * @typeParam ShouldOmitSubcommandFunctions - Whether to omit subcommand functions.\n */\nexport class SharedSlashCommandOptions {\n\tpublic readonly options!: ToAPIApplicationCommandOptions[];\n\n\t/**\n\t * Adds a boolean option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addBooleanOption(\n\t\tinput: SlashCommandBooleanOption | ((builder: SlashCommandBooleanOption) => SlashCommandBooleanOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandBooleanOption);\n\t}\n\n\t/**\n\t * Adds a user option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addUserOption(input: SlashCommandUserOption | ((builder: SlashCommandUserOption) => SlashCommandUserOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandUserOption);\n\t}\n\n\t/**\n\t * Adds a channel option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addChannelOption(\n\t\tinput: SlashCommandChannelOption | ((builder: SlashCommandChannelOption) => SlashCommandChannelOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandChannelOption);\n\t}\n\n\t/**\n\t * Adds a role option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addRoleOption(input: SlashCommandRoleOption | ((builder: SlashCommandRoleOption) => SlashCommandRoleOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandRoleOption);\n\t}\n\n\t/**\n\t * Adds an attachment option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addAttachmentOption(\n\t\tinput: SlashCommandAttachmentOption | ((builder: SlashCommandAttachmentOption) => SlashCommandAttachmentOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandAttachmentOption);\n\t}\n\n\t/**\n\t * Adds a mentionable option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addMentionableOption(\n\t\tinput: SlashCommandMentionableOption | ((builder: SlashCommandMentionableOption) => SlashCommandMentionableOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandMentionableOption);\n\t}\n\n\t/**\n\t * Adds a string option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addStringOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandStringOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandStringOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandStringOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandStringOption);\n\t}\n\n\t/**\n\t * Adds an integer option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addIntegerOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandIntegerOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandIntegerOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandIntegerOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandIntegerOption);\n\t}\n\n\t/**\n\t * Adds a number option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addNumberOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandNumberOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandNumberOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandNumberOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandNumberOption);\n\t}\n\n\t/**\n\t * Where the actual adding magic happens. ✨\n\t *\n\t * @param input - The input. What else?\n\t * @param Instance - The instance of whatever is being added\n\t * @internal\n\t */\n\tprivate _sharedAddOptionMethod(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| T\n\t\t\t| ((builder: T) => Omit | Omit | T),\n\t\tInstance: new () => T,\n\t): ShouldOmitSubcommandFunctions extends true ? Omit : this {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new Instance()) : input;\n\n\t\tassertReturnOfBuilder(result, Instance);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandType } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ContextMenuCommandType } from './ContextMenuCommandBuilder.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t// eslint-disable-next-line prefer-named-capture-group, unicorn/no-unsafe-regex\n\t.regex(/^( *[\\p{P}\\p{L}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}]+ *)+$/u)\n\t.setValidationEnabled(isValidationEnabled);\nconst typePredicate = s\n\t.union(s.literal(ApplicationCommandType.User), s.literal(ApplicationCommandType.Message))\n\t.setValidationEnabled(isValidationEnabled);\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nexport function validateType(type: unknown): asserts type is ContextMenuCommandType {\n\ttypePredicate.parse(type);\n}\n\nexport function validateRequiredParameters(name: string, type: number) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert type is valid\n\tvalidateType(type);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n","import type {\n\tApplicationCommandType,\n\tLocaleString,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIContextMenuApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { validateLocale, validateLocalizationMap } from '../slashCommands/Assertions.js';\nimport {\n\tvalidateRequiredParameters,\n\tvalidateName,\n\tvalidateType,\n\tvalidateDefaultPermission,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDMPermission,\n} from './Assertions.js';\n\n/**\n * The type a context menu command can be.\n */\nexport type ContextMenuCommandType = ApplicationCommandType.Message | ApplicationCommandType.User;\n\n/**\n * A builder that creates API-compatible JSON data for context menu commands.\n */\nexport class ContextMenuCommandBuilder {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The type of this command.\n\t */\n\tpublic readonly type: ContextMenuCommandType = undefined!;\n\n\t/**\n\t * Whether this command is enabled by default when the application is added to a guild.\n\t *\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * The set of permissions represented as a bit set for the command.\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This property is only for global commands.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Sets the name of this command.\n\t *\n\t * @param name - The name to use\n\t */\n\tpublic setName(name: string) {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the type of this command.\n\t *\n\t * @param type - The type to use\n\t */\n\tpublic setType(type: ContextMenuCommandType) {\n\t\t// Assert the type is valid\n\t\tvalidateType(type);\n\n\t\tReflect.set(this, 'type', type);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether to enable this command by default\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run this command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This method is only for global commands.\n\t * @param enabled - Whether the command should be enabled in direct messages\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a name localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedName - The localized name for the given `locale`\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations for this command.\n\t *\n\t * @param localizedNames - The object of localized names to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames))\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIContextMenuApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.type);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\n\t\treturn { ...this };\n\t}\n}\n","import type { APIEmbed } from 'discord-api-types/v10';\n\n/**\n * Calculates the length of the embed.\n *\n * @param data - The embed data to check\n */\nexport function embedLength(data: APIEmbed) {\n\treturn (\n\t\t(data.title?.length ?? 0) +\n\t\t(data.description?.length ?? 0) +\n\t\t(data.fields?.reduce((prev, curr) => prev + curr.name.length + curr.value.length, 0) ?? 0) +\n\t\t(data.footer?.text.length ?? 0) +\n\t\t(data.author?.name.length ?? 0)\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,6BAAAA;AAAA,EAAA;AAAA,sCAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA,yBAAAA;AAAA,EAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,gCAAAA;AAA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QAAQ,OAAO,QAAQ,cAAc;AAC/C,WAAK,oBAAoB,GAAI,IAAsC;AACpE,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,SAA4D;AAClE,IAAAI,4BAA2B,KAAK,MAAM,KAAK,IAAI;AAE/C,4BAAwB,KAAK,kBAAkB;AAE/C,WAAO,EAAE,GAAG,KAAK;AAAA,EAClB;AACD;AA5Ka;;;AClBN,SAAS,YAAY,MAAgB;AAC3C,UACE,KAAK,OAAO,UAAU,MACtB,KAAK,aAAa,UAAU,MAC5B,KAAK,QAAQ,OAAO,CAAC,MAAM,SAAS,OAAO,KAAK,KAAK,SAAS,KAAK,MAAM,QAAQ,CAAC,KAAK,MACvF,KAAK,QAAQ,KAAK,UAAU,MAC5B,KAAK,QAAQ,KAAK,UAAU;AAE/B;AARgB;;;AzC6DT,IAAM,UAAU;","names":["Assertions_exports","Assertions_exports","import_shapeshift","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","import_v10","Assertions_exports","placeholderValidator","import_shapeshift","import_v10","placeholderValidator","placeholderValidator","isEqual","Assertions_exports","validateRequiredParameters","import_shapeshift","validateRequiredParameters","validateRequiredParameters","Assertions_exports","validateRequiredParameters","import_shapeshift","import_v10","descriptionPredicate","validateRequiredParameters","import_ts_mixer","import_v10","import_ts_mixer","import_v10","validateRequiredParameters","import_v10","import_v10","import_shapeshift","import_v10","import_shapeshift","import_v10","import_ts_mixer","import_shapeshift","import_v10","booleanPredicate","import_v10","import_shapeshift","import_v10","import_ts_mixer","numberValidator","import_v10","import_shapeshift","import_v10","import_ts_mixer","minLengthValidator","maxLengthValidator","import_v10","validateRequiredParameters","validateRequiredParameters","Assertions_exports","validateDMPermission","validateDefaultMemberPermissions","validateDefaultPermission","validateName","validateRequiredParameters","import_shapeshift","import_v10","namePredicate","booleanPredicate","validateDefaultPermission","validateName","validateRequiredParameters","dmPermissionPredicate","validateDMPermission","memberPermissionPredicate","validateDefaultMemberPermissions","validateName","validateDefaultPermission","validateDefaultMemberPermissions","validateDMPermission","validateRequiredParameters"]} \ No newline at end of file diff --git a/node_modules/@discordjs/builders/dist/index.mjs b/node_modules/@discordjs/builders/dist/index.mjs index 6741e4e..2f32e8d 100644 --- a/node_modules/@discordjs/builders/dist/index.mjs +++ b/node_modules/@discordjs/builders/dist/index.mjs @@ -41,9 +41,18 @@ import { s } from "@sapphire/shapeshift"; // src/util/validation.ts var validate = true; -var enableValidators = /* @__PURE__ */ __name(() => validate = true, "enableValidators"); -var disableValidators = /* @__PURE__ */ __name(() => validate = false, "disableValidators"); -var isValidationEnabled = /* @__PURE__ */ __name(() => validate, "isValidationEnabled"); +function enableValidators() { + return validate = true; +} +__name(enableValidators, "enableValidators"); +function disableValidators() { + return validate = false; +} +__name(disableValidators, "disableValidators"); +function isValidationEnabled() { + return validate; +} +__name(isValidationEnabled, "isValidationEnabled"); // src/messages/embed/Assertions.ts var fieldNamePredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(256).setValidationEnabled(isValidationEnabled); @@ -93,22 +102,83 @@ __name(normalizeArray, "normalizeArray"); // src/messages/embed/Embed.ts var EmbedBuilder = class { + /** + * The API data associated with this embed. + */ data; + /** + * Creates a new embed from API data. + * + * @param data - The API data to create this embed with + */ constructor(data = {}) { this.data = { ...data }; if (data.timestamp) this.data.timestamp = new Date(data.timestamp).toISOString(); } + /** + * Appends fields to the embed. + * + * @remarks + * This method accepts either an array of fields or a variable number of field parameters. + * The maximum amount of fields that can be added is 25. + * @example + * Using an array: + * ```ts + * const fields: APIEmbedField[] = ...; + * const embed = new EmbedBuilder() + * .addFields(fields); + * ``` + * @example + * Using rest parameters (variadic): + * ```ts + * const embed = new EmbedBuilder() + * .addFields( + * { name: 'Field 1', value: 'Value 1' }, + * { name: 'Field 2', value: 'Value 2' }, + * ); + * ``` + * @param fields - The fields to add + */ addFields(...fields) { - fields = normalizeArray(fields); - validateFieldLength(fields.length, this.data.fields); - embedFieldsArrayPredicate.parse(fields); + const normalizedFields = normalizeArray(fields); + validateFieldLength(normalizedFields.length, this.data.fields); + embedFieldsArrayPredicate.parse(normalizedFields); if (this.data.fields) - this.data.fields.push(...fields); + this.data.fields.push(...normalizedFields); else - this.data.fields = fields; - return this; - } + this.data.fields = normalizedFields; + return this; + } + /** + * Removes, replaces, or inserts fields for this embed. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice | Array.prototype.splice()}. + * The maximum amount of fields that can be added is 25. + * + * It's useful for modifying and adjusting order of the already-existing fields of an embed. + * @example + * Remove the first field: + * ```ts + * embed.spliceFields(0, 1); + * ``` + * @example + * Remove the first n fields: + * ```ts + * const n = 4; + * embed.spliceFields(0, n); + * ``` + * @example + * Remove the last field: + * ```ts + * embed.spliceFields(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of fields to remove + * @param fields - The replacing field objects + */ spliceFields(index, deleteCount, ...fields) { validateFieldLength(fields.length - deleteCount, this.data.fields); embedFieldsArrayPredicate.parse(fields); @@ -118,10 +188,25 @@ var EmbedBuilder = class { this.data.fields = fields; return this; } + /** + * Sets the fields for this embed. + * + * @remarks + * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically, + * it splices the entire array of fields, replacing them with the provided fields. + * + * You can set a maximum of 25 fields. + * @param fields - The fields to set + */ setFields(...fields) { this.spliceFields(0, this.data.fields?.length ?? 0, ...normalizeArray(fields)); return this; } + /** + * Sets the author of this embed. + * + * @param options - The options to use + */ setAuthor(options) { if (options === null) { this.data.author = void 0; @@ -131,6 +216,11 @@ var EmbedBuilder = class { this.data.author = { name: options.name, url: options.url, icon_url: options.iconURL }; return this; } + /** + * Sets the color of this embed. + * + * @param color - The color to use + */ setColor(color) { colorPredicate.parse(color); if (Array.isArray(color)) { @@ -141,11 +231,21 @@ var EmbedBuilder = class { this.data.color = color ?? void 0; return this; } + /** + * Sets the description of this embed. + * + * @param description - The description to use + */ setDescription(description) { descriptionPredicate.parse(description); this.data.description = description ?? void 0; return this; } + /** + * Sets the footer of this embed. + * + * @param options - The footer to use + */ setFooter(options) { if (options === null) { this.data.footer = void 0; @@ -155,142 +255,71 @@ var EmbedBuilder = class { this.data.footer = { text: options.text, icon_url: options.iconURL }; return this; } + /** + * Sets the image of this embed. + * + * @param url - The image URL to use + */ setImage(url) { imageURLPredicate.parse(url); this.data.image = url ? { url } : void 0; return this; } + /** + * Sets the thumbnail of this embed. + * + * @param url - The thumbnail URL to use + */ setThumbnail(url) { imageURLPredicate.parse(url); this.data.thumbnail = url ? { url } : void 0; return this; } + /** + * Sets the timestamp of this embed. + * + * @param timestamp - The timestamp or date to use + */ setTimestamp(timestamp = Date.now()) { timestampPredicate.parse(timestamp); this.data.timestamp = timestamp ? new Date(timestamp).toISOString() : void 0; return this; } + /** + * Sets the title for this embed. + * + * @param title - The title to use + */ setTitle(title) { titlePredicate.parse(title); this.data.title = title ?? void 0; return this; } + /** + * Sets the URL of this embed. + * + * @param url - The URL to use + */ setURL(url) { urlPredicate.parse(url); this.data.url = url ?? void 0; return this; } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON() { return { ...this.data }; } }; __name(EmbedBuilder, "EmbedBuilder"); -// src/messages/formatters.ts -function codeBlock(language, content) { - return typeof content === "undefined" ? `\`\`\` -${language} -\`\`\`` : `\`\`\`${language} -${content} -\`\`\``; -} -__name(codeBlock, "codeBlock"); -function inlineCode(content) { - return `\`${content}\``; -} -__name(inlineCode, "inlineCode"); -function italic(content) { - return `_${content}_`; -} -__name(italic, "italic"); -function bold(content) { - return `**${content}**`; -} -__name(bold, "bold"); -function underscore(content) { - return `__${content}__`; -} -__name(underscore, "underscore"); -function strikethrough(content) { - return `~~${content}~~`; -} -__name(strikethrough, "strikethrough"); -function quote(content) { - return `> ${content}`; -} -__name(quote, "quote"); -function blockQuote(content) { - return `>>> ${content}`; -} -__name(blockQuote, "blockQuote"); -function hideLinkEmbed(url) { - return `<${url}>`; -} -__name(hideLinkEmbed, "hideLinkEmbed"); -function hyperlink(content, url, title) { - return title ? `[${content}](${url} "${title}")` : `[${content}](${url})`; -} -__name(hyperlink, "hyperlink"); -function spoiler(content) { - return `||${content}||`; -} -__name(spoiler, "spoiler"); -function userMention(userId) { - return `<@${userId}>`; -} -__name(userMention, "userMention"); -function channelMention(channelId) { - return `<#${channelId}>`; -} -__name(channelMention, "channelMention"); -function roleMention(roleId) { - return `<@&${roleId}>`; -} -__name(roleMention, "roleMention"); -function chatInputApplicationCommandMention(commandName, subcommandGroupName, subcommandName, commandId) { - if (typeof commandId !== "undefined") { - return ``; - } - if (typeof subcommandName !== "undefined") { - return ``; - } - return ``; -} -__name(chatInputApplicationCommandMention, "chatInputApplicationCommandMention"); -function formatEmoji(emojiId, animated = false) { - return `<${animated ? "a" : ""}:_:${emojiId}>`; -} -__name(formatEmoji, "formatEmoji"); -function channelLink(channelId, guildId) { - return `https://discord.com/channels/${guildId ?? "@me"}/${channelId}`; -} -__name(channelLink, "channelLink"); -function messageLink(channelId, messageId, guildId) { - return `${typeof guildId === "undefined" ? channelLink(channelId) : channelLink(channelId, guildId)}/${messageId}`; -} -__name(messageLink, "messageLink"); -function time(timeOrSeconds, style) { - if (typeof timeOrSeconds !== "number") { - timeOrSeconds = Math.floor((timeOrSeconds?.getTime() ?? Date.now()) / 1e3); - } - return typeof style === "string" ? `` : ``; -} -__name(time, "time"); -var TimestampStyles = { - ShortTime: "t", - LongTime: "T", - ShortDate: "d", - LongDate: "D", - ShortDateTime: "f", - LongDateTime: "F", - RelativeTime: "R" -}; -var Faces = /* @__PURE__ */ ((Faces2) => { - Faces2["Shrug"] = "\xAF\\_(\u30C4)\\_/\xAF"; - Faces2["Tableflip"] = "(\u256F\xB0\u25A1\xB0\uFF09\u256F\uFE35 \u253B\u2501\u253B"; - Faces2["Unflip"] = "\u252C\u2500\u252C \u30CE( \u309C-\u309C\u30CE)"; - return Faces2; -})(Faces || {}); +// src/index.ts +export * from "@discordjs/formatters"; // src/components/Assertions.ts var Assertions_exports2 = {}; @@ -319,29 +348,79 @@ import { ButtonStyle, ChannelType } from "discord-api-types/v10"; // src/components/selectMenu/StringSelectMenuOption.ts var StringSelectMenuOptionBuilder = class { + /** + * Creates a new string select menu option from API data. + * + * @param data - The API data to create this string select menu option with + * @example + * Creating a string select menu option from an API data object: + * ```ts + * const selectMenuOption = new SelectMenuOptionBuilder({ + * label: 'catchy label', + * value: '1', + * }); + * ``` + * @example + * Creating a string select menu option using setters and API data: + * ```ts + * const selectMenuOption = new SelectMenuOptionBuilder({ + * default: true, + * value: '1', + * }) + * .setLabel('woah'); + * ``` + */ constructor(data = {}) { this.data = data; } + /** + * Sets the label for this option. + * + * @param label - The label to use + */ setLabel(label) { this.data.label = labelValueDescriptionValidator.parse(label); return this; } + /** + * Sets the value for this option. + * + * @param value - The value to use + */ setValue(value) { this.data.value = labelValueDescriptionValidator.parse(value); return this; } + /** + * Sets the description for this option. + * + * @param description - The description to use + */ setDescription(description) { this.data.description = labelValueDescriptionValidator.parse(description); return this; } + /** + * Sets whether this option is selected by default. + * + * @param isDefault - Whether this option is selected by default + */ setDefault(isDefault = true) { this.data.default = defaultValidator.parse(isDefault); return this; } + /** + * Sets the emoji to display for this option. + * + * @param emoji - The emoji to use + */ setEmoji(emoji) { this.data.emoji = emojiValidator.parse(emoji); return this; } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ toJSON() { validateRequiredSelectMenuOptionParameters(this.data.label, this.data.value); return { @@ -413,7 +492,15 @@ import { // src/components/Component.ts var ComponentBuilder = class { + /** + * The API data associated with this component. + */ data; + /** + * Constructs a new kind of component. + * + * @param data - The data to construct a component out of + */ constructor(data) { this.data = data; } @@ -428,33 +515,99 @@ import { ComponentType } from "discord-api-types/v10"; var ButtonBuilder = class extends ComponentBuilder { + /** + * Creates a new button from API data. + * + * @param data - The API data to create this button with + * @example + * Creating a button from an API data object: + * ```ts + * const button = new ButtonBuilder({ + * custom_id: 'a cool button', + * style: ButtonStyle.Primary, + * label: 'Click Me', + * emoji: { + * name: 'smile', + * id: '123456789012345678', + * }, + * }); + * ``` + * @example + * Creating a button using setters and API data: + * ```ts + * const button = new ButtonBuilder({ + * style: ButtonStyle.Secondary, + * label: 'Click Me', + * }) + * .setEmoji({ name: 'πŸ™‚' }) + * .setCustomId('another cool button'); + * ``` + */ constructor(data) { super({ type: ComponentType.Button, ...data }); } + /** + * Sets the style of this button. + * + * @param style - The style to use + */ setStyle(style) { this.data.style = buttonStyleValidator.parse(style); return this; } + /** + * Sets the URL for this button. + * + * @remarks + * This method is only available to buttons using the `Link` button style. + * Only three types of URL schemes are currently supported: `https://`, `http://`, and `discord://`. + * @param url - The URL to use + */ setURL(url) { this.data.url = urlValidator.parse(url); return this; } + /** + * Sets the custom id for this button. + * + * @remarks + * This method is only applicable to buttons that are not using the `Link` button style. + * @param customId - The custom id to use + */ setCustomId(customId) { this.data.custom_id = customIdValidator.parse(customId); return this; } + /** + * Sets the emoji to display on this button. + * + * @param emoji - The emoji to use + */ setEmoji(emoji) { this.data.emoji = emojiValidator.parse(emoji); return this; } + /** + * Sets whether this button is disabled. + * + * @param disabled - Whether to disable this button + */ setDisabled(disabled = true) { this.data.disabled = disabledValidator.parse(disabled); return this; } + /** + * Sets the label for this button. + * + * @param label - The label to use + */ setLabel(label) { this.data.label = buttonLabelValidator.parse(label); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { validateRequiredButtonParameters( this.data.style, @@ -475,26 +628,54 @@ import { ComponentType as ComponentType2 } from "discord-api-types/v10"; // src/components/selectMenu/BaseSelectMenu.ts var BaseSelectMenuBuilder = class extends ComponentBuilder { + /** + * Sets the placeholder for this select menu. + * + * @param placeholder - The placeholder to use + */ setPlaceholder(placeholder) { this.data.placeholder = placeholderValidator.parse(placeholder); return this; } + /** + * Sets the minimum values that must be selected in the select menu. + * + * @param minValues - The minimum values that must be selected + */ setMinValues(minValues) { this.data.min_values = minMaxValidator.parse(minValues); return this; } + /** + * Sets the maximum values that must be selected in the select menu. + * + * @param maxValues - The maximum values that must be selected + */ setMaxValues(maxValues) { this.data.max_values = minMaxValidator.parse(maxValues); return this; } + /** + * Sets the custom id for this select menu. + * + * @param customId - The custom id to use + */ setCustomId(customId) { this.data.custom_id = customIdValidator.parse(customId); return this; } + /** + * Sets whether this select menu is disabled. + * + * @param disabled - Whether this select menu is disabled + */ setDisabled(disabled = true) { this.data.disabled = disabledValidator.parse(disabled); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { customIdValidator.parse(this.data.custom_id); return { @@ -506,21 +687,57 @@ __name(BaseSelectMenuBuilder, "BaseSelectMenuBuilder"); // src/components/selectMenu/ChannelSelectMenu.ts var ChannelSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new ChannelSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new ChannelSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement) + * .setMinValues(2); + * ``` + */ constructor(data) { super({ ...data, type: ComponentType2.ChannelSelect }); } + /** + * Adds channel types to this select menu. + * + * @param types - The channel types to use + */ addChannelTypes(...types) { - types = normalizeArray(types); + const normalizedTypes = normalizeArray(types); this.data.channel_types ??= []; - this.data.channel_types.push(...channelTypesValidator.parse(types)); + this.data.channel_types.push(...channelTypesValidator.parse(normalizedTypes)); return this; } + /** + * Sets channel types for this select menu. + * + * @param types - The channel types to use + */ setChannelTypes(...types) { - types = normalizeArray(types); + const normalizedTypes = normalizeArray(types); this.data.channel_types ??= []; - this.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(types)); + this.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(normalizedTypes)); return this; } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ toJSON() { customIdValidator.parse(this.data.custom_id); return { @@ -533,6 +750,28 @@ __name(ChannelSelectMenuBuilder, "ChannelSelectMenuBuilder"); // src/components/selectMenu/MentionableSelectMenu.ts import { ComponentType as ComponentType3 } from "discord-api-types/v10"; var MentionableSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new MentionableSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new MentionableSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ constructor(data) { super({ ...data, type: ComponentType3.MentionableSelect }); } @@ -542,6 +781,28 @@ __name(MentionableSelectMenuBuilder, "MentionableSelectMenuBuilder"); // src/components/selectMenu/RoleSelectMenu.ts import { ComponentType as ComponentType4 } from "discord-api-types/v10"; var RoleSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new RoleSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new RoleSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ constructor(data) { super({ ...data, type: ComponentType4.RoleSelect }); } @@ -551,34 +812,113 @@ __name(RoleSelectMenuBuilder, "RoleSelectMenuBuilder"); // src/components/selectMenu/StringSelectMenu.ts import { ComponentType as ComponentType5 } from "discord-api-types/v10"; var StringSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * The options within this select menu. + */ options; + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new StringSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * options: [ + * { label: 'option 1', value: '1' }, + * { label: 'option 2', value: '2' }, + * { label: 'option 3', value: '3' }, + * ], + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new StringSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1) + * .addOptions({ + * label: 'Catchy', + * value: 'catch', + * }); + * ``` + */ constructor(data) { const { options, ...initData } = data ?? {}; super({ ...initData, type: ComponentType5.StringSelect }); this.options = options?.map((option) => new StringSelectMenuOptionBuilder(option)) ?? []; } + /** + * Adds options to this select menu. + * + * @param options - The options to add + */ addOptions(...options) { - options = normalizeArray(options); - optionsLengthValidator.parse(this.options.length + options.length); + const normalizedOptions = normalizeArray(options); + optionsLengthValidator.parse(this.options.length + normalizedOptions.length); this.options.push( - ...options.map( - (option) => option instanceof StringSelectMenuOptionBuilder ? option : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)) + ...normalizedOptions.map( + (normalizedOption) => normalizedOption instanceof StringSelectMenuOptionBuilder ? normalizedOption : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)) ) ); return this; } + /** + * Sets the options for this select menu. + * + * @param options - The options to set + */ setOptions(...options) { - options = normalizeArray(options); - optionsLengthValidator.parse(options.length); - this.options.splice( - 0, - this.options.length, - ...options.map( - (option) => option instanceof StringSelectMenuOptionBuilder ? option : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)) + return this.spliceOptions(0, this.options.length, ...options); + } + /** + * Removes, replaces, or inserts options for this select menu. + * + * @remarks + * This method behaves similarly + * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice()}. + * It's useful for modifying and adjusting the order of existing options. + * @example + * Remove the first option: + * ```ts + * selectMenu.spliceOptions(0, 1); + * ``` + * @example + * Remove the first n option: + * ```ts + * const n = 4; + * selectMenu.spliceOptions(0, n); + * ``` + * @example + * Remove the last option: + * ```ts + * selectMenu.spliceOptions(-1, 1); + * ``` + * @param index - The index to start at + * @param deleteCount - The number of options to remove + * @param options - The replacing option objects or builders + */ + spliceOptions(index, deleteCount, ...options) { + const normalizedOptions = normalizeArray(options); + const clone = [...this.options]; + clone.splice( + index, + deleteCount, + ...normalizedOptions.map( + (normalizedOption) => normalizedOption instanceof StringSelectMenuOptionBuilder ? normalizedOption : new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)) ) ); + optionsLengthValidator.parse(clone.length); + this.options.splice(0, this.options.length, ...clone); return this; } + /** + * {@inheritDoc BaseSelectMenuBuilder.toJSON} + */ toJSON() { validateRequiredSelectMenuParameters(this.options, this.data.custom_id); return { @@ -592,6 +932,28 @@ __name(StringSelectMenuBuilder, "StringSelectMenuBuilder"); // src/components/selectMenu/UserSelectMenu.ts import { ComponentType as ComponentType6 } from "discord-api-types/v10"; var UserSelectMenuBuilder = class extends BaseSelectMenuBuilder { + /** + * Creates a new select menu from API data. + * + * @param data - The API data to create this select menu with + * @example + * Creating a select menu from an API data object: + * ```ts + * const selectMenu = new UserSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * placeholder: 'select an option', + * max_values: 2, + * }); + * ``` + * @example + * Creating a select menu using setters and API data: + * ```ts + * const selectMenu = new UserSelectMenuBuilder({ + * custom_id: 'a cool select menu', + * }) + * .setMinValues(1); + * ``` + */ constructor(data) { super({ ...data, type: ComponentType6.UserSelect }); } @@ -633,47 +995,116 @@ __name(validateRequiredParameters, "validateRequiredParameters"); // src/components/textInput/TextInput.ts var TextInputBuilder = class extends ComponentBuilder { + /** + * Creates a new text input from API data. + * + * @param data - The API data to create this text input with + * @example + * Creating a select menu option from an API data object: + * ```ts + * const textInput = new TextInputBuilder({ + * custom_id: 'a cool select menu', + * label: 'Type something', + * style: TextInputStyle.Short, + * }); + * ``` + * @example + * Creating a select menu option using setters and API data: + * ```ts + * const textInput = new TextInputBuilder({ + * label: 'Type something else', + * }) + * .setCustomId('woah') + * .setStyle(TextInputStyle.Paragraph); + * ``` + */ constructor(data) { super({ type: ComponentType7.TextInput, ...data }); } + /** + * Sets the custom id for this text input. + * + * @param customId - The custom id to use + */ setCustomId(customId) { this.data.custom_id = customIdValidator.parse(customId); return this; } + /** + * Sets the label for this text input. + * + * @param label - The label to use + */ setLabel(label) { this.data.label = labelValidator.parse(label); return this; } + /** + * Sets the style for this text input. + * + * @param style - The style to use + */ setStyle(style) { this.data.style = textInputStyleValidator.parse(style); return this; } + /** + * Sets the minimum length of text for this text input. + * + * @param minLength - The minimum length of text for this text input + */ setMinLength(minLength) { this.data.min_length = minLengthValidator.parse(minLength); return this; } + /** + * Sets the maximum length of text for this text input. + * + * @param maxLength - The maximum length of text for this text input + */ setMaxLength(maxLength) { this.data.max_length = maxLengthValidator.parse(maxLength); return this; } + /** + * Sets the placeholder for this text input. + * + * @param placeholder - The placeholder to use + */ setPlaceholder(placeholder) { this.data.placeholder = placeholderValidator2.parse(placeholder); return this; } + /** + * Sets the value for this text input. + * + * @param value - The value to use + */ setValue(value) { this.data.value = valueValidator.parse(value); return this; } + /** + * Sets whether this text input is required. + * + * @param required - Whether this text input is required + */ setRequired(required = true) { this.data.required = requiredValidator.parse(required); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { validateRequiredParameters(this.data.custom_id, this.data.style, this.data.label); return { ...this.data }; } + /** + * {@inheritDoc Equatable.equals} + */ equals(other) { if (isJSONEncodable(other)) { return isEqual(other.toJSON(), this.data); @@ -713,19 +1144,69 @@ __name(createComponentBuilder, "createComponentBuilder"); // src/components/ActionRow.ts var ActionRowBuilder = class extends ComponentBuilder { + /** + * The components within this action row. + */ components; + /** + * Creates a new action row from API data. + * + * @param data - The API data to create this action row with + * @example + * Creating an action row from an API data object: + * ```ts + * const actionRow = new ActionRowBuilder({ + * components: [ + * { + * custom_id: "custom id", + * label: "Type something", + * style: TextInputStyle.Short, + * type: ComponentType.TextInput, + * }, + * ], + * }); + * ``` + * @example + * Creating an action row using setters and API data: + * ```ts + * const actionRow = new ActionRowBuilder({ + * components: [ + * { + * custom_id: "custom id", + * label: "Click me", + * style: ButtonStyle.Primary, + * type: ComponentType.Button, + * }, + * ], + * }) + * .addComponents(button2, button3); + * ``` + */ constructor({ components, ...data } = {}) { super({ type: ComponentType9.ActionRow, ...data }); this.components = components?.map((component) => createComponentBuilder(component)) ?? []; } + /** + * Adds components to this action row. + * + * @param components - The components to add + */ addComponents(...components) { this.components.push(...normalizeArray(components)); return this; } + /** + * Sets components for this action row. + * + * @param components - The components to set + */ setComponents(...components) { this.components.splice(0, this.components.length, ...normalizeArray(components)); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { return { ...this.data, @@ -754,20 +1235,46 @@ __name(validateRequiredParameters2, "validateRequiredParameters"); // src/interactions/modals/Modal.ts var ModalBuilder = class { + /** + * The API data associated with this modal. + */ data; + /** + * The components within this modal. + */ components = []; + /** + * Creates a new modal from API data. + * + * @param data - The API data to create this modal with + */ constructor({ components, ...data } = {}) { this.data = { ...data }; this.components = components?.map((component) => createComponentBuilder(component)) ?? []; } + /** + * Sets the title of this modal. + * + * @param title - The title to use + */ setTitle(title) { this.data.title = titleValidator.parse(title); return this; } + /** + * Sets the custom id of this modal. + * + * @param customId - The custom id to use + */ setCustomId(customId) { this.data.custom_id = customIdValidator.parse(customId); return this; } + /** + * Adds components to this modal. + * + * @param components - The components to add + */ addComponents(...components) { this.components.push( ...normalizeArray(components).map( @@ -776,10 +1283,18 @@ var ModalBuilder = class { ); return this; } + /** + * Sets components for this modal. + * + * @param components - The components to set + */ setComponents(...components) { this.components.splice(0, this.components.length, ...normalizeArray(components)); return this; } + /** + * {@inheritDoc ComponentBuilder.toJSON} + */ toJSON() { validateRequiredParameters2(this.data.custom_id, this.data.title, this.components); return { @@ -803,6 +1318,7 @@ __export(Assertions_exports5, { validateLocale: () => validateLocale, validateLocalizationMap: () => validateLocalizationMap, validateMaxOptionsLength: () => validateMaxOptionsLength, + validateNSFW: () => validateNSFW, validateName: () => validateName, validateRequired: () => validateRequired, validateRequiredParameters: () => validateRequiredParameters3 @@ -872,6 +1388,10 @@ function validateDefaultMemberPermissions(permissions) { return memberPermissionPredicate.parse(permissions); } __name(validateDefaultMemberPermissions, "validateDefaultMemberPermissions"); +function validateNSFW(value) { + booleanPredicate.parse(value); +} +__name(validateNSFW, "validateNSFW"); // src/interactions/slashCommands/SlashCommandBuilder.ts import { mix as mix6 } from "ts-mixer"; @@ -884,20 +1404,48 @@ import { mix as mix5 } from "ts-mixer"; // src/interactions/slashCommands/mixins/NameAndDescription.ts var SharedNameAndDescription = class { + /** + * The name of this command. + */ name; + /** + * The name localizations of this command. + */ name_localizations; + /** + * The description of this command. + */ description; + /** + * The description localizations of this command. + */ description_localizations; + /** + * Sets the name of this command. + * + * @param name - The name to use + */ setName(name) { validateName(name); Reflect.set(this, "name", name); return this; } + /** + * Sets the description of this command. + * + * @param description - The description to use + */ setDescription(description) { validateDescription(description); Reflect.set(this, "description", description); return this; } + /** + * SSets a name localization for this command. + * + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` + */ setNameLocalization(locale, localizedName) { if (!this.name_localizations) { Reflect.set(this, "name_localizations", {}); @@ -911,6 +1459,11 @@ var SharedNameAndDescription = class { this.name_localizations[parsedLocale] = localizedName; return this; } + /** + * Sets the name localizations for this command. + * + * @param localizedNames - The object of localized names to set + */ setNameLocalizations(localizedNames) { if (localizedNames === null) { Reflect.set(this, "name_localizations", null); @@ -922,6 +1475,12 @@ var SharedNameAndDescription = class { } return this; } + /** + * Sets a description localization for this command. + * + * @param locale - The locale to set + * @param localizedDescription - The localized description for the given locale + */ setDescriptionLocalization(locale, localizedDescription) { if (!this.description_localizations) { Reflect.set(this, "description_localizations", {}); @@ -935,6 +1494,11 @@ var SharedNameAndDescription = class { this.description_localizations[parsedLocale] = localizedDescription; return this; } + /** + * Sets the description localizations for this command. + * + * @param localizedDescriptions - The object of localized descriptions to set + */ setDescriptionLocalizations(localizedDescriptions) { if (localizedDescriptions === null) { Reflect.set(this, "description_localizations", null); @@ -954,12 +1518,25 @@ import { ApplicationCommandOptionType } from "discord-api-types/v10"; // src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts var ApplicationCommandOptionBase = class extends SharedNameAndDescription { + /** + * Whether this option is required. + * + * @defaultValue `false` + */ required = false; + /** + * Sets whether this option is required. + * + * @param required - Whether this option should be required + */ setRequired(required) { validateRequired(required); Reflect.set(this, "required", required); return this; } + /** + * This method runs required validators on this builder. + */ runRequiredValidations() { validateRequiredParameters3(this.name, this.description, []); validateLocalizationMap(this.name_localizations); @@ -971,7 +1548,13 @@ __name(ApplicationCommandOptionBase, "ApplicationCommandOptionBase"); // src/interactions/slashCommands/options/attachment.ts var SlashCommandAttachmentOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType.Attachment; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -982,7 +1565,13 @@ __name(SlashCommandAttachmentOption, "SlashCommandAttachmentOption"); // src/interactions/slashCommands/options/boolean.ts import { ApplicationCommandOptionType as ApplicationCommandOptionType2 } from "discord-api-types/v10"; var SlashCommandBooleanOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType2.Boolean; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1010,7 +1599,15 @@ var allowedChannelTypes = [ ]; var channelTypesPredicate = s6.array(s6.union(...allowedChannelTypes.map((type) => s6.literal(type)))); var ApplicationCommandOptionChannelTypesMixin = class { + /** + * The channel types of this option. + */ channel_types; + /** + * Adds channel types to this option. + * + * @param channelTypes - The channel types + */ addChannelTypes(...channelTypes) { if (this.channel_types === void 0) { Reflect.set(this, "channel_types", []); @@ -1023,7 +1620,13 @@ __name(ApplicationCommandOptionChannelTypesMixin, "ApplicationCommandOptionChann // src/interactions/slashCommands/options/channel.ts var SlashCommandChannelOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType3.Channel; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1041,7 +1644,13 @@ import { mix as mix2 } from "ts-mixer"; // src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts var ApplicationCommandNumericOptionMinMaxValueMixin = class { + /** + * The maximum value of this option. + */ max_value; + /** + * The minimum value of this option. + */ min_value; }; __name(ApplicationCommandNumericOptionMinMaxValueMixin, "ApplicationCommandNumericOptionMinMaxValueMixin"); @@ -1058,9 +1667,25 @@ var choicesPredicate = s7.object({ }).array; var booleanPredicate2 = s7.boolean; var ApplicationCommandOptionWithChoicesAndAutocompleteMixin = class { + /** + * The choices of this option. + */ choices; + /** + * Whether this option utilizes autocomplete. + */ autocomplete; + /** + * The type of this option. + * + * @privateRemarks Since this is present and this is a mixin, this is needed. + */ type; + /** + * Adds multiple choices to this option. + * + * @param choices - The choices to add + */ addChoices(...choices) { if (choices.length > 0 && this.autocomplete) { throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); @@ -1080,6 +1705,11 @@ var ApplicationCommandOptionWithChoicesAndAutocompleteMixin = class { } return this; } + /** + * Sets multiple choices for this option. + * + * @param choices - The choices to set + */ setChoices(...choices) { if (choices.length > 0 && this.autocomplete) { throw new RangeError("Autocomplete and choices are mutually exclusive to each other."); @@ -1089,6 +1719,11 @@ var ApplicationCommandOptionWithChoicesAndAutocompleteMixin = class { this.addChoices(...choices); return this; } + /** + * Whether this option uses autocomplete. + * + * @param autocomplete - Whether this option should use autocomplete + */ setAutocomplete(autocomplete) { booleanPredicate2.parse(autocomplete); if (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { @@ -1103,17 +1738,29 @@ __name(ApplicationCommandOptionWithChoicesAndAutocompleteMixin, "ApplicationComm // src/interactions/slashCommands/options/integer.ts var numberValidator = s8.number.int; var SlashCommandIntegerOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType5.Integer; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ setMaxValue(max) { numberValidator.parse(max); Reflect.set(this, "max_value", max); return this; } + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ setMinValue(min) { numberValidator.parse(min); Reflect.set(this, "min_value", min); return this; } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { @@ -1130,7 +1777,13 @@ SlashCommandIntegerOption = __decorateClass([ // src/interactions/slashCommands/options/mentionable.ts import { ApplicationCommandOptionType as ApplicationCommandOptionType6 } from "discord-api-types/v10"; var SlashCommandMentionableOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType6.Mentionable; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1144,17 +1797,29 @@ import { ApplicationCommandOptionType as ApplicationCommandOptionType7 } from "d import { mix as mix3 } from "ts-mixer"; var numberValidator2 = s9.number; var SlashCommandNumberOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType7.Number; + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue} + */ setMaxValue(max) { numberValidator2.parse(max); Reflect.set(this, "max_value", max); return this; } + /** + * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue} + */ setMinValue(min) { numberValidator2.parse(min); Reflect.set(this, "min_value", min); return this; } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { @@ -1171,7 +1836,13 @@ SlashCommandNumberOption = __decorateClass([ // src/interactions/slashCommands/options/role.ts import { ApplicationCommandOptionType as ApplicationCommandOptionType8 } from "discord-api-types/v10"; var SlashCommandRoleOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType8.Role; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1186,19 +1857,41 @@ import { mix as mix4 } from "ts-mixer"; var minLengthValidator2 = s10.number.greaterThanOrEqual(0).lessThanOrEqual(6e3); var maxLengthValidator2 = s10.number.greaterThanOrEqual(1).lessThanOrEqual(6e3); var SlashCommandStringOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType9.String; + /** + * The maximum length of this option. + */ max_length; + /** + * The minimum length of this option. + */ min_length; + /** + * Sets the maximum length of this string option. + * + * @param max - The maximum length this option can be + */ setMaxLength(max) { maxLengthValidator2.parse(max); Reflect.set(this, "max_length", max); return this; } + /** + * Sets the minimum length of this string option. + * + * @param min - The minimum length this option can be + */ setMinLength(min) { minLengthValidator2.parse(min); Reflect.set(this, "min_length", min); return this; } + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); if (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) { @@ -1215,7 +1908,13 @@ SlashCommandStringOption = __decorateClass([ // src/interactions/slashCommands/options/user.ts import { ApplicationCommandOptionType as ApplicationCommandOptionType10 } from "discord-api-types/v10"; var SlashCommandUserOption = class extends ApplicationCommandOptionBase { + /** + * The type of this option. + */ type = ApplicationCommandOptionType10.User; + /** + * {@inheritDoc ApplicationCommandOptionBase.toJSON} + */ toJSON() { this.runRequiredValidations(); return { ...this }; @@ -1226,33 +1925,85 @@ __name(SlashCommandUserOption, "SlashCommandUserOption"); // src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts var SharedSlashCommandOptions = class { options; + /** + * Adds a boolean option. + * + * @param input - A function that returns an option builder or an already built builder + */ addBooleanOption(input) { return this._sharedAddOptionMethod(input, SlashCommandBooleanOption); } + /** + * Adds a user option. + * + * @param input - A function that returns an option builder or an already built builder + */ addUserOption(input) { return this._sharedAddOptionMethod(input, SlashCommandUserOption); } + /** + * Adds a channel option. + * + * @param input - A function that returns an option builder or an already built builder + */ addChannelOption(input) { return this._sharedAddOptionMethod(input, SlashCommandChannelOption); } + /** + * Adds a role option. + * + * @param input - A function that returns an option builder or an already built builder + */ addRoleOption(input) { return this._sharedAddOptionMethod(input, SlashCommandRoleOption); } + /** + * Adds an attachment option. + * + * @param input - A function that returns an option builder or an already built builder + */ addAttachmentOption(input) { return this._sharedAddOptionMethod(input, SlashCommandAttachmentOption); } + /** + * Adds a mentionable option. + * + * @param input - A function that returns an option builder or an already built builder + */ addMentionableOption(input) { return this._sharedAddOptionMethod(input, SlashCommandMentionableOption); } + /** + * Adds a string option. + * + * @param input - A function that returns an option builder or an already built builder + */ addStringOption(input) { return this._sharedAddOptionMethod(input, SlashCommandStringOption); } + /** + * Adds an integer option. + * + * @param input - A function that returns an option builder or an already built builder + */ addIntegerOption(input) { return this._sharedAddOptionMethod(input, SlashCommandIntegerOption); } + /** + * Adds a number option. + * + * @param input - A function that returns an option builder or an already built builder + */ addNumberOption(input) { return this._sharedAddOptionMethod(input, SlashCommandNumberOption); } + /** + * Where the actual adding magic happens. ✨ + * + * @param input - The input. What else? + * @param Instance - The instance of whatever is being added + * @internal + */ _sharedAddOptionMethod(input, Instance) { const { options } = this; validateMaxOptionsLength(options); @@ -1266,9 +2017,23 @@ __name(SharedSlashCommandOptions, "SharedSlashCommandOptions"); // src/interactions/slashCommands/SlashCommandSubcommands.ts var SlashCommandSubcommandGroupBuilder = class { + /** + * The name of this subcommand group. + */ name = void 0; + /** + * The description of this subcommand group. + */ description = void 0; + /** + * The subcommands within this subcommand group. + */ options = []; + /** + * Adds a new subcommand to this group. + * + * @param input - A function that returns a subcommand builder or an already built builder + */ addSubcommand(input) { const { options } = this; validateMaxOptionsLength(options); @@ -1277,6 +2042,13 @@ var SlashCommandSubcommandGroupBuilder = class { options.push(result); return this; } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON() { validateRequiredParameters3(this.name, this.description, this.options); return { @@ -1294,9 +2066,25 @@ SlashCommandSubcommandGroupBuilder = __decorateClass([ mix5(SharedNameAndDescription) ], SlashCommandSubcommandGroupBuilder); var SlashCommandSubcommandBuilder = class { + /** + * The name of this subcommand. + */ name = void 0; + /** + * The description of this subcommand. + */ description = void 0; + /** + * The options within this subcommand. + */ options = []; + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON() { validateRequiredParameters3(this.name, this.description, this.options); return { @@ -1316,38 +2104,102 @@ SlashCommandSubcommandBuilder = __decorateClass([ // src/interactions/slashCommands/SlashCommandBuilder.ts var SlashCommandBuilder = class { + /** + * The name of this command. + */ name = void 0; + /** + * The name localizations of this command. + */ name_localizations; + /** + * The description of this command. + */ description = void 0; + /** + * The description localizations of this command. + */ description_localizations; + /** + * The options of this command. + */ options = []; + /** + * Whether this command is enabled by default when the application is added to a guild. + * + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ default_permission = void 0; + /** + * The set of permissions represented as a bit set for the command. + */ default_member_permissions = void 0; + /** + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. + */ dm_permission = void 0; - toJSON() { - validateRequiredParameters3(this.name, this.description, this.options); - validateLocalizationMap(this.name_localizations); - validateLocalizationMap(this.description_localizations); - return { - ...this, - options: this.options.map((option) => option.toJSON()) - }; - } + /** + * Whether this command is NSFW. + */ + nsfw = void 0; + /** + * Sets whether the command is enabled by default when the application is added to a guild. + * + * @remarks + * If set to `false`, you will have to later `PUT` the permissions for this command. + * @param value - Whether or not to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link SlashCommandBuilder.setDefaultMemberPermissions} or {@link SlashCommandBuilder.setDMPermission} instead. + */ setDefaultPermission(value) { validateDefaultPermission(value); Reflect.set(this, "default_permission", value); return this; } + /** + * Sets the default permissions a member should have in order to run the command. + * + * @remarks + * You can set this to `'0'` to disable the command by default. + * @param permissions - The permissions bit field to set + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ setDefaultMemberPermissions(permissions) { const permissionValue = validateDefaultMemberPermissions(permissions); Reflect.set(this, "default_member_permissions", permissionValue); return this; } + /** + * Sets if the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ setDMPermission(enabled) { validateDMPermission(enabled); Reflect.set(this, "dm_permission", enabled); return this; } + /** + * Sets whether this command is NSFW. + * + * @param nsfw - Whether this command is NSFW + */ + setNSFW(nsfw = true) { + validateNSFW(nsfw); + Reflect.set(this, "nsfw", nsfw); + return this; + } + /** + * Adds a new subcommand group to this command. + * + * @param input - A function that returns a subcommand group builder or an already built builder + */ addSubcommandGroup(input) { const { options } = this; validateMaxOptionsLength(options); @@ -1356,6 +2208,11 @@ var SlashCommandBuilder = class { options.push(result); return this; } + /** + * Adds a new subcommand to this command. + * + * @param input - A function that returns a subcommand builder or an already built builder + */ addSubcommand(input) { const { options } = this; validateMaxOptionsLength(options); @@ -1364,6 +2221,22 @@ var SlashCommandBuilder = class { options.push(result); return this; } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ + toJSON() { + validateRequiredParameters3(this.name, this.description, this.options); + validateLocalizationMap(this.name_localizations); + validateLocalizationMap(this.description_localizations); + return { + ...this, + options: this.options.map((option) => option.toJSON()) + }; + } }; __name(SlashCommandBuilder, "SlashCommandBuilder"); SlashCommandBuilder = __decorateClass([ @@ -1419,37 +2292,101 @@ __name(validateDefaultMemberPermissions2, "validateDefaultMemberPermissions"); // src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts var ContextMenuCommandBuilder = class { + /** + * The name of this command. + */ name = void 0; + /** + * The name localizations of this command. + */ name_localizations; + /** + * The type of this command. + */ type = void 0; + /** + * Whether this command is enabled by default when the application is added to a guild. + * + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ default_permission = void 0; + /** + * The set of permissions represented as a bit set for the command. + */ default_member_permissions = void 0; + /** + * Indicates whether the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This property is only for global commands. + */ dm_permission = void 0; + /** + * Sets the name of this command. + * + * @param name - The name to use + */ setName(name) { validateName2(name); Reflect.set(this, "name", name); return this; } + /** + * Sets the type of this command. + * + * @param type - The type to use + */ setType(type) { validateType(type); Reflect.set(this, "type", type); return this; } + /** + * Sets whether the command is enabled by default when the application is added to a guild. + * + * @remarks + * If set to `false`, you will have to later `PUT` the permissions for this command. + * @param value - Whether to enable this command by default + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead. + */ setDefaultPermission(value) { validateDefaultPermission2(value); Reflect.set(this, "default_permission", value); return this; } + /** + * Sets the default permissions a member should have in order to run this command. + * + * @remarks + * You can set this to `'0'` to disable the command by default. + * @param permissions - The permissions bit field to set + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ setDefaultMemberPermissions(permissions) { const permissionValue = validateDefaultMemberPermissions2(permissions); Reflect.set(this, "default_member_permissions", permissionValue); return this; } + /** + * Sets if the command is available in direct messages with the application. + * + * @remarks + * By default, commands are visible. This method is only for global commands. + * @param enabled - Whether the command should be enabled in direct messages + * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions} + */ setDMPermission(enabled) { validateDMPermission2(enabled); Reflect.set(this, "dm_permission", enabled); return this; } + /** + * Sets a name localization for this command. + * + * @param locale - The locale to set + * @param localizedName - The localized name for the given `locale` + */ setNameLocalization(locale, localizedName) { if (!this.name_localizations) { Reflect.set(this, "name_localizations", {}); @@ -1463,6 +2400,11 @@ var ContextMenuCommandBuilder = class { this.name_localizations[parsedLocale] = localizedName; return this; } + /** + * Sets the name localizations for this command. + * + * @param localizedNames - The object of localized names to set + */ setNameLocalizations(localizedNames) { if (localizedNames === null) { Reflect.set(this, "name_localizations", null); @@ -1473,6 +2415,13 @@ var ContextMenuCommandBuilder = class { this.setNameLocalization(...args); return this; } + /** + * Serializes this builder to API-compatible JSON data. + * + * @remarks + * This method runs validations on the data before serializing it. + * As such, it may throw an error if the data is invalid. + */ toJSON() { validateRequiredParameters4(this.name, this.type); validateLocalizationMap(this.name_localizations); @@ -1488,8 +2437,7 @@ function embedLength(data) { __name(embedLength, "embedLength"); // src/index.ts -export * from "@discordjs/util"; -var version = "1.4.0"; +var version = "1.6.3"; export { ActionRowBuilder, ApplicationCommandNumericOptionMinMaxValueMixin, @@ -1505,7 +2453,6 @@ export { ContextMenuCommandBuilder, Assertions_exports as EmbedAssertions, EmbedBuilder, - Faces, MentionableSelectMenuBuilder, Assertions_exports4 as ModalAssertions, ModalBuilder, @@ -1531,33 +2478,13 @@ export { StringSelectMenuOptionBuilder, Assertions_exports3 as TextInputAssertions, TextInputBuilder, - TimestampStyles, UserSelectMenuBuilder, - blockQuote, - bold, - channelLink, - channelMention, - chatInputApplicationCommandMention, - codeBlock, createComponentBuilder, disableValidators, embedLength, enableValidators, - formatEmoji, - hideLinkEmbed, - hyperlink, - inlineCode, isValidationEnabled, - italic, - messageLink, normalizeArray, - quote, - roleMention, - spoiler, - strikethrough, - time, - underscore, - userMention, version }; //# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@discordjs/builders/dist/index.mjs.map b/node_modules/@discordjs/builders/dist/index.mjs.map index 49ec254..38013f8 100644 --- a/node_modules/@discordjs/builders/dist/index.mjs.map +++ b/node_modules/@discordjs/builders/dist/index.mjs.map @@ -1 +1 @@ -{"version":3,"sources":["../src/messages/embed/Assertions.ts","../src/util/validation.ts","../src/util/normalizeArray.ts","../src/messages/embed/Embed.ts","../src/messages/formatters.ts","../src/components/Assertions.ts","../src/components/selectMenu/StringSelectMenuOption.ts","../src/components/ActionRow.ts","../src/components/Component.ts","../src/components/Components.ts","../src/components/button/Button.ts","../src/components/selectMenu/ChannelSelectMenu.ts","../src/components/selectMenu/BaseSelectMenu.ts","../src/components/selectMenu/MentionableSelectMenu.ts","../src/components/selectMenu/RoleSelectMenu.ts","../src/components/selectMenu/StringSelectMenu.ts","../src/components/selectMenu/UserSelectMenu.ts","../src/components/textInput/TextInput.ts","../src/components/textInput/Assertions.ts","../src/interactions/modals/Assertions.ts","../src/interactions/modals/Modal.ts","../src/interactions/slashCommands/Assertions.ts","../src/interactions/slashCommands/SlashCommandBuilder.ts","../src/interactions/slashCommands/SlashCommandSubcommands.ts","../src/interactions/slashCommands/mixins/NameAndDescription.ts","../src/interactions/slashCommands/options/attachment.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts","../src/interactions/slashCommands/options/boolean.ts","../src/interactions/slashCommands/options/channel.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.ts","../src/interactions/slashCommands/options/integer.ts","../src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.ts","../src/interactions/slashCommands/options/mentionable.ts","../src/interactions/slashCommands/options/number.ts","../src/interactions/slashCommands/options/role.ts","../src/interactions/slashCommands/options/string.ts","../src/interactions/slashCommands/options/user.ts","../src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts","../src/interactions/contextMenuCommands/Assertions.ts","../src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts","../src/util/componentUtil.ts","../src/index.ts"],"sourcesContent":["import { s } from '@sapphire/shapeshift';\nimport type { APIEmbedField } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const fieldNamePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(256)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldValuePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(1_024)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldInlinePredicate = s.boolean.optional;\n\nexport const embedFieldPredicate = s\n\t.object({\n\t\tname: fieldNamePredicate,\n\t\tvalue: fieldValuePredicate,\n\t\tinline: fieldInlinePredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const embedFieldsArrayPredicate = embedFieldPredicate.array.setValidationEnabled(isValidationEnabled);\n\nexport const fieldLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateFieldLength(amountAdding: number, fields?: APIEmbedField[]): void {\n\tfieldLengthPredicate.parse((fields?.length ?? 0) + amountAdding);\n}\n\nexport const authorNamePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const imageURLPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'attachment:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const urlPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const embedAuthorPredicate = s\n\t.object({\n\t\tname: authorNamePredicate,\n\t\ticonURL: imageURLPredicate,\n\t\turl: urlPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const RGBPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(255)\n\t.setValidationEnabled(isValidationEnabled);\nexport const colorPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(0xffffff)\n\t.or(s.tuple([RGBPredicate, RGBPredicate, RGBPredicate]))\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(4_096)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const footerTextPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(2_048)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const embedFooterPredicate = s\n\t.object({\n\t\ttext: footerTextPredicate,\n\t\ticonURL: imageURLPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const timestampPredicate = s.union(s.number, s.date).nullable.setValidationEnabled(isValidationEnabled);\n\nexport const titlePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n","let validate = true;\n\nexport const enableValidators = () => (validate = true);\nexport const disableValidators = () => (validate = false);\nexport const isValidationEnabled = () => validate;\n","export function normalizeArray(arr: RestOrArray): T[] {\n\tif (Array.isArray(arr[0])) return arr[0];\n\treturn arr as T[];\n}\n\nexport type RestOrArray = T[] | [T[]];\n","import type { APIEmbed, APIEmbedAuthor, APIEmbedField, APIEmbedFooter, APIEmbedImage } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport {\n\tcolorPredicate,\n\tdescriptionPredicate,\n\tembedAuthorPredicate,\n\tembedFieldsArrayPredicate,\n\tembedFooterPredicate,\n\timageURLPredicate,\n\ttimestampPredicate,\n\ttitlePredicate,\n\turlPredicate,\n\tvalidateFieldLength,\n} from './Assertions.js';\n\nexport type RGBTuple = [red: number, green: number, blue: number];\n\nexport interface IconData {\n\t/**\n\t * The URL of the icon\n\t */\n\ticonURL?: string;\n\t/**\n\t * The proxy URL of the icon\n\t */\n\tproxyIconURL?: string;\n}\n\nexport type EmbedAuthorData = IconData & Omit;\n\nexport type EmbedAuthorOptions = Omit;\n\nexport type EmbedFooterData = IconData & Omit;\n\nexport type EmbedFooterOptions = Omit;\n\nexport interface EmbedImageData extends Omit {\n\t/**\n\t * The proxy URL for the image\n\t */\n\tproxyURL?: string;\n}\n/**\n * Represents a embed in a message (image/video preview, rich embed, etc.)\n */\nexport class EmbedBuilder {\n\tpublic readonly data: APIEmbed;\n\n\tpublic constructor(data: APIEmbed = {}) {\n\t\tthis.data = { ...data };\n\t\tif (data.timestamp) this.data.timestamp = new Date(data.timestamp).toISOString();\n\t}\n\n\t/**\n\t * Appends fields to the embed\n\t *\n\t * @remarks\n\t * This method accepts either an array of fields or a variable number of field parameters.\n\t * The maximum amount of fields that can be added is 25.\n\t * @example\n\t * Using an array\n\t * ```ts\n\t * const fields: APIEmbedField[] = ...;\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(fields);\n\t * ```\n\t * @example\n\t * Using rest parameters (variadic)\n\t * ```ts\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(\n\t * \t\t{ name: 'Field 1', value: 'Value 1' },\n\t * \t\t{ name: 'Field 2', value: 'Value 2' },\n\t * \t);\n\t * ```\n\t * @param fields - The fields to add\n\t */\n\tpublic addFields(...fields: RestOrArray): this {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\tfields = normalizeArray(fields);\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(fields.length, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(fields);\n\n\t\tif (this.data.fields) this.data.fields.push(...fields);\n\t\telse this.data.fields = fields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts fields in the embed.\n\t *\n\t * @remarks\n\t * This method behaves similarly\n\t * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice}.\n\t * The maximum amount of fields that can be added is 25.\n\t *\n\t * It's useful for modifying and adjusting order of the already-existing fields of an embed.\n\t * @example\n\t * Remove the first field\n\t * ```ts\n\t * embed.spliceFields(0, 1);\n\t * ```\n\t * @example\n\t * Remove the first n fields\n\t * ```ts\n\t * const n = 4\n\t * embed.spliceFields(0, n);\n\t * ```\n\t * @example\n\t * Remove the last field\n\t * ```ts\n\t * embed.spliceFields(-1, 1);\n\t * ```\n\t * @param index - The index to start at\n\t * @param deleteCount - The number of fields to remove\n\t * @param fields - The replacing field objects\n\t */\n\tpublic spliceFields(index: number, deleteCount: number, ...fields: APIEmbedField[]): this {\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(fields.length - deleteCount, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(fields);\n\t\tif (this.data.fields) this.data.fields.splice(index, deleteCount, ...fields);\n\t\telse this.data.fields = fields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the embed's fields\n\t *\n\t * @remarks\n\t * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically,\n\t * it splices the entire array of fields, replacing them with the provided fields.\n\t *\n\t * You can set a maximum of 25 fields.\n\t * @param fields - The fields to set\n\t */\n\tpublic setFields(...fields: RestOrArray) {\n\t\tthis.spliceFields(0, this.data.fields?.length ?? 0, ...normalizeArray(fields));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the author of this embed\n\t *\n\t * @param options - The options for the author\n\t */\n\n\tpublic setAuthor(options: EmbedAuthorOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.author = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedAuthorPredicate.parse(options);\n\n\t\tthis.data.author = { name: options.name, url: options.url, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the color of this embed\n\t *\n\t * @param color - The color of the embed\n\t */\n\tpublic setColor(color: RGBTuple | number | null): this {\n\t\t// Data assertions\n\t\tcolorPredicate.parse(color);\n\n\t\tif (Array.isArray(color)) {\n\t\t\tconst [red, green, blue] = color;\n\t\t\tthis.data.color = (red << 16) + (green << 8) + blue;\n\t\t\treturn this;\n\t\t}\n\n\t\tthis.data.color = color ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this embed\n\t *\n\t * @param description - The description\n\t */\n\tpublic setDescription(description: string | null): this {\n\t\t// Data assertions\n\t\tdescriptionPredicate.parse(description);\n\n\t\tthis.data.description = description ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the footer of this embed\n\t *\n\t * @param options - The options for the footer\n\t */\n\tpublic setFooter(options: EmbedFooterOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.footer = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedFooterPredicate.parse(options);\n\n\t\tthis.data.footer = { text: options.text, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the image of this embed\n\t *\n\t * @param url - The URL of the image\n\t */\n\tpublic setImage(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.image = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the thumbnail of this embed\n\t *\n\t * @param url - The URL of the thumbnail\n\t */\n\tpublic setThumbnail(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.thumbnail = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the timestamp of this embed\n\t *\n\t * @param timestamp - The timestamp or date\n\t */\n\tpublic setTimestamp(timestamp: Date | number | null = Date.now()): this {\n\t\t// Data assertions\n\t\ttimestampPredicate.parse(timestamp);\n\n\t\tthis.data.timestamp = timestamp ? new Date(timestamp).toISOString() : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the title of this embed\n\t *\n\t * @param title - The title\n\t */\n\tpublic setTitle(title: string | null): this {\n\t\t// Data assertions\n\t\ttitlePredicate.parse(title);\n\n\t\tthis.data.title = title ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL of this embed\n\t *\n\t * @param url - The URL\n\t */\n\tpublic setURL(url: string | null): this {\n\t\t// Data assertions\n\t\turlPredicate.parse(url);\n\n\t\tthis.data.url = url ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Transforms the embed to a plain object\n\t */\n\tpublic toJSON(): APIEmbed {\n\t\treturn { ...this.data };\n\t}\n}\n","import type { URL } from 'node:url';\nimport type { Snowflake } from 'discord-api-types/globals';\n\n/**\n * Wraps the content inside a codeblock with no language\n *\n * @param content - The content to wrap\n */\nexport function codeBlock(content: C): `\\`\\`\\`\\n${C}\\n\\`\\`\\``;\n\n/**\n * Wraps the content inside a codeblock with the specified language\n *\n * @param language - The language for the codeblock\n * @param content - The content to wrap\n */\nexport function codeBlock(language: L, content: C): `\\`\\`\\`${L}\\n${C}\\n\\`\\`\\``;\nexport function codeBlock(language: string, content?: string): string {\n\treturn typeof content === 'undefined' ? `\\`\\`\\`\\n${language}\\n\\`\\`\\`` : `\\`\\`\\`${language}\\n${content}\\n\\`\\`\\``;\n}\n\n/**\n * Wraps the content inside \\`backticks\\`, which formats it as inline code\n *\n * @param content - The content to wrap\n */\nexport function inlineCode(content: C): `\\`${C}\\`` {\n\treturn `\\`${content}\\``;\n}\n\n/**\n * Formats the content into italic text\n *\n * @param content - The content to wrap\n */\nexport function italic(content: C): `_${C}_` {\n\treturn `_${content}_`;\n}\n\n/**\n * Formats the content into bold text\n *\n * @param content - The content to wrap\n */\nexport function bold(content: C): `**${C}**` {\n\treturn `**${content}**`;\n}\n\n/**\n * Formats the content into underscored text\n *\n * @param content - The content to wrap\n */\nexport function underscore(content: C): `__${C}__` {\n\treturn `__${content}__`;\n}\n\n/**\n * Formats the content into strike-through text\n *\n * @param content - The content to wrap\n */\nexport function strikethrough(content: C): `~~${C}~~` {\n\treturn `~~${content}~~`;\n}\n\n/**\n * Formats the content into a quote. This needs to be at the start of the line for Discord to format it\n *\n * @param content - The content to wrap\n */\nexport function quote(content: C): `> ${C}` {\n\treturn `> ${content}`;\n}\n\n/**\n * Formats the content into a block quote. This needs to be at the start of the line for Discord to format it\n *\n * @param content - The content to wrap\n */\nexport function blockQuote(content: C): `>>> ${C}` {\n\treturn `>>> ${content}`;\n}\n\n/**\n * Wraps the URL into `<>`, which stops it from embedding\n *\n * @param url - The URL to wrap\n */\nexport function hideLinkEmbed(url: C): `<${C}>`;\n\n/**\n * Wraps the URL into `<>`, which stops it from embedding\n *\n * @param url - The URL to wrap\n */\nexport function hideLinkEmbed(url: URL): `<${string}>`;\nexport function hideLinkEmbed(url: URL | string) {\n\treturn `<${url}>`;\n}\n\n/**\n * Formats the content and the URL into a masked URL\n *\n * @param content - The content to display\n * @param url - The URL the content links to\n */\nexport function hyperlink(content: C, url: URL): `[${C}](${string})`;\n\n/**\n * Formats the content and the URL into a masked URL\n *\n * @param content - The content to display\n * @param url - The URL the content links to\n */\nexport function hyperlink(content: C, url: U): `[${C}](${U})`;\n\n/**\n * Formats the content and the URL into a masked URL\n *\n * @param content - The content to display\n * @param url - The URL the content links to\n * @param title - The title shown when hovering on the masked link\n */\nexport function hyperlink(\n\tcontent: C,\n\turl: URL,\n\ttitle: T,\n): `[${C}](${string} \"${T}\")`;\n\n/**\n * Formats the content and the URL into a masked URL\n *\n * @param content - The content to display\n * @param url - The URL the content links to\n * @param title - The title shown when hovering on the masked link\n */\nexport function hyperlink(\n\tcontent: C,\n\turl: U,\n\ttitle: T,\n): `[${C}](${U} \"${T}\")`;\nexport function hyperlink(content: string, url: URL | string, title?: string) {\n\treturn title ? `[${content}](${url} \"${title}\")` : `[${content}](${url})`;\n}\n\n/**\n * Wraps the content inside spoiler (hidden text)\n *\n * @param content - The content to wrap\n */\nexport function spoiler(content: C): `||${C}||` {\n\treturn `||${content}||`;\n}\n\n/**\n * Formats a user ID into a user mention\n *\n * @param userId - The user ID to format\n */\nexport function userMention(userId: C): `<@${C}>` {\n\treturn `<@${userId}>`;\n}\n\n/**\n * Formats a channel ID into a channel mention\n *\n * @param channelId - The channel ID to format\n */\nexport function channelMention(channelId: C): `<#${C}>` {\n\treturn `<#${channelId}>`;\n}\n\n/**\n * Formats a role ID into a role mention\n *\n * @param roleId - The role ID to format\n */\nexport function roleMention(roleId: C): `<@&${C}>` {\n\treturn `<@&${roleId}>`;\n}\n\n/**\n * Formats an application command name, subcommand group name, subcommand name, and ID into an application command mention\n *\n * @param commandName - The application command name to format\n * @param subcommandGroupName - The subcommand group name to format\n * @param subcommandName - The subcommand name to format\n * @param commandId - The application command ID to format\n */\nexport function chatInputApplicationCommandMention<\n\tN extends string,\n\tG extends string,\n\tS extends string,\n\tI extends Snowflake,\n>(commandName: N, subcommandGroupName: G, subcommandName: S, commandId: I): ``;\n\n/**\n * Formats an application command name, subcommand name, and ID into an application command mention\n *\n * @param commandName - The application command name to format\n * @param subcommandName - The subcommand name to format\n * @param commandId - The application command ID to format\n */\nexport function chatInputApplicationCommandMention(\n\tcommandName: N,\n\tsubcommandName: S,\n\tcommandId: I,\n): ``;\n\n/**\n * Formats an application command name and ID into an application command mention\n *\n * @param commandName - The application command name to format\n * @param commandId - The application command ID to format\n */\nexport function chatInputApplicationCommandMention(\n\tcommandName: N,\n\tcommandId: I,\n): ``;\n\n/**\n * Formats an application command name, subcommand group name, subcommand name, and ID into an application command mention\n *\n * @param commandName - The application command name to format\n * @param subcommandGroupName - The subcommand group name to format\n * @param subcommandName - The subcommand name to format\n * @param commandId - The application command ID to format\n */\nexport function chatInputApplicationCommandMention<\n\tN extends string,\n\tG extends Snowflake | string,\n\tS extends Snowflake | string,\n\tI extends Snowflake,\n>(\n\tcommandName: N,\n\tsubcommandGroupName: G,\n\tsubcommandName?: S,\n\tcommandId?: I,\n): `` | `` | `` {\n\tif (typeof commandId !== 'undefined') {\n\t\treturn ``;\n\t}\n\n\tif (typeof subcommandName !== 'undefined') {\n\t\treturn ``;\n\t}\n\n\treturn ``;\n}\n\n/**\n * Formats an emoji ID into a fully qualified emoji identifier\n *\n * @param emojiId - The emoji ID to format\n */\nexport function formatEmoji(emojiId: C, animated?: false): `<:_:${C}>`;\n\n/**\n * Formats an emoji ID into a fully qualified emoji identifier\n *\n * @param emojiId - The emoji ID to format\n * @param animated - Whether the emoji is animated or not. Defaults to `false`\n */\nexport function formatEmoji(emojiId: C, animated?: true): ``;\n\n/**\n * Formats an emoji ID into a fully qualified emoji identifier\n *\n * @param emojiId - The emoji ID to format\n * @param animated - Whether the emoji is animated or not. Defaults to `false`\n */\nexport function formatEmoji(emojiId: C, animated?: boolean): `<:_:${C}>` | ``;\n\n/**\n * Formats an emoji ID into a fully qualified emoji identifier\n *\n * @param emojiId - The emoji ID to format\n * @param animated - Whether the emoji is animated or not. Defaults to `false`\n */\nexport function formatEmoji(emojiId: C, animated = false): `<:_:${C}>` | `` {\n\treturn `<${animated ? 'a' : ''}:_:${emojiId}>`;\n}\n\n/**\n * Formats a channel link for a direct message channel.\n *\n * @param channelId - The channel's id\n */\nexport function channelLink(channelId: C): `https://discord.com/channels/@me/${C}`;\n\n/**\n * Formats a channel link for a guild channel.\n *\n * @param channelId - The channel's id\n * @param guildId - The guild's id\n */\nexport function channelLink(\n\tchannelId: C,\n\tguildId: G,\n): `https://discord.com/channels/${G}/${C}`;\n\nexport function channelLink(\n\tchannelId: C,\n\tguildId?: G,\n): `https://discord.com/channels/@me/${C}` | `https://discord.com/channels/${G}/${C}` {\n\treturn `https://discord.com/channels/${guildId ?? '@me'}/${channelId}`;\n}\n\n/**\n * Formats a message link for a direct message channel.\n *\n * @param channelId - The channel's id\n * @param messageId - The message's id\n */\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n): `https://discord.com/channels/@me/${C}/${M}`;\n\n/**\n * Formats a message link for a guild channel.\n *\n * @param channelId - The channel's id\n * @param messageId - The message's id\n * @param guildId - The guild's id\n */\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n\tguildId: G,\n): `https://discord.com/channels/${G}/${C}/${M}`;\n\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n\tguildId?: G,\n): `https://discord.com/channels/@me/${C}/${M}` | `https://discord.com/channels/${G}/${C}/${M}` {\n\treturn `${typeof guildId === 'undefined' ? channelLink(channelId) : channelLink(channelId, guildId)}/${messageId}`;\n}\n\n/**\n * Formats a date into a short date-time string\n *\n * @param date - The date to format, defaults to the current time\n */\nexport function time(date?: Date): ``;\n\n/**\n * Formats a date given a format style\n *\n * @param date - The date to format\n * @param style - The style to use\n */\nexport function time(date: Date, style: S): ``;\n\n/**\n * Formats the given timestamp into a short date-time string\n *\n * @param seconds - The time to format, represents an UNIX timestamp in seconds\n */\nexport function time(seconds: C): ``;\n\n/**\n * Formats the given timestamp into a short date-time string\n *\n * @param seconds - The time to format, represents an UNIX timestamp in seconds\n * @param style - The style to use\n */\nexport function time(seconds: C, style: S): ``;\nexport function time(timeOrSeconds?: Date | number, style?: TimestampStylesString): string {\n\tif (typeof timeOrSeconds !== 'number') {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\ttimeOrSeconds = Math.floor((timeOrSeconds?.getTime() ?? Date.now()) / 1_000);\n\t}\n\n\treturn typeof style === 'string' ? `` : ``;\n}\n\n/**\n * The {@link https://discord.com/developers/docs/reference#message-formatting-timestamp-styles | message formatting timestamp styles} supported by Discord\n */\nexport const TimestampStyles = {\n\t/**\n\t * Short time format, consisting of hours and minutes, e.g. 16:20\n\t */\n\tShortTime: 't',\n\n\t/**\n\t * Long time format, consisting of hours, minutes, and seconds, e.g. 16:20:30\n\t */\n\tLongTime: 'T',\n\n\t/**\n\t * Short date format, consisting of day, month, and year, e.g. 20/04/2021\n\t */\n\tShortDate: 'd',\n\n\t/**\n\t * Long date format, consisting of day, month, and year, e.g. 20 April 2021\n\t */\n\tLongDate: 'D',\n\n\t/**\n\t * Short date-time format, consisting of short date and short time formats, e.g. 20 April 2021 16:20\n\t */\n\tShortDateTime: 'f',\n\n\t/**\n\t * Long date-time format, consisting of long date and short time formats, e.g. Tuesday, 20 April 2021 16:20\n\t */\n\tLongDateTime: 'F',\n\n\t/**\n\t * Relative time format, consisting of a relative duration format, e.g. 2 months ago\n\t */\n\tRelativeTime: 'R',\n} as const;\n\n/**\n * The possible values, see {@link TimestampStyles} for more information\n */\nexport type TimestampStylesString = typeof TimestampStyles[keyof typeof TimestampStyles];\n\n/**\n * An enum with all the available faces from Discord's native slash commands\n */\nexport enum Faces {\n\t/**\n\t * Β―\\\\_(ツ)\\\\_/Β―\n\t */\n\tShrug = 'Β―\\\\_(ツ)\\\\_/Β―',\n\n\t/**\n\t * (β•―Β°β–‘Β°οΌ‰β•―οΈ΅ ┻━┻\n\t */\n\tTableflip = '(β•―Β°β–‘Β°οΌ‰β•―οΈ΅ ┻━┻',\n\n\t/**\n\t * ┬─┬ γƒŽ( γ‚œ-γ‚œγƒŽ)\n\t */\n\tUnflip = '┬─┬ γƒŽ( γ‚œ-γ‚œγƒŽ)',\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ButtonStyle, ChannelType, type APIMessageComponentEmoji } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../util/validation.js';\nimport { StringSelectMenuOptionBuilder } from './selectMenu/StringSelectMenuOption.js';\n\nexport const customIdValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const emojiValidator = s\n\t.object({\n\t\tid: s.string,\n\t\tname: s.string,\n\t\tanimated: s.boolean,\n\t})\n\t.partial.strict.setValidationEnabled(isValidationEnabled);\n\nexport const disabledValidator = s.boolean;\n\nexport const buttonLabelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(80)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const buttonStyleValidator = s.nativeEnum(ButtonStyle);\n\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(150).setValidationEnabled(isValidationEnabled);\nexport const minMaxValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const labelValueDescriptionValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const jsonOptionValidator = s\n\t.object({\n\t\tlabel: labelValueDescriptionValidator,\n\t\tvalue: labelValueDescriptionValidator,\n\t\tdescription: labelValueDescriptionValidator.optional,\n\t\temoji: emojiValidator.optional,\n\t\tdefault: s.boolean.optional,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const optionValidator = s.instance(StringSelectMenuOptionBuilder).setValidationEnabled(isValidationEnabled);\n\nexport const optionsValidator = optionValidator.array\n\t.lengthGreaterThanOrEqual(0)\n\t.setValidationEnabled(isValidationEnabled);\nexport const optionsLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredSelectMenuParameters(options: StringSelectMenuOptionBuilder[], customId?: string) {\n\tcustomIdValidator.parse(customId);\n\toptionsValidator.parse(options);\n}\n\nexport const defaultValidator = s.boolean;\n\nexport function validateRequiredSelectMenuOptionParameters(label?: string, value?: string) {\n\tlabelValueDescriptionValidator.parse(label);\n\tlabelValueDescriptionValidator.parse(value);\n}\n\nexport const channelTypesValidator = s.nativeEnum(ChannelType).array.setValidationEnabled(isValidationEnabled);\n\nexport const urlValidator = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'discord:'],\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredButtonParameters(\n\tstyle?: ButtonStyle,\n\tlabel?: string,\n\temoji?: APIMessageComponentEmoji,\n\tcustomId?: string,\n\turl?: string,\n) {\n\tif (url && customId) {\n\t\tthrow new RangeError('URL and custom id are mutually exclusive');\n\t}\n\n\tif (!label && !emoji) {\n\t\tthrow new RangeError('Buttons must have a label and/or an emoji');\n\t}\n\n\tif (style === ButtonStyle.Link) {\n\t\tif (!url) {\n\t\t\tthrow new RangeError('Link buttons must have a url');\n\t\t}\n\t} else if (url) {\n\t\tthrow new RangeError('Non-link buttons cannot have a url');\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type { APIMessageComponentEmoji, APISelectMenuOption } from 'discord-api-types/v10';\nimport {\n\tdefaultValidator,\n\temojiValidator,\n\tlabelValueDescriptionValidator,\n\tvalidateRequiredSelectMenuOptionParameters,\n} from '../Assertions.js';\n\n/**\n * Represents an option within a string select menu component\n */\nexport class StringSelectMenuOptionBuilder implements JSONEncodable {\n\t/**\n\t * Creates a new string select menu option from API data\n\t *\n\t * @param data - The API data to create this string select menu option with\n\t * @example\n\t * Creating a string select menu option from an API data object\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tlabel: 'catchy label',\n\t * \tvalue: '1',\n\t * });\n\t * ```\n\t * @example\n\t * Creating a string select menu option using setters and API data\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tdefault: true,\n\t * \tvalue: '1',\n\t * })\n\t * \t.setLabel('woah')\n\t * ```\n\t */\n\tpublic constructor(public data: Partial = {}) {}\n\n\t/**\n\t * Sets the label of this option\n\t *\n\t * @param label - The label to show on this option\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValueDescriptionValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value of this option\n\t *\n\t * @param value - The value of this option\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = labelValueDescriptionValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this option\n\t *\n\t * @param description - The description of this option\n\t */\n\tpublic setDescription(description: string) {\n\t\tthis.data.description = labelValueDescriptionValidator.parse(description);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this option is selected by default\n\t *\n\t * @param isDefault - Whether this option is selected by default\n\t */\n\tpublic setDefault(isDefault = true) {\n\t\tthis.data.default = defaultValidator.parse(isDefault);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display on this option\n\t *\n\t * @param emoji - The emoji to display on this option\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APISelectMenuOption {\n\t\tvalidateRequiredSelectMenuOptionParameters(this.data.label, this.data.value);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APISelectMenuOption;\n\t}\n}\n","/* eslint-disable jsdoc/check-param-names */\n\nimport {\n\ttype APIActionRowComponent,\n\tComponentType,\n\ttype APIMessageActionRowComponent,\n\ttype APIModalActionRowComponent,\n\ttype APIActionRowComponentTypes,\n} from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../util/normalizeArray.js';\nimport { ComponentBuilder } from './Component.js';\nimport { createComponentBuilder } from './Components.js';\nimport type { ButtonBuilder } from './button/Button.js';\nimport type { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport type { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport type { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport type { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport type { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport type { TextInputBuilder } from './textInput/TextInput.js';\n\nexport type MessageComponentBuilder =\n\t| ActionRowBuilder\n\t| MessageActionRowComponentBuilder;\nexport type ModalComponentBuilder = ActionRowBuilder | ModalActionRowComponentBuilder;\nexport type MessageActionRowComponentBuilder =\n\t| ButtonBuilder\n\t| ChannelSelectMenuBuilder\n\t| MentionableSelectMenuBuilder\n\t| RoleSelectMenuBuilder\n\t| StringSelectMenuBuilder\n\t| UserSelectMenuBuilder;\nexport type ModalActionRowComponentBuilder = TextInputBuilder;\nexport type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalActionRowComponentBuilder;\n\n/**\n * Represents an action row component\n *\n * @typeParam T - The types of components this action row holds\n */\nexport class ActionRowBuilder extends ComponentBuilder<\n\tAPIActionRowComponent\n> {\n\t/**\n\t * The components within this action row\n\t */\n\tpublic readonly components: T[];\n\n\t/**\n\t * Creates a new action row from API data\n\t *\n\t * @param data - The API data to create this action row with\n\t * @example\n\t * Creating an action row from an API data object\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Type something\",\n\t * \t\t\tstyle: TextInputStyle.Short,\n\t * \t\t\ttype: ComponentType.TextInput,\n\t * \t\t},\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating an action row using setters and API data\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Click me\",\n\t * \t\t\tstyle: ButtonStyle.Primary,\n\t * \t\t\ttype: ComponentType.Button,\n\t * \t\t},\n\t * \t],\n\t * })\n\t * \t.addComponents(button2, button3);\n\t * ```\n\t */\n\tpublic constructor({ components, ...data }: Partial> = {}) {\n\t\tsuper({ type: ComponentType.ActionRow, ...data });\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ?? []) as T[];\n\t}\n\n\t/**\n\t * Adds components to this action row.\n\t *\n\t * @param components - The components to add to this action row.\n\t */\n\tpublic addComponents(...components: RestOrArray) {\n\t\tthis.components.push(...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the components in this action row\n\t *\n\t * @param components - The components to set this row to\n\t */\n\tpublic setComponents(...components: RestOrArray) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIActionRowComponent> {\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIActionRowComponent>;\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIActionRowComponentTypes,\n\tAPIBaseComponent,\n\tComponentType,\n} from 'discord-api-types/v10';\n\nexport type AnyAPIActionRowComponent = APIActionRowComponent | APIActionRowComponentTypes;\n\n/**\n * Represents a discord component\n *\n * @typeParam DataType - The type of internal API data that is stored within the component\n */\nexport abstract class ComponentBuilder<\n\tDataType extends Partial> = APIBaseComponent,\n> implements JSONEncodable\n{\n\t/**\n\t * The API data associated with this component\n\t */\n\tpublic readonly data: Partial;\n\n\t/**\n\t * Serializes this component to an API-compatible JSON object\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic abstract toJSON(): AnyAPIActionRowComponent;\n\n\tpublic constructor(data: Partial) {\n\t\tthis.data = data;\n\t}\n}\n","import { ComponentType, type APIMessageComponent, type APIModalComponent } from 'discord-api-types/v10';\nimport {\n\tActionRowBuilder,\n\ttype AnyComponentBuilder,\n\ttype MessageComponentBuilder,\n\ttype ModalComponentBuilder,\n} from './ActionRow.js';\nimport { ComponentBuilder } from './Component.js';\nimport { ButtonBuilder } from './button/Button.js';\nimport { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport { TextInputBuilder } from './textInput/TextInput.js';\n\nexport interface MappedComponentTypes {\n\t[ComponentType.ActionRow]: ActionRowBuilder;\n\t[ComponentType.Button]: ButtonBuilder;\n\t[ComponentType.StringSelect]: StringSelectMenuBuilder;\n\t[ComponentType.TextInput]: TextInputBuilder;\n\t[ComponentType.UserSelect]: UserSelectMenuBuilder;\n\t[ComponentType.RoleSelect]: RoleSelectMenuBuilder;\n\t[ComponentType.MentionableSelect]: MentionableSelectMenuBuilder;\n\t[ComponentType.ChannelSelect]: ChannelSelectMenuBuilder;\n}\n\n/**\n * Factory for creating components from API data\n *\n * @param data - The api data to transform to a component class\n */\nexport function createComponentBuilder(\n\t// eslint-disable-next-line @typescript-eslint/sort-type-union-intersection-members\n\tdata: (APIModalComponent | APIMessageComponent) & { type: T },\n): MappedComponentTypes[T];\nexport function createComponentBuilder(data: C): C;\nexport function createComponentBuilder(\n\tdata: APIMessageComponent | APIModalComponent | MessageComponentBuilder,\n): ComponentBuilder {\n\tif (data instanceof ComponentBuilder) {\n\t\treturn data;\n\t}\n\n\tswitch (data.type) {\n\t\tcase ComponentType.ActionRow:\n\t\t\treturn new ActionRowBuilder(data);\n\t\tcase ComponentType.Button:\n\t\t\treturn new ButtonBuilder(data);\n\t\tcase ComponentType.StringSelect:\n\t\t\treturn new StringSelectMenuBuilder(data);\n\t\tcase ComponentType.TextInput:\n\t\t\treturn new TextInputBuilder(data);\n\t\tcase ComponentType.UserSelect:\n\t\t\treturn new UserSelectMenuBuilder(data);\n\t\tcase ComponentType.RoleSelect:\n\t\t\treturn new RoleSelectMenuBuilder(data);\n\t\tcase ComponentType.MentionableSelect:\n\t\t\treturn new MentionableSelectMenuBuilder(data);\n\t\tcase ComponentType.ChannelSelect:\n\t\t\treturn new ChannelSelectMenuBuilder(data);\n\t\tdefault:\n\t\t\t// @ts-expect-error: This case can still occur if we get a newer unsupported component type\n\t\t\tthrow new Error(`Cannot properly serialize component type: ${data.type}`);\n\t}\n}\n","import {\n\tComponentType,\n\ttype APIMessageComponentEmoji,\n\ttype APIButtonComponent,\n\ttype APIButtonComponentWithURL,\n\ttype APIButtonComponentWithCustomId,\n\ttype ButtonStyle,\n} from 'discord-api-types/v10';\nimport {\n\tbuttonLabelValidator,\n\tbuttonStyleValidator,\n\tcustomIdValidator,\n\tdisabledValidator,\n\temojiValidator,\n\turlValidator,\n\tvalidateRequiredButtonParameters,\n} from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\n/**\n * Represents a button component\n */\nexport class ButtonBuilder extends ComponentBuilder {\n\t/**\n\t * Creates a new button from API data\n\t *\n\t * @param data - The API data to create this button with\n\t * @example\n\t * Creating a button from an API data object\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tcustom_id: 'a cool button',\n\t * \tstyle: ButtonStyle.Primary,\n\t * \tlabel: 'Click Me',\n\t * \temoji: {\n\t * \t\tname: 'smile',\n\t * \t\tid: '123456789012345678',\n\t * \t},\n\t * });\n\t * ```\n\t * @example\n\t * Creating a button using setters and API data\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tstyle: ButtonStyle.Secondary,\n\t * \tlabel: 'Click Me',\n\t * })\n\t * \t.setEmoji({ name: 'πŸ™‚' })\n\t * \t.setCustomId('another cool button');\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ type: ComponentType.Button, ...data });\n\t}\n\n\t/**\n\t * Sets the style of this button\n\t *\n\t * @param style - The style of the button\n\t */\n\tpublic setStyle(style: ButtonStyle) {\n\t\tthis.data.style = buttonStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL for this button\n\t *\n\t * @remarks\n\t * This method is only available to buttons using the `Link` button style.\n\t * Only three types of URL schemes are currently supported: `https://`, `http://` and `discord://`\n\t * @param url - The URL to open when this button is clicked\n\t */\n\tpublic setURL(url: string) {\n\t\t(this.data as APIButtonComponentWithURL).url = urlValidator.parse(url);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this button\n\t *\n\t * @remarks\n\t * This method is only applicable to buttons that are not using the `Link` button style.\n\t * @param customId - The custom id to use for this button\n\t */\n\tpublic setCustomId(customId: string) {\n\t\t(this.data as APIButtonComponentWithCustomId).custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display on this button\n\t *\n\t * @param emoji - The emoji to display on this button\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this button is disabled\n\t *\n\t * @param disabled - Whether to disable this button\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this button\n\t *\n\t * @param label - The label to display on this button\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = buttonLabelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIButtonComponent {\n\t\tvalidateRequiredButtonParameters(\n\t\t\tthis.data.style,\n\t\t\tthis.data.label,\n\t\t\tthis.data.emoji,\n\t\t\t(this.data as APIButtonComponentWithCustomId).custom_id,\n\t\t\t(this.data as APIButtonComponentWithURL).url,\n\t\t);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIButtonComponent;\n\t}\n}\n","import type { APIChannelSelectComponent, ChannelType } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { channelTypesValidator, customIdValidator } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\nexport class ChannelSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement)\n\t * \t.setMinValues(2)\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.ChannelSelect });\n\t}\n\n\tpublic addChannelTypes(...types: RestOrArray) {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\ttypes = normalizeArray(types);\n\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.push(...channelTypesValidator.parse(types));\n\t\treturn this;\n\t}\n\n\tpublic setChannelTypes(...types: RestOrArray) {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\ttypes = normalizeArray(types);\n\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(types));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIChannelSelectComponent {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIChannelSelectComponent;\n\t}\n}\n","import type { APISelectMenuComponent } from 'discord-api-types/v10';\nimport { customIdValidator, disabledValidator, minMaxValidator, placeholderValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\nexport class BaseSelectMenuBuilder<\n\tSelectMenuType extends APISelectMenuComponent,\n> extends ComponentBuilder {\n\t/**\n\t * Sets the placeholder for this select menu\n\t *\n\t * @param placeholder - The placeholder to use for this select menu\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum values that must be selected in the select menu\n\t *\n\t * @param minValues - The minimum values that must be selected\n\t */\n\tpublic setMinValues(minValues: number) {\n\t\tthis.data.min_values = minMaxValidator.parse(minValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum values that must be selected in the select menu\n\t *\n\t * @param maxValues - The maximum values that must be selected\n\t */\n\tpublic setMaxValues(maxValues: number) {\n\t\tthis.data.max_values = minMaxValidator.parse(maxValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this select menu\n\t *\n\t * @param customId - The custom id to use for this select menu\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this select menu is disabled\n\t *\n\t * @param disabled - Whether this select menu is disabled\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): SelectMenuType {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as SelectMenuType;\n\t}\n}\n","import type { APIMentionableSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\nexport class MentionableSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.MentionableSelect });\n\t}\n}\n","import type { APIRoleSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\nexport class RoleSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.RoleSelect });\n\t}\n}\n","import type { APIStringSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType, type APISelectMenuOption } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { jsonOptionValidator, optionsLengthValidator, validateRequiredSelectMenuParameters } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\nimport { StringSelectMenuOptionBuilder } from './StringSelectMenuOption.js';\n\n/**\n * Represents a string select menu component\n */\nexport class StringSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * The options within this select menu\n\t */\n\tpublic readonly options: StringSelectMenuOptionBuilder[];\n\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * \toptions: [\n\t * \t\t{ label: 'option 1', value: '1' },\n\t * \t\t{ label: 'option 2', value: '2' },\n\t * \t\t{ label: 'option 3', value: '3' },\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * \t.addOptions({\n\t * \t\tlabel: 'Catchy',\n\t * \t\tvalue: 'catch',\n\t * \t});\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tconst { options, ...initData } = data ?? {};\n\t\tsuper({ ...initData, type: ComponentType.StringSelect });\n\t\tthis.options = options?.map((option: APISelectMenuOption) => new StringSelectMenuOptionBuilder(option)) ?? [];\n\t}\n\n\t/**\n\t * Adds options to this select menu\n\t *\n\t * @param options - The options to add to this select menu\n\t * @returns\n\t */\n\tpublic addOptions(...options: RestOrArray) {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\toptions = normalizeArray(options);\n\t\toptionsLengthValidator.parse(this.options.length + options.length);\n\t\tthis.options.push(\n\t\t\t...options.map((option) =>\n\t\t\t\toption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? option\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the options on this select menu\n\t *\n\t * @param options - The options to set on this select menu\n\t */\n\tpublic setOptions(...options: RestOrArray) {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\toptions = normalizeArray(options);\n\t\toptionsLengthValidator.parse(options.length);\n\t\tthis.options.splice(\n\t\t\t0,\n\t\t\tthis.options.length,\n\t\t\t...options.map((option) =>\n\t\t\t\toption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? option\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(option)),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIStringSelectComponent {\n\t\tvalidateRequiredSelectMenuParameters(this.options, this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t} as APIStringSelectComponent;\n\t}\n}\n","import type { APIUserSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\nexport class UserSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.UserSelect });\n\t}\n}\n","import { isJSONEncodable, type Equatable, type JSONEncodable } from '@discordjs/util';\nimport { ComponentType, type TextInputStyle, type APITextInputComponent } from 'discord-api-types/v10';\nimport isEqual from 'fast-deep-equal';\nimport { customIdValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\nimport {\n\tmaxLengthValidator,\n\tminLengthValidator,\n\tplaceholderValidator,\n\trequiredValidator,\n\tvalueValidator,\n\tvalidateRequiredParameters,\n\tlabelValidator,\n\ttextInputStyleValidator,\n} from './Assertions.js';\n\nexport class TextInputBuilder\n\textends ComponentBuilder\n\timplements Equatable>\n{\n\t/**\n\t * Creates a new text input from API data\n\t *\n\t * @param data - The API data to create this text input with\n\t * @example\n\t * Creating a select menu option from an API data object\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tlabel: 'Type something',\n\t * \tstyle: TextInputStyle.Short,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu option using setters and API data\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tlabel: 'Type something else',\n\t * })\n\t * \t.setCustomId('woah')\n\t * \t.setStyle(TextInputStyle.Paragraph);\n\t * ```\n\t */\n\tpublic constructor(data?: APITextInputComponent & { type?: ComponentType.TextInput }) {\n\t\tsuper({ type: ComponentType.TextInput, ...data });\n\t}\n\n\t/**\n\t * Sets the custom id for this text input\n\t *\n\t * @param customId - The custom id of this text input\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this text input\n\t *\n\t * @param label - The label for this text input\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the style for this text input\n\t *\n\t * @param style - The style for this text input\n\t */\n\tpublic setStyle(style: TextInputStyle) {\n\t\tthis.data.style = textInputStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of text for this text input\n\t *\n\t * @param minLength - The minimum length of text for this text input\n\t */\n\tpublic setMinLength(minLength: number) {\n\t\tthis.data.min_length = minLengthValidator.parse(minLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum length of text for this text input\n\t *\n\t * @param maxLength - The maximum length of text for this text input\n\t */\n\tpublic setMaxLength(maxLength: number) {\n\t\tthis.data.max_length = maxLengthValidator.parse(maxLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the placeholder of this text input\n\t *\n\t * @param placeholder - The placeholder of this text input\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value of this text input\n\t *\n\t * @param value - The value for this text input\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = valueValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this text input is required\n\t *\n\t * @param required - Whether this text input is required\n\t */\n\tpublic setRequired(required = true) {\n\t\tthis.data.required = requiredValidator.parse(required);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APITextInputComponent {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.style, this.data.label);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APITextInputComponent;\n\t}\n\n\t/**\n\t * {@inheritDoc Equatable.equals}\n\t */\n\tpublic equals(other: APITextInputComponent | JSONEncodable): boolean {\n\t\tif (isJSONEncodable(other)) {\n\t\t\treturn isEqual(other.toJSON(), this.data);\n\t\t}\n\n\t\treturn isEqual(other, this.data);\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { TextInputStyle } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport { customIdValidator } from '../Assertions.js';\n\nexport const textInputStyleValidator = s.nativeEnum(TextInputStyle);\nexport const minLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const maxLengthValidator = s.number.int\n\t.greaterThanOrEqual(1)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const requiredValidator = s.boolean;\nexport const valueValidator = s.string.lengthLessThanOrEqual(4_000).setValidationEnabled(isValidationEnabled);\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled);\nexport const labelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(customId?: string, style?: TextInputStyle, label?: string) {\n\tcustomIdValidator.parse(customId);\n\ttextInputStyleValidator.parse(style);\n\tlabelValidator.parse(label);\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const titleValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\nexport const componentsValidator = s\n\t.instance(ActionRowBuilder)\n\t.array.lengthGreaterThanOrEqual(1)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(\n\tcustomId?: string,\n\ttitle?: string,\n\tcomponents?: ActionRowBuilder[],\n) {\n\tcustomIdValidator.parse(customId);\n\ttitleValidator.parse(title);\n\tcomponentsValidator.parse(components);\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIModalActionRowComponent,\n\tAPIModalInteractionResponseCallbackData,\n} from 'discord-api-types/v10';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { createComponentBuilder } from '../../components/Components.js';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { titleValidator, validateRequiredParameters } from './Assertions.js';\n\nexport class ModalBuilder implements JSONEncodable {\n\tpublic readonly data: Partial;\n\n\tpublic readonly components: ActionRowBuilder[] = [];\n\n\tpublic constructor({ components, ...data }: Partial = {}) {\n\t\tthis.data = { ...data };\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ??\n\t\t\t[]) as ActionRowBuilder[];\n\t}\n\n\t/**\n\t * Sets the title of the modal\n\t *\n\t * @param title - The title of the modal\n\t */\n\tpublic setTitle(title: string) {\n\t\tthis.data.title = titleValidator.parse(title);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id of the modal\n\t *\n\t * @param customId - The custom id of this modal\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds components to this modal\n\t *\n\t * @param components - The components to add to this modal\n\t */\n\tpublic addComponents(\n\t\t...components: RestOrArray<\n\t\t\tActionRowBuilder | APIActionRowComponent\n\t\t>\n\t) {\n\t\tthis.components.push(\n\t\t\t...normalizeArray(components).map((component) =>\n\t\t\t\tcomponent instanceof ActionRowBuilder\n\t\t\t\t\t? component\n\t\t\t\t\t: new ActionRowBuilder(component),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the components in this modal\n\t *\n\t * @param components - The components to set this modal to\n\t */\n\tpublic setComponents(...components: RestOrArray>) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIModalInteractionResponseCallbackData {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.title, this.components);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIModalInteractionResponseCallbackData;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { Locale, type APIApplicationCommandOptionChoice, type LocalizationMap } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t.regex(/^[\\p{Ll}\\p{Lm}\\p{Lo}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}_-]+$/u)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nconst descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\nconst localePredicate = s.nativeEnum(Locale);\n\nexport function validateDescription(description: unknown): asserts description is string {\n\tdescriptionPredicate.parse(description);\n}\n\nconst maxArrayLengthPredicate = s.unknown.array.lengthLessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\nexport function validateLocale(locale: unknown) {\n\treturn localePredicate.parse(locale);\n}\n\nexport function validateMaxOptionsLength(options: unknown): asserts options is ToAPIApplicationCommandOptions[] {\n\tmaxArrayLengthPredicate.parse(options);\n}\n\nexport function validateRequiredParameters(\n\tname: string,\n\tdescription: string,\n\toptions: ToAPIApplicationCommandOptions[],\n) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert description conditions\n\tvalidateDescription(description);\n\n\t// Assert options conditions\n\tvalidateMaxOptionsLength(options);\n}\n\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateRequired(required: unknown): asserts required is boolean {\n\tbooleanPredicate.parse(required);\n}\n\nconst choicesLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateChoicesLength(amountAdding: number, choices?: APIApplicationCommandOptionChoice[]): void {\n\tchoicesLengthPredicate.parse((choices?.length ?? 0) + amountAdding);\n}\n\nexport function assertReturnOfBuilder<\n\tT extends ApplicationCommandOptionBase | SlashCommandSubcommandBuilder | SlashCommandSubcommandGroupBuilder,\n>(input: unknown, ExpectedInstanceOf: new () => T): asserts input is T {\n\ts.instance(ExpectedInstanceOf).parse(input);\n}\n\nexport const localizationMapPredicate = s\n\t.object(Object.fromEntries(Object.values(Locale).map((locale) => [locale, s.string.nullish])))\n\t.strict.nullish.setValidationEnabled(isValidationEnabled);\n\nexport function validateLocalizationMap(value: unknown): asserts value is LocalizationMap {\n\tlocalizationMapPredicate.parse(value);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n","import type {\n\tAPIApplicationCommandOption,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIChatInputApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport {\n\tassertReturnOfBuilder,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDefaultPermission,\n\tvalidateLocalizationMap,\n\tvalidateDMPermission,\n\tvalidateMaxOptionsLength,\n\tvalidateRequiredParameters,\n} from './Assertions.js';\nimport { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n@mix(SharedSlashCommandOptions, SharedNameAndDescription)\nexport class SlashCommandBuilder {\n\t/**\n\t * The name of this slash command\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The localized names for this command\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The description of this slash command\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The localized descriptions for this command\n\t */\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * The options of this slash command\n\t */\n\tpublic readonly options: ToAPIApplicationCommandOptions[] = [];\n\n\t/**\n\t * Whether the command is enabled by default when the app is added to a guild\n\t *\n\t * @deprecated This property is deprecated and will be removed in the future.\n\t * You should use {@link (SlashCommandBuilder:class).setDefaultMemberPermissions} or {@link (SlashCommandBuilder:class).setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Set of permissions represented as a bit set for the command\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in DMs with the application, only for globally-scoped commands.\n\t * By default, commands are visible.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Returns the final data that should be sent to Discord.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIChatInputApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\treturn {\n\t\t\t...this,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether or not to enable this command by default\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t * @deprecated Use {@link (SlashCommandBuilder:class).setDefaultMemberPermissions} or {@link (SlashCommandBuilder:class).setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run the command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in DMs with the application, only for globally-scoped commands.\n\t * By default, commands are visible.\n\t *\n\t * @param enabled - If the command should be enabled in DMs\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand group to this command\n\t *\n\t * @param input - A function that returns a subcommand group builder, or an already built builder\n\t */\n\tpublic addSubcommandGroup(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandGroupBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandGroupBuilder) => SlashCommandSubcommandGroupBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandGroupBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandGroupBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand to this command\n\t *\n\t * @param input - A function that returns a subcommand builder, or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n}\n\nexport interface SlashCommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n\nexport interface SlashCommandSubcommandsOnlyBuilder\n\textends Omit> {}\n\nexport interface SlashCommandOptionsOnlyBuilder\n\textends SharedNameAndDescription,\n\t\tSharedSlashCommandOptions,\n\t\tPick {}\n\nexport interface ToAPIApplicationCommandOptions {\n\ttoJSON(): APIApplicationCommandOption;\n}\n","import {\n\tApplicationCommandOptionType,\n\ttype APIApplicationCommandSubcommandGroupOption,\n\ttype APIApplicationCommandSubcommandOption,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { assertReturnOfBuilder, validateMaxOptionsLength, validateRequiredParameters } from './Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n/**\n * Represents a folder for subcommands\n *\n * For more information, go to https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups\n */\n@mix(SharedNameAndDescription)\nexport class SlashCommandSubcommandGroupBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand group\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand group\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The subcommands part of this subcommand group\n\t */\n\tpublic readonly options: SlashCommandSubcommandBuilder[] = [];\n\n\t/**\n\t * Adds a new subcommand to this group\n\t *\n\t * @param input - A function that returns a subcommand builder, or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t) {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): APIApplicationCommandSubcommandGroupOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.SubcommandGroup,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription {}\n\n/**\n * Represents a subcommand\n *\n * For more information, go to https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups\n */\n@mix(SharedNameAndDescription, SharedSlashCommandOptions)\nexport class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The options of this subcommand\n\t */\n\tpublic readonly options: ApplicationCommandOptionBase[] = [];\n\n\tpublic toJSON(): APIApplicationCommandSubcommandOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.Subcommand,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n","import type { LocaleString, LocalizationMap } from 'discord-api-types/v10';\nimport { validateDescription, validateLocale, validateName } from '../Assertions.js';\n\nexport class SharedNameAndDescription {\n\tpublic readonly name!: string;\n\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\tpublic readonly description!: string;\n\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * Sets the name\n\t *\n\t * @param name - The name\n\t */\n\tpublic setName(name: string): this {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description\n\t *\n\t * @param description - The description\n\t */\n\tpublic setDescription(description: string) {\n\t\t// Assert the description matches the conditions\n\t\tvalidateDescription(description);\n\n\t\tReflect.set(this, 'description', description);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a name localization\n\t *\n\t * @param locale - The locale to set a description for\n\t * @param localizedName - The localized description for the given locale\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations\n\t *\n\t * @param localizedNames - The dictionary of localized descriptions to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames)) {\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a description localization\n\t *\n\t * @param locale - The locale to set a description for\n\t * @param localizedDescription - The localized description for the given locale\n\t */\n\tpublic setDescriptionLocalization(locale: LocaleString, localizedDescription: string | null) {\n\t\tif (!this.description_localizations) {\n\t\t\tReflect.set(this, 'description_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedDescription === null) {\n\t\t\tthis.description_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateDescription(localizedDescription);\n\n\t\tthis.description_localizations![parsedLocale] = localizedDescription;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description localizations\n\t *\n\t * @param localizedDescriptions - The dictionary of localized descriptions to set\n\t */\n\tpublic setDescriptionLocalizations(localizedDescriptions: LocalizationMap | null) {\n\t\tif (localizedDescriptions === null) {\n\t\t\tReflect.set(this, 'description_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'description_localizations', {});\n\t\tfor (const args of Object.entries(localizedDescriptions)) {\n\t\t\tthis.setDescriptionLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandAttachmentOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandAttachmentOption extends ApplicationCommandOptionBase {\n\tpublic override readonly type = ApplicationCommandOptionType.Attachment as const;\n\n\tpublic toJSON(): APIApplicationCommandAttachmentOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import type { APIApplicationCommandBasicOption, ApplicationCommandOptionType } from 'discord-api-types/v10';\nimport { validateRequiredParameters, validateRequired, validateLocalizationMap } from '../Assertions.js';\nimport { SharedNameAndDescription } from './NameAndDescription.js';\n\nexport abstract class ApplicationCommandOptionBase extends SharedNameAndDescription {\n\tpublic abstract readonly type: ApplicationCommandOptionType;\n\n\tpublic readonly required: boolean = false;\n\n\t/**\n\t * Marks the option as required\n\t *\n\t * @param required - If this option should be required\n\t */\n\tpublic setRequired(required: boolean) {\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(required);\n\n\t\tReflect.set(this, 'required', required);\n\n\t\treturn this;\n\t}\n\n\tpublic abstract toJSON(): APIApplicationCommandBasicOption;\n\n\tprotected runRequiredValidations() {\n\t\tvalidateRequiredParameters(this.name, this.description, []);\n\n\t\t// Validate localizations\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(this.required);\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandBooleanOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandBooleanOption extends ApplicationCommandOptionBase {\n\tpublic readonly type = ApplicationCommandOptionType.Boolean as const;\n\n\tpublic toJSON(): APIApplicationCommandBooleanOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandChannelOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionChannelTypesMixin } from '../mixins/ApplicationCommandOptionChannelTypesMixin.js';\n\n@mix(ApplicationCommandOptionChannelTypesMixin)\nexport class SlashCommandChannelOption extends ApplicationCommandOptionBase {\n\tpublic override readonly type = ApplicationCommandOptionType.Channel as const;\n\n\tpublic toJSON(): APIApplicationCommandChannelOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandChannelOption extends ApplicationCommandOptionChannelTypesMixin {}\n","import { s } from '@sapphire/shapeshift';\nimport { ChannelType } from 'discord-api-types/v10';\n\n// Only allow valid channel types to be used. (This can't be dynamic because const enums are erased at runtime)\nconst allowedChannelTypes = [\n\tChannelType.GuildText,\n\tChannelType.GuildVoice,\n\tChannelType.GuildCategory,\n\tChannelType.GuildAnnouncement,\n\tChannelType.AnnouncementThread,\n\tChannelType.PublicThread,\n\tChannelType.PrivateThread,\n\tChannelType.GuildStageVoice,\n\tChannelType.GuildForum,\n] as const;\n\nexport type ApplicationCommandOptionAllowedChannelTypes = typeof allowedChannelTypes[number];\n\nconst channelTypesPredicate = s.array(s.union(...allowedChannelTypes.map((type) => s.literal(type))));\n\nexport class ApplicationCommandOptionChannelTypesMixin {\n\tpublic readonly channel_types?: ApplicationCommandOptionAllowedChannelTypes[];\n\n\t/**\n\t * Adds channel types to this option\n\t *\n\t * @param channelTypes - The channel types to add\n\t */\n\tpublic addChannelTypes(...channelTypes: ApplicationCommandOptionAllowedChannelTypes[]) {\n\t\tif (this.channel_types === undefined) {\n\t\t\tReflect.set(this, 'channel_types', []);\n\t\t}\n\n\t\tthis.channel_types!.push(...channelTypesPredicate.parse(channelTypes));\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandIntegerOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number.int;\n\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandIntegerOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\tpublic readonly type = ApplicationCommandOptionType.Integer as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): APIApplicationCommandIntegerOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandIntegerOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","export abstract class ApplicationCommandNumericOptionMinMaxValueMixin {\n\tpublic readonly max_value?: number;\n\n\tpublic readonly min_value?: number;\n\n\t/**\n\t * Sets the maximum number value of this option\n\t *\n\t * @param max - The maximum value this option can be\n\t */\n\tpublic abstract setMaxValue(max: number): this;\n\n\t/**\n\t * Sets the minimum number value of this option\n\t *\n\t * @param min - The minimum value this option can be\n\t */\n\tpublic abstract setMinValue(min: number): this;\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandOptionChoice } from 'discord-api-types/v10';\nimport { localizationMapPredicate, validateChoicesLength } from '../Assertions.js';\n\nconst stringPredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100);\nconst numberPredicate = s.number.greaterThan(Number.NEGATIVE_INFINITY).lessThan(Number.POSITIVE_INFINITY);\nconst choicesPredicate = s.object({\n\tname: stringPredicate,\n\tname_localizations: localizationMapPredicate,\n\tvalue: s.union(stringPredicate, numberPredicate),\n}).array;\nconst booleanPredicate = s.boolean;\n\nexport class ApplicationCommandOptionWithChoicesAndAutocompleteMixin {\n\tpublic readonly choices?: APIApplicationCommandOptionChoice[];\n\n\tpublic readonly autocomplete?: boolean;\n\n\t// Since this is present and this is a mixin, this is needed\n\tpublic readonly type!: ApplicationCommandOptionType;\n\n\t/**\n\t * Adds multiple choices for this option\n\t *\n\t * @param choices - The choices to add\n\t */\n\tpublic addChoices(...choices: APIApplicationCommandOptionChoice[]): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tif (this.choices === undefined) {\n\t\t\tReflect.set(this, 'choices', []);\n\t\t}\n\n\t\tvalidateChoicesLength(choices.length, this.choices);\n\n\t\tfor (const { name, name_localizations, value } of choices) {\n\t\t\t// Validate the value\n\t\t\tif (this.type === ApplicationCommandOptionType.String) {\n\t\t\t\tstringPredicate.parse(value);\n\t\t\t} else {\n\t\t\t\tnumberPredicate.parse(value);\n\t\t\t}\n\n\t\t\tthis.choices!.push({ name, name_localizations, value });\n\t\t}\n\n\t\treturn this;\n\t}\n\n\tpublic setChoices[]>(...choices: Input): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tReflect.set(this, 'choices', []);\n\t\tthis.addChoices(...choices);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Marks the option as autocompletable\n\t *\n\t * @param autocomplete - If this option should be autocompletable\n\t */\n\tpublic setAutocomplete(autocomplete: boolean): this {\n\t\t// Assert that you actually passed a boolean\n\t\tbooleanPredicate.parse(autocomplete);\n\n\t\tif (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tReflect.set(this, 'autocomplete', autocomplete);\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandMentionableOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandMentionableOption extends ApplicationCommandOptionBase {\n\tpublic readonly type = ApplicationCommandOptionType.Mentionable as const;\n\n\tpublic toJSON(): APIApplicationCommandMentionableOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandNumberOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number;\n\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandNumberOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\tpublic readonly type = ApplicationCommandOptionType.Number as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): APIApplicationCommandNumberOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandNumberOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandRoleOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandRoleOption extends ApplicationCommandOptionBase {\n\tpublic override readonly type = ApplicationCommandOptionType.Role as const;\n\n\tpublic toJSON(): APIApplicationCommandRoleOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandStringOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst minLengthValidator = s.number.greaterThanOrEqual(0).lessThanOrEqual(6_000);\nconst maxLengthValidator = s.number.greaterThanOrEqual(1).lessThanOrEqual(6_000);\n\n@mix(ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandStringOption extends ApplicationCommandOptionBase {\n\tpublic readonly type = ApplicationCommandOptionType.String as const;\n\n\tpublic readonly max_length?: number;\n\n\tpublic readonly min_length?: number;\n\n\t/**\n\t * Sets the maximum length of this string option.\n\t *\n\t * @param max - The maximum length this option can be\n\t */\n\tpublic setMaxLength(max: number): this {\n\t\tmaxLengthValidator.parse(max);\n\n\t\tReflect.set(this, 'max_length', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of this string option.\n\t *\n\t * @param min - The minimum length this option can be\n\t */\n\tpublic setMinLength(min: number): this {\n\t\tminLengthValidator.parse(min);\n\n\t\tReflect.set(this, 'min_length', min);\n\n\t\treturn this;\n\t}\n\n\tpublic toJSON(): APIApplicationCommandStringOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandStringOption extends ApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandUserOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\nexport class SlashCommandUserOption extends ApplicationCommandOptionBase {\n\tpublic readonly type = ApplicationCommandOptionType.User as const;\n\n\tpublic toJSON(): APIApplicationCommandUserOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { assertReturnOfBuilder, validateMaxOptionsLength } from '../Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from '../SlashCommandBuilder';\nimport { SlashCommandAttachmentOption } from '../options/attachment.js';\nimport { SlashCommandBooleanOption } from '../options/boolean.js';\nimport { SlashCommandChannelOption } from '../options/channel.js';\nimport { SlashCommandIntegerOption } from '../options/integer.js';\nimport { SlashCommandMentionableOption } from '../options/mentionable.js';\nimport { SlashCommandNumberOption } from '../options/number.js';\nimport { SlashCommandRoleOption } from '../options/role.js';\nimport { SlashCommandStringOption } from '../options/string.js';\nimport { SlashCommandUserOption } from '../options/user.js';\nimport type { ApplicationCommandOptionBase } from './ApplicationCommandOptionBase.js';\n\nexport class SharedSlashCommandOptions {\n\tpublic readonly options!: ToAPIApplicationCommandOptions[];\n\n\t/**\n\t * Adds a boolean option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addBooleanOption(\n\t\tinput: SlashCommandBooleanOption | ((builder: SlashCommandBooleanOption) => SlashCommandBooleanOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandBooleanOption);\n\t}\n\n\t/**\n\t * Adds a user option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addUserOption(input: SlashCommandUserOption | ((builder: SlashCommandUserOption) => SlashCommandUserOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandUserOption);\n\t}\n\n\t/**\n\t * Adds a channel option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addChannelOption(\n\t\tinput: SlashCommandChannelOption | ((builder: SlashCommandChannelOption) => SlashCommandChannelOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandChannelOption);\n\t}\n\n\t/**\n\t * Adds a role option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addRoleOption(input: SlashCommandRoleOption | ((builder: SlashCommandRoleOption) => SlashCommandRoleOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandRoleOption);\n\t}\n\n\t/**\n\t * Adds an attachment option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addAttachmentOption(\n\t\tinput: SlashCommandAttachmentOption | ((builder: SlashCommandAttachmentOption) => SlashCommandAttachmentOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandAttachmentOption);\n\t}\n\n\t/**\n\t * Adds a mentionable option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addMentionableOption(\n\t\tinput: SlashCommandMentionableOption | ((builder: SlashCommandMentionableOption) => SlashCommandMentionableOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandMentionableOption);\n\t}\n\n\t/**\n\t * Adds a string option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addStringOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandStringOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandStringOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandStringOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandStringOption);\n\t}\n\n\t/**\n\t * Adds an integer option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addIntegerOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandIntegerOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandIntegerOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandIntegerOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandIntegerOption);\n\t}\n\n\t/**\n\t * Adds a number option\n\t *\n\t * @param input - A function that returns an option builder, or an already built builder\n\t */\n\tpublic addNumberOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandNumberOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandNumberOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandNumberOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandNumberOption);\n\t}\n\n\tprivate _sharedAddOptionMethod(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| T\n\t\t\t| ((builder: T) => Omit | Omit | T),\n\t\tInstance: new () => T,\n\t): ShouldOmitSubcommandFunctions extends true ? Omit : this {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new Instance()) : input;\n\n\t\tassertReturnOfBuilder(result, Instance);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandType } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ContextMenuCommandType } from './ContextMenuCommandBuilder.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t// eslint-disable-next-line prefer-named-capture-group, unicorn/no-unsafe-regex\n\t.regex(/^( *[\\p{P}\\p{L}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}]+ *)+$/u)\n\t.setValidationEnabled(isValidationEnabled);\nconst typePredicate = s\n\t.union(s.literal(ApplicationCommandType.User), s.literal(ApplicationCommandType.Message))\n\t.setValidationEnabled(isValidationEnabled);\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nexport function validateType(type: unknown): asserts type is ContextMenuCommandType {\n\ttypePredicate.parse(type);\n}\n\nexport function validateRequiredParameters(name: string, type: number) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert type is valid\n\tvalidateType(type);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n","import type {\n\tApplicationCommandType,\n\tLocaleString,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIContextMenuApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { validateLocale, validateLocalizationMap } from '../slashCommands/Assertions.js';\nimport {\n\tvalidateRequiredParameters,\n\tvalidateName,\n\tvalidateType,\n\tvalidateDefaultPermission,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDMPermission,\n} from './Assertions.js';\n\nexport class ContextMenuCommandBuilder {\n\t/**\n\t * The name of this context menu command\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The localized names for this command\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The type of this context menu command\n\t */\n\tpublic readonly type: ContextMenuCommandType = undefined!;\n\n\t/**\n\t * Whether the command is enabled by default when the app is added to a guild\n\t *\n\t * @deprecated This property is deprecated and will be removed in the future.\n\t * You should use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Set of permissions represented as a bit set for the command\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in DMs with the application, only for globally-scoped commands.\n\t * By default, commands are visible.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Sets the name\n\t *\n\t * @param name - The name\n\t */\n\tpublic setName(name: string) {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the type\n\t *\n\t * @param type - The type\n\t */\n\tpublic setType(type: ContextMenuCommandType) {\n\t\t// Assert the type is valid\n\t\tvalidateType(type);\n\n\t\tReflect.set(this, 'type', type);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether or not to enable this command by default\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run the command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in DMs with the application, only for globally-scoped commands.\n\t * By default, commands are visible.\n\t *\n\t * @param enabled - If the command should be enabled in DMs\n\t * @see https://discord.com/developers/docs/interactions/application-commands#permissions\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a name localization\n\t *\n\t * @param locale - The locale to set a description for\n\t * @param localizedName - The localized description for the given locale\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations\n\t *\n\t * @param localizedNames - The dictionary of localized descriptions to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames))\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Returns the final data that should be sent to Discord.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIContextMenuApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.type);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\n\t\treturn { ...this };\n\t}\n}\n\nexport type ContextMenuCommandType = ApplicationCommandType.Message | ApplicationCommandType.User;\n","import type { APIEmbed } from 'discord-api-types/v10';\n\nexport function embedLength(data: APIEmbed) {\n\treturn (\n\t\t(data.title?.length ?? 0) +\n\t\t(data.description?.length ?? 0) +\n\t\t(data.fields?.reduce((prev, curr) => prev + curr.name.length + curr.value.length, 0) ?? 0) +\n\t\t(data.footer?.text.length ?? 0) +\n\t\t(data.author?.name.length ?? 0)\n\t);\n}\n","export * as EmbedAssertions from './messages/embed/Assertions.js';\nexport * from './messages/embed/Embed.js';\nexport * from './messages/formatters.js';\n\nexport * as ComponentAssertions from './components/Assertions.js';\nexport * from './components/ActionRow.js';\nexport * from './components/button/Button.js';\nexport * from './components/Component.js';\nexport * from './components/Components.js';\nexport * from './components/textInput/TextInput.js';\nexport * as TextInputAssertions from './components/textInput/Assertions.js';\nexport * from './interactions/modals/Modal.js';\nexport * as ModalAssertions from './interactions/modals/Assertions.js';\n\nexport * from './components/selectMenu/BaseSelectMenu.js';\nexport * from './components/selectMenu/ChannelSelectMenu.js';\nexport * from './components/selectMenu/MentionableSelectMenu.js';\nexport * from './components/selectMenu/RoleSelectMenu.js';\nexport * from './components/selectMenu/StringSelectMenu.js';\n// TODO: Remove those aliases in v2\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuBuilder} instead.\n\t */\n\tStringSelectMenuBuilder as SelectMenuBuilder,\n} from './components/selectMenu/StringSelectMenu.js';\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuOptionBuilder} instead.\n\t */\n\tStringSelectMenuOptionBuilder as SelectMenuOptionBuilder,\n} from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/UserSelectMenu.js';\n\nexport * as SlashCommandAssertions from './interactions/slashCommands/Assertions.js';\nexport * from './interactions/slashCommands/SlashCommandBuilder.js';\nexport * from './interactions/slashCommands/SlashCommandSubcommands.js';\nexport * from './interactions/slashCommands/options/boolean.js';\nexport * from './interactions/slashCommands/options/channel.js';\nexport * from './interactions/slashCommands/options/integer.js';\nexport * from './interactions/slashCommands/options/mentionable.js';\nexport * from './interactions/slashCommands/options/number.js';\nexport * from './interactions/slashCommands/options/role.js';\nexport * from './interactions/slashCommands/options/attachment.js';\nexport * from './interactions/slashCommands/options/string.js';\nexport * from './interactions/slashCommands/options/user.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionBase.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\nexport * from './interactions/slashCommands/mixins/NameAndDescription.js';\nexport * from './interactions/slashCommands/mixins/SharedSlashCommandOptions.js';\n\nexport * as ContextMenuCommandAssertions from './interactions/contextMenuCommands/Assertions.js';\nexport * from './interactions/contextMenuCommands/ContextMenuCommandBuilder.js';\n\nexport * from './util/componentUtil.js';\nexport * from './util/normalizeArray.js';\nexport * from './util/validation.js';\nexport * from '@discordjs/util';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/builders/#readme | @discordjs/builders} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const version: string = '1.4.0';\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAS,SAAS;;;ACAlB,IAAI,WAAW;AAER,IAAM,mBAAmB,6BAAO,WAAW,MAAlB;AACzB,IAAM,oBAAoB,6BAAO,WAAW,OAAlB;AAC1B,IAAM,sBAAsB,6BAAM,UAAN;;;ADA5B,IAAM,qBAAqB,EAAE,OAClC,yBAAyB,CAAC,EAC1B,sBAAsB,GAAG,EACzB,qBAAqB,mBAAmB;AAEnC,IAAM,sBAAsB,EAAE,OACnC,yBAAyB,CAAC,EAC1B,sBAAsB,IAAK,EAC3B,qBAAqB,mBAAmB;AAEnC,IAAM,uBAAuB,EAAE,QAAQ;AAEvC,IAAM,sBAAsB,EACjC,OAAO;AAAA,EACP,MAAM;AAAA,EACN,OAAO;AAAA,EACP,QAAQ;AACT,CAAC,EACA,qBAAqB,mBAAmB;AAEnC,IAAM,4BAA4B,oBAAoB,MAAM,qBAAqB,mBAAmB;AAEpG,IAAM,uBAAuB,EAAE,OAAO,gBAAgB,EAAE,EAAE,qBAAqB,mBAAmB;AAElG,SAAS,oBAAoB,cAAsB,QAAgC;AACzF,uBAAqB,OAAO,QAAQ,UAAU,KAAK,YAAY;AAChE;AAFgB;AAIT,IAAM,sBAAsB,mBAAmB,SAAS,qBAAqB,mBAAmB;AAEhG,IAAM,oBAAoB,EAAE,OACjC,IAAI;AAAA,EACJ,kBAAkB,CAAC,SAAS,UAAU,aAAa;AACpD,CAAC,EACA,QAAQ,qBAAqB,mBAAmB;AAE3C,IAAM,eA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I,MAAM,sBAAsB,CAAC,CAAC;AAAA,IAC3C;AAEA,UAAM,eAAe,eAAe,MAAM;AAE1C,QAAI,kBAAkB,MAAM;AAC3B,WAAK,mBAAoB,gBAAgB;AACzC,aAAO;AAAA,IACR;AAEA,IAAAH,cAAa,aAAa;AAE1B,SAAK,mBAAoB,gBAAgB;AACzC,WAAO;AAAA,EACR;AAAA,EAOO,qBAAqB,gBAAwC;AACnE,QAAI,mBAAmB,MAAM;AAC5B,cAAQ,IAAI,MAAM,sBAAsB,IAAI;AAC5C,aAAO;AAAA,IACR;AAEA,YAAQ,IAAI,MAAM,sBAAsB,CAAC,CAAC;AAE1C,eAAW,QAAQ,OAAO,QAAQ,cAAc;AAC/C,WAAK,oBAAoB,GAAI,IAAsC;AACpE,WAAO;AAAA,EACR;AAAA,EASO,SAA4D;AAClE,IAAAI,4BAA2B,KAAK,MAAM,KAAK,IAAI;AAE/C,4BAAwB,KAAK,kBAAkB;AAE/C,WAAO,EAAE,GAAG,KAAK;AAAA,EAClB;AACD;AA1Ka;;;ACfN,SAAS,YAAY,MAAgB;AAC3C,UACE,KAAK,OAAO,UAAU,MACtB,KAAK,aAAa,UAAU,MAC5B,KAAK,QAAQ,OAAO,CAAC,MAAM,SAAS,OAAO,KAAK,KAAK,SAAS,KAAK,MAAM,QAAQ,CAAC,KAAK,MACvF,KAAK,QAAQ,KAAK,UAAU,MAC5B,KAAK,QAAQ,KAAK,UAAU;AAE/B;AARgB;;;AC0DhB,cAAc;AAQP,IAAM,UAAkB;","names":["Faces","Assertions_exports","s","s","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","Assertions_exports","placeholderValidator","s","s","placeholderValidator","ComponentType","placeholderValidator","ComponentType","ComponentType","Assertions_exports","validateRequiredParameters","s","s","validateRequiredParameters","validateRequiredParameters","Assertions_exports","validateRequiredParameters","s","s","descriptionPredicate","validateRequiredParameters","mix","ApplicationCommandOptionType","mix","validateRequiredParameters","ApplicationCommandOptionType","ApplicationCommandOptionType","ApplicationCommandOptionType","s","ChannelType","ChannelType","s","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","s","ApplicationCommandOptionType","s","booleanPredicate","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","ApplicationCommandOptionType","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","numberValidator","s","ApplicationCommandOptionType","mix","ApplicationCommandOptionType","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","minLengthValidator","s","maxLengthValidator","ApplicationCommandOptionType","mix","ApplicationCommandOptionType","ApplicationCommandOptionType","validateRequiredParameters","ApplicationCommandOptionType","mix","validateRequiredParameters","mix","Assertions_exports","validateDMPermission","validateDefaultMemberPermissions","validateDefaultPermission","validateName","validateRequiredParameters","s","namePredicate","s","booleanPredicate","validateDefaultPermission","validateName","validateRequiredParameters","dmPermissionPredicate","validateDMPermission","memberPermissionPredicate","validateDefaultMemberPermissions","validateName","validateDefaultPermission","validateDefaultMemberPermissions","validateDMPermission","validateRequiredParameters"]} \ No newline at end of file +{"version":3,"sources":["../src/messages/embed/Assertions.ts","../src/util/validation.ts","../src/util/normalizeArray.ts","../src/messages/embed/Embed.ts","../src/index.ts","../src/components/Assertions.ts","../src/components/selectMenu/StringSelectMenuOption.ts","../src/components/ActionRow.ts","../src/components/Component.ts","../src/components/Components.ts","../src/components/button/Button.ts","../src/components/selectMenu/ChannelSelectMenu.ts","../src/components/selectMenu/BaseSelectMenu.ts","../src/components/selectMenu/MentionableSelectMenu.ts","../src/components/selectMenu/RoleSelectMenu.ts","../src/components/selectMenu/StringSelectMenu.ts","../src/components/selectMenu/UserSelectMenu.ts","../src/components/textInput/TextInput.ts","../src/components/textInput/Assertions.ts","../src/interactions/modals/Assertions.ts","../src/interactions/modals/Modal.ts","../src/interactions/slashCommands/Assertions.ts","../src/interactions/slashCommands/SlashCommandBuilder.ts","../src/interactions/slashCommands/SlashCommandSubcommands.ts","../src/interactions/slashCommands/mixins/NameAndDescription.ts","../src/interactions/slashCommands/options/attachment.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionBase.ts","../src/interactions/slashCommands/options/boolean.ts","../src/interactions/slashCommands/options/channel.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.ts","../src/interactions/slashCommands/options/integer.ts","../src/interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.ts","../src/interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.ts","../src/interactions/slashCommands/options/mentionable.ts","../src/interactions/slashCommands/options/number.ts","../src/interactions/slashCommands/options/role.ts","../src/interactions/slashCommands/options/string.ts","../src/interactions/slashCommands/options/user.ts","../src/interactions/slashCommands/mixins/SharedSlashCommandOptions.ts","../src/interactions/contextMenuCommands/Assertions.ts","../src/interactions/contextMenuCommands/ContextMenuCommandBuilder.ts","../src/util/componentUtil.ts"],"sourcesContent":["import { s } from '@sapphire/shapeshift';\nimport type { APIEmbedField } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const fieldNamePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(256)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldValuePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(1_024)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const fieldInlinePredicate = s.boolean.optional;\n\nexport const embedFieldPredicate = s\n\t.object({\n\t\tname: fieldNamePredicate,\n\t\tvalue: fieldValuePredicate,\n\t\tinline: fieldInlinePredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const embedFieldsArrayPredicate = embedFieldPredicate.array.setValidationEnabled(isValidationEnabled);\n\nexport const fieldLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateFieldLength(amountAdding: number, fields?: APIEmbedField[]): void {\n\tfieldLengthPredicate.parse((fields?.length ?? 0) + amountAdding);\n}\n\nexport const authorNamePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const imageURLPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'attachment:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const urlPredicate = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:'],\n\t})\n\t.nullish.setValidationEnabled(isValidationEnabled);\n\nexport const embedAuthorPredicate = s\n\t.object({\n\t\tname: authorNamePredicate,\n\t\ticonURL: imageURLPredicate,\n\t\turl: urlPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const RGBPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(255)\n\t.setValidationEnabled(isValidationEnabled);\nexport const colorPredicate = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(0xffffff)\n\t.or(s.tuple([RGBPredicate, RGBPredicate, RGBPredicate]))\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(4_096)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const footerTextPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(2_048)\n\t.nullable.setValidationEnabled(isValidationEnabled);\n\nexport const embedFooterPredicate = s\n\t.object({\n\t\ttext: footerTextPredicate,\n\t\ticonURL: imageURLPredicate,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const timestampPredicate = s.union(s.number, s.date).nullable.setValidationEnabled(isValidationEnabled);\n\nexport const titlePredicate = fieldNamePredicate.nullable.setValidationEnabled(isValidationEnabled);\n","let validate = true;\n\n/**\n * Enables validators.\n *\n * @returns Whether validation is occurring.\n */\nexport function enableValidators() {\n\treturn (validate = true);\n}\n\n/**\n * Disables validators.\n *\n * @returns Whether validation is occurring.\n */\nexport function disableValidators() {\n\treturn (validate = false);\n}\n\n/**\n * Checks whether validation is occurring.\n */\nexport function isValidationEnabled() {\n\treturn validate;\n}\n","/**\n * Normalizes data that is a rest parameter or an array into an array with a depth of 1.\n *\n * @typeParam T - The data that must satisfy {@link RestOrArray}.\n * @param arr - The (possibly variadic) data to normalize\n */\nexport function normalizeArray(arr: RestOrArray): T[] {\n\tif (Array.isArray(arr[0])) return arr[0];\n\treturn arr as T[];\n}\n\n/**\n * Represents data that may be an array or came from a rest parameter.\n *\n * @remarks\n * This type is used throughout builders to ensure both an array and variadic arguments\n * may be used. It is normalized with {@link normalizeArray}.\n */\nexport type RestOrArray = T[] | [T[]];\n","import type { APIEmbed, APIEmbedAuthor, APIEmbedField, APIEmbedFooter, APIEmbedImage } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport {\n\tcolorPredicate,\n\tdescriptionPredicate,\n\tembedAuthorPredicate,\n\tembedFieldsArrayPredicate,\n\tembedFooterPredicate,\n\timageURLPredicate,\n\ttimestampPredicate,\n\ttitlePredicate,\n\turlPredicate,\n\tvalidateFieldLength,\n} from './Assertions.js';\n\n/**\n * A tuple satisfying the RGB color model.\n *\n * @see {@link https://developer.mozilla.org/docs/Glossary/RGB}\n */\nexport type RGBTuple = [red: number, green: number, blue: number];\n\n/**\n * The base icon data typically used in payloads.\n */\nexport interface IconData {\n\t/**\n\t * The URL of the icon.\n\t */\n\ticonURL?: string;\n\t/**\n\t * The proxy URL of the icon.\n\t */\n\tproxyIconURL?: string;\n}\n\n/**\n * Represents the author data of an embed.\n */\nexport type EmbedAuthorData = IconData & Omit;\n\n/**\n * Represents the author options of an embed.\n */\nexport type EmbedAuthorOptions = Omit;\n\n/**\n * Represents the footer data of an embed.\n */\nexport type EmbedFooterData = IconData & Omit;\n\n/**\n * Represents the footer options of an embed.\n */\nexport type EmbedFooterOptions = Omit;\n\n/**\n * Represents the image data of an embed.\n */\nexport interface EmbedImageData extends Omit {\n\t/**\n\t * The proxy URL for the image.\n\t */\n\tproxyURL?: string;\n}\n\n/**\n * A builder that creates API-compatible JSON data for embeds.\n */\nexport class EmbedBuilder {\n\t/**\n\t * The API data associated with this embed.\n\t */\n\tpublic readonly data: APIEmbed;\n\n\t/**\n\t * Creates a new embed from API data.\n\t *\n\t * @param data - The API data to create this embed with\n\t */\n\tpublic constructor(data: APIEmbed = {}) {\n\t\tthis.data = { ...data };\n\t\tif (data.timestamp) this.data.timestamp = new Date(data.timestamp).toISOString();\n\t}\n\n\t/**\n\t * Appends fields to the embed.\n\t *\n\t * @remarks\n\t * This method accepts either an array of fields or a variable number of field parameters.\n\t * The maximum amount of fields that can be added is 25.\n\t * @example\n\t * Using an array:\n\t * ```ts\n\t * const fields: APIEmbedField[] = ...;\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(fields);\n\t * ```\n\t * @example\n\t * Using rest parameters (variadic):\n\t * ```ts\n\t * const embed = new EmbedBuilder()\n\t * \t.addFields(\n\t * \t\t{ name: 'Field 1', value: 'Value 1' },\n\t * \t\t{ name: 'Field 2', value: 'Value 2' },\n\t * \t);\n\t * ```\n\t * @param fields - The fields to add\n\t */\n\tpublic addFields(...fields: RestOrArray): this {\n\t\tconst normalizedFields = normalizeArray(fields);\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(normalizedFields.length, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(normalizedFields);\n\n\t\tif (this.data.fields) this.data.fields.push(...normalizedFields);\n\t\telse this.data.fields = normalizedFields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts fields for this embed.\n\t *\n\t * @remarks\n\t * This method behaves similarly\n\t * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice | Array.prototype.splice()}.\n\t * The maximum amount of fields that can be added is 25.\n\t *\n\t * It's useful for modifying and adjusting order of the already-existing fields of an embed.\n\t * @example\n\t * Remove the first field:\n\t * ```ts\n\t * embed.spliceFields(0, 1);\n\t * ```\n\t * @example\n\t * Remove the first n fields:\n\t * ```ts\n\t * const n = 4;\n\t * embed.spliceFields(0, n);\n\t * ```\n\t * @example\n\t * Remove the last field:\n\t * ```ts\n\t * embed.spliceFields(-1, 1);\n\t * ```\n\t * @param index - The index to start at\n\t * @param deleteCount - The number of fields to remove\n\t * @param fields - The replacing field objects\n\t */\n\tpublic spliceFields(index: number, deleteCount: number, ...fields: APIEmbedField[]): this {\n\t\t// Ensure adding these fields won't exceed the 25 field limit\n\t\tvalidateFieldLength(fields.length - deleteCount, this.data.fields);\n\n\t\t// Data assertions\n\t\tembedFieldsArrayPredicate.parse(fields);\n\t\tif (this.data.fields) this.data.fields.splice(index, deleteCount, ...fields);\n\t\telse this.data.fields = fields;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the fields for this embed.\n\t *\n\t * @remarks\n\t * This method is an alias for {@link EmbedBuilder.spliceFields}. More specifically,\n\t * it splices the entire array of fields, replacing them with the provided fields.\n\t *\n\t * You can set a maximum of 25 fields.\n\t * @param fields - The fields to set\n\t */\n\tpublic setFields(...fields: RestOrArray) {\n\t\tthis.spliceFields(0, this.data.fields?.length ?? 0, ...normalizeArray(fields));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the author of this embed.\n\t *\n\t * @param options - The options to use\n\t */\n\n\tpublic setAuthor(options: EmbedAuthorOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.author = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedAuthorPredicate.parse(options);\n\n\t\tthis.data.author = { name: options.name, url: options.url, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the color of this embed.\n\t *\n\t * @param color - The color to use\n\t */\n\tpublic setColor(color: RGBTuple | number | null): this {\n\t\t// Data assertions\n\t\tcolorPredicate.parse(color);\n\n\t\tif (Array.isArray(color)) {\n\t\t\tconst [red, green, blue] = color;\n\t\t\tthis.data.color = (red << 16) + (green << 8) + blue;\n\t\t\treturn this;\n\t\t}\n\n\t\tthis.data.color = color ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this embed.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string | null): this {\n\t\t// Data assertions\n\t\tdescriptionPredicate.parse(description);\n\n\t\tthis.data.description = description ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the footer of this embed.\n\t *\n\t * @param options - The footer to use\n\t */\n\tpublic setFooter(options: EmbedFooterOptions | null): this {\n\t\tif (options === null) {\n\t\t\tthis.data.footer = undefined;\n\t\t\treturn this;\n\t\t}\n\n\t\t// Data assertions\n\t\tembedFooterPredicate.parse(options);\n\n\t\tthis.data.footer = { text: options.text, icon_url: options.iconURL };\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the image of this embed.\n\t *\n\t * @param url - The image URL to use\n\t */\n\tpublic setImage(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.image = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the thumbnail of this embed.\n\t *\n\t * @param url - The thumbnail URL to use\n\t */\n\tpublic setThumbnail(url: string | null): this {\n\t\t// Data assertions\n\t\timageURLPredicate.parse(url);\n\n\t\tthis.data.thumbnail = url ? { url } : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the timestamp of this embed.\n\t *\n\t * @param timestamp - The timestamp or date to use\n\t */\n\tpublic setTimestamp(timestamp: Date | number | null = Date.now()): this {\n\t\t// Data assertions\n\t\ttimestampPredicate.parse(timestamp);\n\n\t\tthis.data.timestamp = timestamp ? new Date(timestamp).toISOString() : undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the title for this embed.\n\t *\n\t * @param title - The title to use\n\t */\n\tpublic setTitle(title: string | null): this {\n\t\t// Data assertions\n\t\ttitlePredicate.parse(title);\n\n\t\tthis.data.title = title ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL of this embed.\n\t *\n\t * @param url - The URL to use\n\t */\n\tpublic setURL(url: string | null): this {\n\t\t// Data assertions\n\t\turlPredicate.parse(url);\n\n\t\tthis.data.url = url ?? undefined;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIEmbed {\n\t\treturn { ...this.data };\n\t}\n}\n","export * as EmbedAssertions from './messages/embed/Assertions.js';\nexport * from './messages/embed/Embed.js';\n// TODO: Consider removing this dep in the next major version\nexport * from '@discordjs/formatters';\n\nexport * as ComponentAssertions from './components/Assertions.js';\nexport * from './components/ActionRow.js';\nexport * from './components/button/Button.js';\nexport * from './components/Component.js';\nexport * from './components/Components.js';\nexport * from './components/textInput/TextInput.js';\nexport * as TextInputAssertions from './components/textInput/Assertions.js';\nexport * from './interactions/modals/Modal.js';\nexport * as ModalAssertions from './interactions/modals/Assertions.js';\n\nexport * from './components/selectMenu/BaseSelectMenu.js';\nexport * from './components/selectMenu/ChannelSelectMenu.js';\nexport * from './components/selectMenu/MentionableSelectMenu.js';\nexport * from './components/selectMenu/RoleSelectMenu.js';\nexport * from './components/selectMenu/StringSelectMenu.js';\n// TODO: Remove those aliases in v2\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuBuilder} instead.\n\t */\n\tStringSelectMenuBuilder as SelectMenuBuilder,\n} from './components/selectMenu/StringSelectMenu.js';\nexport {\n\t/**\n\t * @deprecated Will be removed in the next major version, use {@link StringSelectMenuOptionBuilder} instead.\n\t */\n\tStringSelectMenuOptionBuilder as SelectMenuOptionBuilder,\n} from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/StringSelectMenuOption.js';\nexport * from './components/selectMenu/UserSelectMenu.js';\n\nexport * as SlashCommandAssertions from './interactions/slashCommands/Assertions.js';\nexport * from './interactions/slashCommands/SlashCommandBuilder.js';\nexport * from './interactions/slashCommands/SlashCommandSubcommands.js';\nexport * from './interactions/slashCommands/options/boolean.js';\nexport * from './interactions/slashCommands/options/channel.js';\nexport * from './interactions/slashCommands/options/integer.js';\nexport * from './interactions/slashCommands/options/mentionable.js';\nexport * from './interactions/slashCommands/options/number.js';\nexport * from './interactions/slashCommands/options/role.js';\nexport * from './interactions/slashCommands/options/attachment.js';\nexport * from './interactions/slashCommands/options/string.js';\nexport * from './interactions/slashCommands/options/user.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionBase.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionChannelTypesMixin.js';\nexport * from './interactions/slashCommands/mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\nexport * from './interactions/slashCommands/mixins/NameAndDescription.js';\nexport * from './interactions/slashCommands/mixins/SharedSlashCommandOptions.js';\n\nexport * as ContextMenuCommandAssertions from './interactions/contextMenuCommands/Assertions.js';\nexport * from './interactions/contextMenuCommands/ContextMenuCommandBuilder.js';\n\nexport * from './util/componentUtil.js';\nexport * from './util/normalizeArray.js';\nexport * from './util/validation.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/builders#readme | @discordjs/builders} version\n * that you are currently using.\n *\n * @privateRemarks This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild.\n */\nexport const version = '1.6.3' as string;\n","import { s } from '@sapphire/shapeshift';\nimport { ButtonStyle, ChannelType, type APIMessageComponentEmoji } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../util/validation.js';\nimport { StringSelectMenuOptionBuilder } from './selectMenu/StringSelectMenuOption.js';\n\nexport const customIdValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const emojiValidator = s\n\t.object({\n\t\tid: s.string,\n\t\tname: s.string,\n\t\tanimated: s.boolean,\n\t})\n\t.partial.strict.setValidationEnabled(isValidationEnabled);\n\nexport const disabledValidator = s.boolean;\n\nexport const buttonLabelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(80)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const buttonStyleValidator = s.nativeEnum(ButtonStyle);\n\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(150).setValidationEnabled(isValidationEnabled);\nexport const minMaxValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const labelValueDescriptionValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const jsonOptionValidator = s\n\t.object({\n\t\tlabel: labelValueDescriptionValidator,\n\t\tvalue: labelValueDescriptionValidator,\n\t\tdescription: labelValueDescriptionValidator.optional,\n\t\temoji: emojiValidator.optional,\n\t\tdefault: s.boolean.optional,\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport const optionValidator = s.instance(StringSelectMenuOptionBuilder).setValidationEnabled(isValidationEnabled);\n\nexport const optionsValidator = optionValidator.array\n\t.lengthGreaterThanOrEqual(0)\n\t.setValidationEnabled(isValidationEnabled);\nexport const optionsLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(25)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredSelectMenuParameters(options: StringSelectMenuOptionBuilder[], customId?: string) {\n\tcustomIdValidator.parse(customId);\n\toptionsValidator.parse(options);\n}\n\nexport const defaultValidator = s.boolean;\n\nexport function validateRequiredSelectMenuOptionParameters(label?: string, value?: string) {\n\tlabelValueDescriptionValidator.parse(label);\n\tlabelValueDescriptionValidator.parse(value);\n}\n\nexport const channelTypesValidator = s.nativeEnum(ChannelType).array.setValidationEnabled(isValidationEnabled);\n\nexport const urlValidator = s.string\n\t.url({\n\t\tallowedProtocols: ['http:', 'https:', 'discord:'],\n\t})\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredButtonParameters(\n\tstyle?: ButtonStyle,\n\tlabel?: string,\n\temoji?: APIMessageComponentEmoji,\n\tcustomId?: string,\n\turl?: string,\n) {\n\tif (url && customId) {\n\t\tthrow new RangeError('URL and custom id are mutually exclusive');\n\t}\n\n\tif (!label && !emoji) {\n\t\tthrow new RangeError('Buttons must have a label and/or an emoji');\n\t}\n\n\tif (style === ButtonStyle.Link) {\n\t\tif (!url) {\n\t\t\tthrow new RangeError('Link buttons must have a url');\n\t\t}\n\t} else if (url) {\n\t\tthrow new RangeError('Non-link buttons cannot have a url');\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type { APIMessageComponentEmoji, APISelectMenuOption } from 'discord-api-types/v10';\nimport {\n\tdefaultValidator,\n\temojiValidator,\n\tlabelValueDescriptionValidator,\n\tvalidateRequiredSelectMenuOptionParameters,\n} from '../Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for string select menu options.\n */\nexport class StringSelectMenuOptionBuilder implements JSONEncodable {\n\t/**\n\t * Creates a new string select menu option from API data.\n\t *\n\t * @param data - The API data to create this string select menu option with\n\t * @example\n\t * Creating a string select menu option from an API data object:\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tlabel: 'catchy label',\n\t * \tvalue: '1',\n\t * });\n\t * ```\n\t * @example\n\t * Creating a string select menu option using setters and API data:\n\t * ```ts\n\t * const selectMenuOption = new SelectMenuOptionBuilder({\n\t * \tdefault: true,\n\t * \tvalue: '1',\n\t * })\n\t * \t.setLabel('woah');\n\t * ```\n\t */\n\tpublic constructor(public data: Partial = {}) {}\n\n\t/**\n\t * Sets the label for this option.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValueDescriptionValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value for this option.\n\t *\n\t * @param value - The value to use\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = labelValueDescriptionValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description for this option.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string) {\n\t\tthis.data.description = labelValueDescriptionValidator.parse(description);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this option is selected by default.\n\t *\n\t * @param isDefault - Whether this option is selected by default\n\t */\n\tpublic setDefault(isDefault = true) {\n\t\tthis.data.default = defaultValidator.parse(isDefault);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display for this option.\n\t *\n\t * @param emoji - The emoji to use\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic toJSON(): APISelectMenuOption {\n\t\tvalidateRequiredSelectMenuOptionParameters(this.data.label, this.data.value);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APISelectMenuOption;\n\t}\n}\n","/* eslint-disable jsdoc/check-param-names */\n\nimport {\n\ttype APIActionRowComponent,\n\tComponentType,\n\ttype APIMessageActionRowComponent,\n\ttype APIModalActionRowComponent,\n\ttype APIActionRowComponentTypes,\n} from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../util/normalizeArray.js';\nimport { ComponentBuilder } from './Component.js';\nimport { createComponentBuilder } from './Components.js';\nimport type { ButtonBuilder } from './button/Button.js';\nimport type { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport type { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport type { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport type { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport type { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport type { TextInputBuilder } from './textInput/TextInput.js';\n\n/**\n * The builders that may be used for messages.\n */\nexport type MessageComponentBuilder =\n\t| ActionRowBuilder\n\t| MessageActionRowComponentBuilder;\n\n/**\n * The builders that may be used for modals.\n */\nexport type ModalComponentBuilder = ActionRowBuilder | ModalActionRowComponentBuilder;\n\n/**\n * The builders that may be used within an action row for messages.\n */\nexport type MessageActionRowComponentBuilder =\n\t| ButtonBuilder\n\t| ChannelSelectMenuBuilder\n\t| MentionableSelectMenuBuilder\n\t| RoleSelectMenuBuilder\n\t| StringSelectMenuBuilder\n\t| UserSelectMenuBuilder;\n\n/**\n * The builders that may be used within an action row for modals.\n */\nexport type ModalActionRowComponentBuilder = TextInputBuilder;\n\n/**\n * Any builder.\n */\nexport type AnyComponentBuilder = MessageActionRowComponentBuilder | ModalActionRowComponentBuilder;\n\n/**\n * A builder that creates API-compatible JSON data for action rows.\n *\n * @typeParam T - The types of components this action row holds\n */\nexport class ActionRowBuilder extends ComponentBuilder<\n\tAPIActionRowComponent\n> {\n\t/**\n\t * The components within this action row.\n\t */\n\tpublic readonly components: T[];\n\n\t/**\n\t * Creates a new action row from API data.\n\t *\n\t * @param data - The API data to create this action row with\n\t * @example\n\t * Creating an action row from an API data object:\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Type something\",\n\t * \t\t\tstyle: TextInputStyle.Short,\n\t * \t\t\ttype: ComponentType.TextInput,\n\t * \t\t},\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating an action row using setters and API data:\n\t * ```ts\n\t * const actionRow = new ActionRowBuilder({\n\t * \tcomponents: [\n\t * \t\t{\n\t * \t\t\tcustom_id: \"custom id\",\n\t * \t\t\tlabel: \"Click me\",\n\t * \t\t\tstyle: ButtonStyle.Primary,\n\t * \t\t\ttype: ComponentType.Button,\n\t * \t\t},\n\t * \t],\n\t * })\n\t * \t.addComponents(button2, button3);\n\t * ```\n\t */\n\tpublic constructor({ components, ...data }: Partial> = {}) {\n\t\tsuper({ type: ComponentType.ActionRow, ...data });\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ?? []) as T[];\n\t}\n\n\t/**\n\t * Adds components to this action row.\n\t *\n\t * @param components - The components to add\n\t */\n\tpublic addComponents(...components: RestOrArray) {\n\t\tthis.components.push(...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets components for this action row.\n\t *\n\t * @param components - The components to set\n\t */\n\tpublic setComponents(...components: RestOrArray) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIActionRowComponent> {\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIActionRowComponent>;\n\t}\n}\n","import type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIActionRowComponentTypes,\n\tAPIBaseComponent,\n\tComponentType,\n} from 'discord-api-types/v10';\n\n/**\n * Any action row component data represented as an object.\n */\nexport type AnyAPIActionRowComponent = APIActionRowComponent | APIActionRowComponentTypes;\n\n/**\n * The base component builder that contains common symbols for all sorts of components.\n *\n * @typeParam DataType - The type of internal API data that is stored within the component\n */\nexport abstract class ComponentBuilder<\n\tDataType extends Partial> = APIBaseComponent,\n> implements JSONEncodable\n{\n\t/**\n\t * The API data associated with this component.\n\t */\n\tpublic readonly data: Partial;\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic abstract toJSON(): AnyAPIActionRowComponent;\n\n\t/**\n\t * Constructs a new kind of component.\n\t *\n\t * @param data - The data to construct a component out of\n\t */\n\tpublic constructor(data: Partial) {\n\t\tthis.data = data;\n\t}\n}\n","import { ComponentType, type APIMessageComponent, type APIModalComponent } from 'discord-api-types/v10';\nimport {\n\tActionRowBuilder,\n\ttype AnyComponentBuilder,\n\ttype MessageComponentBuilder,\n\ttype ModalComponentBuilder,\n} from './ActionRow.js';\nimport { ComponentBuilder } from './Component.js';\nimport { ButtonBuilder } from './button/Button.js';\nimport { ChannelSelectMenuBuilder } from './selectMenu/ChannelSelectMenu.js';\nimport { MentionableSelectMenuBuilder } from './selectMenu/MentionableSelectMenu.js';\nimport { RoleSelectMenuBuilder } from './selectMenu/RoleSelectMenu.js';\nimport { StringSelectMenuBuilder } from './selectMenu/StringSelectMenu.js';\nimport { UserSelectMenuBuilder } from './selectMenu/UserSelectMenu.js';\nimport { TextInputBuilder } from './textInput/TextInput.js';\n\n/**\n * Components here are mapped to their respective builder.\n */\nexport interface MappedComponentTypes {\n\t/**\n\t * The action row component type is associated with an {@link ActionRowBuilder}.\n\t */\n\t[ComponentType.ActionRow]: ActionRowBuilder;\n\t/**\n\t * The button component type is associated with an {@link ButtonBuilder}.\n\t */\n\t[ComponentType.Button]: ButtonBuilder;\n\t/**\n\t * The string select component type is associated with an {@link StringSelectMenuBuilder}.\n\t */\n\t[ComponentType.StringSelect]: StringSelectMenuBuilder;\n\t/**\n\t * The text inpiut component type is associated with an {@link TextInputBuilder}.\n\t */\n\t[ComponentType.TextInput]: TextInputBuilder;\n\t/**\n\t * The user select component type is associated with an {@link UserSelectMenuBuilder}.\n\t */\n\t[ComponentType.UserSelect]: UserSelectMenuBuilder;\n\t/**\n\t * The role select component type is associated with an {@link RoleSelectMenuBuilder}.\n\t */\n\t[ComponentType.RoleSelect]: RoleSelectMenuBuilder;\n\t/**\n\t * The mentionable select component type is associated with an {@link MentionableSelectMenuBuilder}.\n\t */\n\t[ComponentType.MentionableSelect]: MentionableSelectMenuBuilder;\n\t/**\n\t * The channel select component type is associated with an {@link ChannelSelectMenuBuilder}.\n\t */\n\t[ComponentType.ChannelSelect]: ChannelSelectMenuBuilder;\n}\n\n/**\n * Factory for creating components from API data.\n *\n * @typeParam T - The type of component to use\n * @param data - The API data to transform to a component class\n */\nexport function createComponentBuilder(\n\t// eslint-disable-next-line @typescript-eslint/sort-type-union-intersection-members\n\tdata: (APIModalComponent | APIMessageComponent) & { type: T },\n): MappedComponentTypes[T];\n\n/**\n * Factory for creating components from API data.\n *\n * @typeParam C - The type of component to use\n * @param data - The API data to transform to a component class\n */\nexport function createComponentBuilder(data: C): C;\n\nexport function createComponentBuilder(\n\tdata: APIMessageComponent | APIModalComponent | MessageComponentBuilder,\n): ComponentBuilder {\n\tif (data instanceof ComponentBuilder) {\n\t\treturn data;\n\t}\n\n\tswitch (data.type) {\n\t\tcase ComponentType.ActionRow:\n\t\t\treturn new ActionRowBuilder(data);\n\t\tcase ComponentType.Button:\n\t\t\treturn new ButtonBuilder(data);\n\t\tcase ComponentType.StringSelect:\n\t\t\treturn new StringSelectMenuBuilder(data);\n\t\tcase ComponentType.TextInput:\n\t\t\treturn new TextInputBuilder(data);\n\t\tcase ComponentType.UserSelect:\n\t\t\treturn new UserSelectMenuBuilder(data);\n\t\tcase ComponentType.RoleSelect:\n\t\t\treturn new RoleSelectMenuBuilder(data);\n\t\tcase ComponentType.MentionableSelect:\n\t\t\treturn new MentionableSelectMenuBuilder(data);\n\t\tcase ComponentType.ChannelSelect:\n\t\t\treturn new ChannelSelectMenuBuilder(data);\n\t\tdefault:\n\t\t\t// @ts-expect-error This case can still occur if we get a newer unsupported component type\n\t\t\tthrow new Error(`Cannot properly serialize component type: ${data.type}`);\n\t}\n}\n","import {\n\tComponentType,\n\ttype APIMessageComponentEmoji,\n\ttype APIButtonComponent,\n\ttype APIButtonComponentWithURL,\n\ttype APIButtonComponentWithCustomId,\n\ttype ButtonStyle,\n} from 'discord-api-types/v10';\nimport {\n\tbuttonLabelValidator,\n\tbuttonStyleValidator,\n\tcustomIdValidator,\n\tdisabledValidator,\n\temojiValidator,\n\turlValidator,\n\tvalidateRequiredButtonParameters,\n} from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\n/**\n * A builder that creates API-compatible JSON data for buttons.\n */\nexport class ButtonBuilder extends ComponentBuilder {\n\t/**\n\t * Creates a new button from API data.\n\t *\n\t * @param data - The API data to create this button with\n\t * @example\n\t * Creating a button from an API data object:\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tcustom_id: 'a cool button',\n\t * \tstyle: ButtonStyle.Primary,\n\t * \tlabel: 'Click Me',\n\t * \temoji: {\n\t * \t\tname: 'smile',\n\t * \t\tid: '123456789012345678',\n\t * \t},\n\t * });\n\t * ```\n\t * @example\n\t * Creating a button using setters and API data:\n\t * ```ts\n\t * const button = new ButtonBuilder({\n\t * \tstyle: ButtonStyle.Secondary,\n\t * \tlabel: 'Click Me',\n\t * })\n\t * \t.setEmoji({ name: 'πŸ™‚' })\n\t * \t.setCustomId('another cool button');\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ type: ComponentType.Button, ...data });\n\t}\n\n\t/**\n\t * Sets the style of this button.\n\t *\n\t * @param style - The style to use\n\t */\n\tpublic setStyle(style: ButtonStyle) {\n\t\tthis.data.style = buttonStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the URL for this button.\n\t *\n\t * @remarks\n\t * This method is only available to buttons using the `Link` button style.\n\t * Only three types of URL schemes are currently supported: `https://`, `http://`, and `discord://`.\n\t * @param url - The URL to use\n\t */\n\tpublic setURL(url: string) {\n\t\t(this.data as APIButtonComponentWithURL).url = urlValidator.parse(url);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this button.\n\t *\n\t * @remarks\n\t * This method is only applicable to buttons that are not using the `Link` button style.\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\t(this.data as APIButtonComponentWithCustomId).custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the emoji to display on this button.\n\t *\n\t * @param emoji - The emoji to use\n\t */\n\tpublic setEmoji(emoji: APIMessageComponentEmoji) {\n\t\tthis.data.emoji = emojiValidator.parse(emoji);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this button is disabled.\n\t *\n\t * @param disabled - Whether to disable this button\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this button.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = buttonLabelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIButtonComponent {\n\t\tvalidateRequiredButtonParameters(\n\t\t\tthis.data.style,\n\t\t\tthis.data.label,\n\t\t\tthis.data.emoji,\n\t\t\t(this.data as APIButtonComponentWithCustomId).custom_id,\n\t\t\t(this.data as APIButtonComponentWithURL).url,\n\t\t);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIButtonComponent;\n\t}\n}\n","import type { APIChannelSelectComponent, ChannelType } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { channelTypesValidator, customIdValidator } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for channel select menus.\n */\nexport class ChannelSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new ChannelSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.addChannelTypes(ChannelType.GuildText, ChannelType.GuildAnnouncement)\n\t * \t.setMinValues(2);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.ChannelSelect });\n\t}\n\n\t/**\n\t * Adds channel types to this select menu.\n\t *\n\t * @param types - The channel types to use\n\t */\n\tpublic addChannelTypes(...types: RestOrArray) {\n\t\tconst normalizedTypes = normalizeArray(types);\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.push(...channelTypesValidator.parse(normalizedTypes));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets channel types for this select menu.\n\t *\n\t * @param types - The channel types to use\n\t */\n\tpublic setChannelTypes(...types: RestOrArray) {\n\t\tconst normalizedTypes = normalizeArray(types);\n\t\tthis.data.channel_types ??= [];\n\t\tthis.data.channel_types.splice(0, this.data.channel_types.length, ...channelTypesValidator.parse(normalizedTypes));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIChannelSelectComponent {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APIChannelSelectComponent;\n\t}\n}\n","import type { APISelectMenuComponent } from 'discord-api-types/v10';\nimport { customIdValidator, disabledValidator, minMaxValidator, placeholderValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\n\n/**\n * The base select menu builder that contains common symbols for select menu builders.\n *\n * @typeParam SelectMenuType - The type of select menu this would be instantiated for.\n */\nexport abstract class BaseSelectMenuBuilder<\n\tSelectMenuType extends APISelectMenuComponent,\n> extends ComponentBuilder {\n\t/**\n\t * Sets the placeholder for this select menu.\n\t *\n\t * @param placeholder - The placeholder to use\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum values that must be selected in the select menu.\n\t *\n\t * @param minValues - The minimum values that must be selected\n\t */\n\tpublic setMinValues(minValues: number) {\n\t\tthis.data.min_values = minMaxValidator.parse(minValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum values that must be selected in the select menu.\n\t *\n\t * @param maxValues - The maximum values that must be selected\n\t */\n\tpublic setMaxValues(maxValues: number) {\n\t\tthis.data.max_values = minMaxValidator.parse(maxValues);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id for this select menu.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this select menu is disabled.\n\t *\n\t * @param disabled - Whether this select menu is disabled\n\t */\n\tpublic setDisabled(disabled = true) {\n\t\tthis.data.disabled = disabledValidator.parse(disabled);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): SelectMenuType {\n\t\tcustomIdValidator.parse(this.data.custom_id);\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as SelectMenuType;\n\t}\n}\n","import type { APIMentionableSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for mentionable select menus.\n */\nexport class MentionableSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new MentionableSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.MentionableSelect });\n\t}\n}\n","import type { APIRoleSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for role select menus.\n */\nexport class RoleSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new RoleSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.RoleSelect });\n\t}\n}\n","import { ComponentType } from 'discord-api-types/v10';\nimport type { APIStringSelectComponent, APISelectMenuOption } from 'discord-api-types/v10';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { jsonOptionValidator, optionsLengthValidator, validateRequiredSelectMenuParameters } from '../Assertions.js';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\nimport { StringSelectMenuOptionBuilder } from './StringSelectMenuOption.js';\n\n/**\n * A builder that creates API-compatible JSON data for string select menus.\n */\nexport class StringSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * The options within this select menu.\n\t */\n\tpublic readonly options: StringSelectMenuOptionBuilder[];\n\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * \toptions: [\n\t * \t\t{ label: 'option 1', value: '1' },\n\t * \t\t{ label: 'option 2', value: '2' },\n\t * \t\t{ label: 'option 3', value: '3' },\n\t * \t],\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new StringSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1)\n\t * \t.addOptions({\n\t * \t\tlabel: 'Catchy',\n\t * \t\tvalue: 'catch',\n\t * \t});\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tconst { options, ...initData } = data ?? {};\n\t\tsuper({ ...initData, type: ComponentType.StringSelect });\n\t\tthis.options = options?.map((option: APISelectMenuOption) => new StringSelectMenuOptionBuilder(option)) ?? [];\n\t}\n\n\t/**\n\t * Adds options to this select menu.\n\t *\n\t * @param options - The options to add\n\t */\n\tpublic addOptions(...options: RestOrArray) {\n\t\tconst normalizedOptions = normalizeArray(options);\n\t\toptionsLengthValidator.parse(this.options.length + normalizedOptions.length);\n\t\tthis.options.push(\n\t\t\t...normalizedOptions.map((normalizedOption) =>\n\t\t\t\tnormalizedOption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? normalizedOption\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the options for this select menu.\n\t *\n\t * @param options - The options to set\n\t */\n\tpublic setOptions(...options: RestOrArray) {\n\t\treturn this.spliceOptions(0, this.options.length, ...options);\n\t}\n\n\t/**\n\t * Removes, replaces, or inserts options for this select menu.\n\t *\n\t * @remarks\n\t * This method behaves similarly\n\t * to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice | Array.prototype.splice()}.\n\t * It's useful for modifying and adjusting the order of existing options.\n\t * @example\n\t * Remove the first option:\n\t * ```ts\n\t * selectMenu.spliceOptions(0, 1);\n\t * ```\n\t * @example\n\t * Remove the first n option:\n\t * ```ts\n\t * const n = 4;\n\t * selectMenu.spliceOptions(0, n);\n\t * ```\n\t * @example\n\t * Remove the last option:\n\t * ```ts\n\t * selectMenu.spliceOptions(-1, 1);\n\t * ```\n\t * @param index - The index to start at\n\t * @param deleteCount - The number of options to remove\n\t * @param options - The replacing option objects or builders\n\t */\n\tpublic spliceOptions(\n\t\tindex: number,\n\t\tdeleteCount: number,\n\t\t...options: RestOrArray\n\t) {\n\t\tconst normalizedOptions = normalizeArray(options);\n\n\t\tconst clone = [...this.options];\n\n\t\tclone.splice(\n\t\t\tindex,\n\t\t\tdeleteCount,\n\t\t\t...normalizedOptions.map((normalizedOption) =>\n\t\t\t\tnormalizedOption instanceof StringSelectMenuOptionBuilder\n\t\t\t\t\t? normalizedOption\n\t\t\t\t\t: new StringSelectMenuOptionBuilder(jsonOptionValidator.parse(normalizedOption)),\n\t\t\t),\n\t\t);\n\n\t\toptionsLengthValidator.parse(clone.length);\n\t\tthis.options.splice(0, this.options.length, ...clone);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc BaseSelectMenuBuilder.toJSON}\n\t */\n\tpublic override toJSON(): APIStringSelectComponent {\n\t\tvalidateRequiredSelectMenuParameters(this.options, this.data.custom_id);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t} as APIStringSelectComponent;\n\t}\n}\n","import type { APIUserSelectComponent } from 'discord-api-types/v10';\nimport { ComponentType } from 'discord-api-types/v10';\nimport { BaseSelectMenuBuilder } from './BaseSelectMenu.js';\n\n/**\n * A builder that creates API-compatible JSON data for user select menus.\n */\nexport class UserSelectMenuBuilder extends BaseSelectMenuBuilder {\n\t/**\n\t * Creates a new select menu from API data.\n\t *\n\t * @param data - The API data to create this select menu with\n\t * @example\n\t * Creating a select menu from an API data object:\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tplaceholder: 'select an option',\n\t * \tmax_values: 2,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu using setters and API data:\n\t * ```ts\n\t * const selectMenu = new UserSelectMenuBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * })\n\t * \t.setMinValues(1);\n\t * ```\n\t */\n\tpublic constructor(data?: Partial) {\n\t\tsuper({ ...data, type: ComponentType.UserSelect });\n\t}\n}\n","import { isJSONEncodable, type Equatable, type JSONEncodable } from '@discordjs/util';\nimport { ComponentType, type TextInputStyle, type APITextInputComponent } from 'discord-api-types/v10';\nimport isEqual from 'fast-deep-equal';\nimport { customIdValidator } from '../Assertions.js';\nimport { ComponentBuilder } from '../Component.js';\nimport {\n\tmaxLengthValidator,\n\tminLengthValidator,\n\tplaceholderValidator,\n\trequiredValidator,\n\tvalueValidator,\n\tvalidateRequiredParameters,\n\tlabelValidator,\n\ttextInputStyleValidator,\n} from './Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for text inputs.\n */\nexport class TextInputBuilder\n\textends ComponentBuilder\n\timplements Equatable>\n{\n\t/**\n\t * Creates a new text input from API data.\n\t *\n\t * @param data - The API data to create this text input with\n\t * @example\n\t * Creating a select menu option from an API data object:\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tcustom_id: 'a cool select menu',\n\t * \tlabel: 'Type something',\n\t * \tstyle: TextInputStyle.Short,\n\t * });\n\t * ```\n\t * @example\n\t * Creating a select menu option using setters and API data:\n\t * ```ts\n\t * const textInput = new TextInputBuilder({\n\t * \tlabel: 'Type something else',\n\t * })\n\t * \t.setCustomId('woah')\n\t * \t.setStyle(TextInputStyle.Paragraph);\n\t * ```\n\t */\n\tpublic constructor(data?: APITextInputComponent & { type?: ComponentType.TextInput }) {\n\t\tsuper({ type: ComponentType.TextInput, ...data });\n\t}\n\n\t/**\n\t * Sets the custom id for this text input.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the label for this text input.\n\t *\n\t * @param label - The label to use\n\t */\n\tpublic setLabel(label: string) {\n\t\tthis.data.label = labelValidator.parse(label);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the style for this text input.\n\t *\n\t * @param style - The style to use\n\t */\n\tpublic setStyle(style: TextInputStyle) {\n\t\tthis.data.style = textInputStyleValidator.parse(style);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of text for this text input.\n\t *\n\t * @param minLength - The minimum length of text for this text input\n\t */\n\tpublic setMinLength(minLength: number) {\n\t\tthis.data.min_length = minLengthValidator.parse(minLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the maximum length of text for this text input.\n\t *\n\t * @param maxLength - The maximum length of text for this text input\n\t */\n\tpublic setMaxLength(maxLength: number) {\n\t\tthis.data.max_length = maxLengthValidator.parse(maxLength);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the placeholder for this text input.\n\t *\n\t * @param placeholder - The placeholder to use\n\t */\n\tpublic setPlaceholder(placeholder: string) {\n\t\tthis.data.placeholder = placeholderValidator.parse(placeholder);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the value for this text input.\n\t *\n\t * @param value - The value to use\n\t */\n\tpublic setValue(value: string) {\n\t\tthis.data.value = valueValidator.parse(value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this text input is required.\n\t *\n\t * @param required - Whether this text input is required\n\t */\n\tpublic setRequired(required = true) {\n\t\tthis.data.required = requiredValidator.parse(required);\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APITextInputComponent {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.style, this.data.label);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t} as APITextInputComponent;\n\t}\n\n\t/**\n\t * {@inheritDoc Equatable.equals}\n\t */\n\tpublic equals(other: APITextInputComponent | JSONEncodable): boolean {\n\t\tif (isJSONEncodable(other)) {\n\t\t\treturn isEqual(other.toJSON(), this.data);\n\t\t}\n\n\t\treturn isEqual(other, this.data);\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { TextInputStyle } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport { customIdValidator } from '../Assertions.js';\n\nexport const textInputStyleValidator = s.nativeEnum(TextInputStyle);\nexport const minLengthValidator = s.number.int\n\t.greaterThanOrEqual(0)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const maxLengthValidator = s.number.int\n\t.greaterThanOrEqual(1)\n\t.lessThanOrEqual(4_000)\n\t.setValidationEnabled(isValidationEnabled);\nexport const requiredValidator = s.boolean;\nexport const valueValidator = s.string.lengthLessThanOrEqual(4_000).setValidationEnabled(isValidationEnabled);\nexport const placeholderValidator = s.string.lengthLessThanOrEqual(100).setValidationEnabled(isValidationEnabled);\nexport const labelValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(customId?: string, style?: TextInputStyle, label?: string) {\n\tcustomIdValidator.parse(customId);\n\ttextInputStyleValidator.parse(style);\n\tlabelValidator.parse(label);\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { isValidationEnabled } from '../../util/validation.js';\n\nexport const titleValidator = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(45)\n\t.setValidationEnabled(isValidationEnabled);\nexport const componentsValidator = s\n\t.instance(ActionRowBuilder)\n\t.array.lengthGreaterThanOrEqual(1)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateRequiredParameters(\n\tcustomId?: string,\n\ttitle?: string,\n\tcomponents?: ActionRowBuilder[],\n) {\n\tcustomIdValidator.parse(customId);\n\ttitleValidator.parse(title);\n\tcomponentsValidator.parse(components);\n}\n","/* eslint-disable jsdoc/check-param-names */\n\nimport type { JSONEncodable } from '@discordjs/util';\nimport type {\n\tAPIActionRowComponent,\n\tAPIModalActionRowComponent,\n\tAPIModalInteractionResponseCallbackData,\n} from 'discord-api-types/v10';\nimport { ActionRowBuilder, type ModalActionRowComponentBuilder } from '../../components/ActionRow.js';\nimport { customIdValidator } from '../../components/Assertions.js';\nimport { createComponentBuilder } from '../../components/Components.js';\nimport { normalizeArray, type RestOrArray } from '../../util/normalizeArray.js';\nimport { titleValidator, validateRequiredParameters } from './Assertions.js';\n\n/**\n * A builder that creates API-compatible JSON data for modals.\n */\nexport class ModalBuilder implements JSONEncodable {\n\t/**\n\t * The API data associated with this modal.\n\t */\n\tpublic readonly data: Partial;\n\n\t/**\n\t * The components within this modal.\n\t */\n\tpublic readonly components: ActionRowBuilder[] = [];\n\n\t/**\n\t * Creates a new modal from API data.\n\t *\n\t * @param data - The API data to create this modal with\n\t */\n\tpublic constructor({ components, ...data }: Partial = {}) {\n\t\tthis.data = { ...data };\n\t\tthis.components = (components?.map((component) => createComponentBuilder(component)) ??\n\t\t\t[]) as ActionRowBuilder[];\n\t}\n\n\t/**\n\t * Sets the title of this modal.\n\t *\n\t * @param title - The title to use\n\t */\n\tpublic setTitle(title: string) {\n\t\tthis.data.title = titleValidator.parse(title);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the custom id of this modal.\n\t *\n\t * @param customId - The custom id to use\n\t */\n\tpublic setCustomId(customId: string) {\n\t\tthis.data.custom_id = customIdValidator.parse(customId);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds components to this modal.\n\t *\n\t * @param components - The components to add\n\t */\n\tpublic addComponents(\n\t\t...components: RestOrArray<\n\t\t\tActionRowBuilder | APIActionRowComponent\n\t\t>\n\t) {\n\t\tthis.components.push(\n\t\t\t...normalizeArray(components).map((component) =>\n\t\t\t\tcomponent instanceof ActionRowBuilder\n\t\t\t\t\t? component\n\t\t\t\t\t: new ActionRowBuilder(component),\n\t\t\t),\n\t\t);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets components for this modal.\n\t *\n\t * @param components - The components to set\n\t */\n\tpublic setComponents(...components: RestOrArray>) {\n\t\tthis.components.splice(0, this.components.length, ...normalizeArray(components));\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ComponentBuilder.toJSON}\n\t */\n\tpublic toJSON(): APIModalInteractionResponseCallbackData {\n\t\tvalidateRequiredParameters(this.data.custom_id, this.data.title, this.components);\n\n\t\treturn {\n\t\t\t...this.data,\n\t\t\tcomponents: this.components.map((component) => component.toJSON()),\n\t\t} as APIModalInteractionResponseCallbackData;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { Locale, type APIApplicationCommandOptionChoice, type LocalizationMap } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t.regex(/^[\\p{Ll}\\p{Lm}\\p{Lo}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}_-]+$/u)\n\t.setValidationEnabled(isValidationEnabled);\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nconst descriptionPredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(100)\n\t.setValidationEnabled(isValidationEnabled);\nconst localePredicate = s.nativeEnum(Locale);\n\nexport function validateDescription(description: unknown): asserts description is string {\n\tdescriptionPredicate.parse(description);\n}\n\nconst maxArrayLengthPredicate = s.unknown.array.lengthLessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\nexport function validateLocale(locale: unknown) {\n\treturn localePredicate.parse(locale);\n}\n\nexport function validateMaxOptionsLength(options: unknown): asserts options is ToAPIApplicationCommandOptions[] {\n\tmaxArrayLengthPredicate.parse(options);\n}\n\nexport function validateRequiredParameters(\n\tname: string,\n\tdescription: string,\n\toptions: ToAPIApplicationCommandOptions[],\n) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert description conditions\n\tvalidateDescription(description);\n\n\t// Assert options conditions\n\tvalidateMaxOptionsLength(options);\n}\n\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateRequired(required: unknown): asserts required is boolean {\n\tbooleanPredicate.parse(required);\n}\n\nconst choicesLengthPredicate = s.number.lessThanOrEqual(25).setValidationEnabled(isValidationEnabled);\n\nexport function validateChoicesLength(amountAdding: number, choices?: APIApplicationCommandOptionChoice[]): void {\n\tchoicesLengthPredicate.parse((choices?.length ?? 0) + amountAdding);\n}\n\nexport function assertReturnOfBuilder<\n\tT extends ApplicationCommandOptionBase | SlashCommandSubcommandBuilder | SlashCommandSubcommandGroupBuilder,\n>(input: unknown, ExpectedInstanceOf: new () => T): asserts input is T {\n\ts.instance(ExpectedInstanceOf).parse(input);\n}\n\nexport const localizationMapPredicate = s\n\t.object(Object.fromEntries(Object.values(Locale).map((locale) => [locale, s.string.nullish])))\n\t.strict.nullish.setValidationEnabled(isValidationEnabled);\n\nexport function validateLocalizationMap(value: unknown): asserts value is LocalizationMap {\n\tlocalizationMapPredicate.parse(value);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n\nexport function validateNSFW(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n","import type {\n\tAPIApplicationCommandOption,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIChatInputApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport {\n\tassertReturnOfBuilder,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDefaultPermission,\n\tvalidateLocalizationMap,\n\tvalidateDMPermission,\n\tvalidateMaxOptionsLength,\n\tvalidateRequiredParameters,\n\tvalidateNSFW,\n} from './Assertions.js';\nimport { SlashCommandSubcommandBuilder, SlashCommandSubcommandGroupBuilder } from './SlashCommandSubcommands.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n/**\n * A builder that creates API-compatible JSON data for slash commands.\n */\n@mix(SharedSlashCommandOptions, SharedNameAndDescription)\nexport class SlashCommandBuilder {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The description of this command.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The description localizations of this command.\n\t */\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * The options of this command.\n\t */\n\tpublic readonly options: ToAPIApplicationCommandOptions[] = [];\n\n\t/**\n\t * Whether this command is enabled by default when the application is added to a guild.\n\t *\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * The set of permissions represented as a bit set for the command.\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This property is only for global commands.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Whether this command is NSFW.\n\t */\n\tpublic readonly nsfw: boolean | undefined = undefined;\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether or not to enable this command by default\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t * @deprecated Use {@link SlashCommandBuilder.setDefaultMemberPermissions} or {@link SlashCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run the command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This method is only for global commands.\n\t * @param enabled - Whether the command should be enabled in direct messages\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether this command is NSFW.\n\t *\n\t * @param nsfw - Whether this command is NSFW\n\t */\n\tpublic setNSFW(nsfw = true) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateNSFW(nsfw);\n\t\tReflect.set(this, 'nsfw', nsfw);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand group to this command.\n\t *\n\t * @param input - A function that returns a subcommand group builder or an already built builder\n\t */\n\tpublic addSubcommandGroup(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandGroupBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandGroupBuilder) => SlashCommandSubcommandGroupBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandGroupBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandGroupBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Adds a new subcommand to this command.\n\t *\n\t * @param input - A function that returns a subcommand builder or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t): SlashCommandSubcommandsOnlyBuilder {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIChatInputApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\treturn {\n\t\t\t...this,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n\n/**\n * An interface specifically for slash command subcommands.\n */\nexport interface SlashCommandSubcommandsOnlyBuilder\n\textends Omit> {}\n\n/**\n * An interface specifically for slash command options.\n */\nexport interface SlashCommandOptionsOnlyBuilder\n\textends SharedNameAndDescription,\n\t\tSharedSlashCommandOptions,\n\t\tPick {}\n\n/**\n * An interface that ensures the `toJSON()` call will return something\n * that can be serialized into API-compatible data.\n */\nexport interface ToAPIApplicationCommandOptions {\n\ttoJSON(): APIApplicationCommandOption;\n}\n","import {\n\tApplicationCommandOptionType,\n\ttype APIApplicationCommandSubcommandGroupOption,\n\ttype APIApplicationCommandSubcommandOption,\n} from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { assertReturnOfBuilder, validateMaxOptionsLength, validateRequiredParameters } from './Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from './SlashCommandBuilder.js';\nimport type { ApplicationCommandOptionBase } from './mixins/ApplicationCommandOptionBase.js';\nimport { SharedNameAndDescription } from './mixins/NameAndDescription.js';\nimport { SharedSlashCommandOptions } from './mixins/SharedSlashCommandOptions.js';\n\n/**\n * Represents a folder for subcommands.\n *\n * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups}\n */\n@mix(SharedNameAndDescription)\nexport class SlashCommandSubcommandGroupBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand group.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand group.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The subcommands within this subcommand group.\n\t */\n\tpublic readonly options: SlashCommandSubcommandBuilder[] = [];\n\n\t/**\n\t * Adds a new subcommand to this group.\n\t *\n\t * @param input - A function that returns a subcommand builder or an already built builder\n\t */\n\tpublic addSubcommand(\n\t\tinput:\n\t\t\t| SlashCommandSubcommandBuilder\n\t\t\t| ((subcommandGroup: SlashCommandSubcommandBuilder) => SlashCommandSubcommandBuilder),\n\t) {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tconst result = typeof input === 'function' ? input(new SlashCommandSubcommandBuilder()) : input;\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\tassertReturnOfBuilder(result, SlashCommandSubcommandBuilder);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIApplicationCommandSubcommandGroupOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.SubcommandGroup,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandGroupBuilder extends SharedNameAndDescription {}\n\n/**\n * A builder that creates API-compatible JSON data for slash command subcommands.\n *\n * @see {@link https://discord.com/developers/docs/interactions/application-commands#subcommands-and-subcommand-groups}\n */\n@mix(SharedNameAndDescription, SharedSlashCommandOptions)\nexport class SlashCommandSubcommandBuilder implements ToAPIApplicationCommandOptions {\n\t/**\n\t * The name of this subcommand.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The description of this subcommand.\n\t */\n\tpublic readonly description: string = undefined!;\n\n\t/**\n\t * The options within this subcommand.\n\t */\n\tpublic readonly options: ApplicationCommandOptionBase[] = [];\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): APIApplicationCommandSubcommandOption {\n\t\tvalidateRequiredParameters(this.name, this.description, this.options);\n\n\t\treturn {\n\t\t\ttype: ApplicationCommandOptionType.Subcommand,\n\t\t\tname: this.name,\n\t\t\tname_localizations: this.name_localizations,\n\t\t\tdescription: this.description,\n\t\t\tdescription_localizations: this.description_localizations,\n\t\t\toptions: this.options.map((option) => option.toJSON()),\n\t\t};\n\t}\n}\n\nexport interface SlashCommandSubcommandBuilder extends SharedNameAndDescription, SharedSlashCommandOptions {}\n","import type { LocaleString, LocalizationMap } from 'discord-api-types/v10';\nimport { validateDescription, validateLocale, validateName } from '../Assertions.js';\n\n/**\n * This mixin holds name and description symbols for slash commands.\n */\nexport class SharedNameAndDescription {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name!: string;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The description of this command.\n\t */\n\tpublic readonly description!: string;\n\n\t/**\n\t * The description localizations of this command.\n\t */\n\tpublic readonly description_localizations?: LocalizationMap;\n\n\t/**\n\t * Sets the name of this command.\n\t *\n\t * @param name - The name to use\n\t */\n\tpublic setName(name: string): this {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description of this command.\n\t *\n\t * @param description - The description to use\n\t */\n\tpublic setDescription(description: string) {\n\t\t// Assert the description matches the conditions\n\t\tvalidateDescription(description);\n\n\t\tReflect.set(this, 'description', description);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * SSets a name localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedName - The localized name for the given `locale`\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations for this command.\n\t *\n\t * @param localizedNames - The object of localized names to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames)) {\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a description localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedDescription - The localized description for the given locale\n\t */\n\tpublic setDescriptionLocalization(locale: LocaleString, localizedDescription: string | null) {\n\t\tif (!this.description_localizations) {\n\t\t\tReflect.set(this, 'description_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedDescription === null) {\n\t\t\tthis.description_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateDescription(localizedDescription);\n\n\t\tthis.description_localizations![parsedLocale] = localizedDescription;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the description localizations for this command.\n\t *\n\t * @param localizedDescriptions - The object of localized descriptions to set\n\t */\n\tpublic setDescriptionLocalizations(localizedDescriptions: LocalizationMap | null) {\n\t\tif (localizedDescriptions === null) {\n\t\t\tReflect.set(this, 'description_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'description_localizations', {});\n\t\tfor (const args of Object.entries(localizedDescriptions)) {\n\t\t\tthis.setDescriptionLocalization(...(args as [LocaleString, string | null]));\n\t\t}\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandAttachmentOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command attachment option.\n */\nexport class SlashCommandAttachmentOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Attachment as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandAttachmentOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import type { APIApplicationCommandBasicOption, ApplicationCommandOptionType } from 'discord-api-types/v10';\nimport { validateRequiredParameters, validateRequired, validateLocalizationMap } from '../Assertions.js';\nimport { SharedNameAndDescription } from './NameAndDescription.js';\n\n/**\n * The base application command option builder that contains common symbols for application command builders.\n */\nexport abstract class ApplicationCommandOptionBase extends SharedNameAndDescription {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic abstract readonly type: ApplicationCommandOptionType;\n\n\t/**\n\t * Whether this option is required.\n\t *\n\t * @defaultValue `false`\n\t */\n\tpublic readonly required: boolean = false;\n\n\t/**\n\t * Sets whether this option is required.\n\t *\n\t * @param required - Whether this option should be required\n\t */\n\tpublic setRequired(required: boolean) {\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(required);\n\n\t\tReflect.set(this, 'required', required);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic abstract toJSON(): APIApplicationCommandBasicOption;\n\n\t/**\n\t * This method runs required validators on this builder.\n\t */\n\tprotected runRequiredValidations() {\n\t\tvalidateRequiredParameters(this.name, this.description, []);\n\n\t\t// Validate localizations\n\t\tvalidateLocalizationMap(this.name_localizations);\n\t\tvalidateLocalizationMap(this.description_localizations);\n\n\t\t// Assert that you actually passed a boolean\n\t\tvalidateRequired(this.required);\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandBooleanOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command boolean option.\n */\nexport class SlashCommandBooleanOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Boolean as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandBooleanOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandChannelOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionChannelTypesMixin } from '../mixins/ApplicationCommandOptionChannelTypesMixin.js';\n\n/**\n * A slash command channel option.\n */\n@mix(ApplicationCommandOptionChannelTypesMixin)\nexport class SlashCommandChannelOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Channel as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandChannelOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandChannelOption extends ApplicationCommandOptionChannelTypesMixin {}\n","import { s } from '@sapphire/shapeshift';\nimport { ChannelType } from 'discord-api-types/v10';\n\n/**\n * The allowed channel types used for a channel option in a slash command builder.\n *\n * @privateRemarks This can't be dynamic because const enums are erased at runtime.\n * @internal\n */\nconst allowedChannelTypes = [\n\tChannelType.GuildText,\n\tChannelType.GuildVoice,\n\tChannelType.GuildCategory,\n\tChannelType.GuildAnnouncement,\n\tChannelType.AnnouncementThread,\n\tChannelType.PublicThread,\n\tChannelType.PrivateThread,\n\tChannelType.GuildStageVoice,\n\tChannelType.GuildForum,\n] as const;\n\n/**\n * The type of allowed channel types used for a channel option.\n */\nexport type ApplicationCommandOptionAllowedChannelTypes = (typeof allowedChannelTypes)[number];\n\nconst channelTypesPredicate = s.array(s.union(...allowedChannelTypes.map((type) => s.literal(type))));\n\n/**\n * This mixin holds channel type symbols used for options.\n */\nexport class ApplicationCommandOptionChannelTypesMixin {\n\t/**\n\t * The channel types of this option.\n\t */\n\tpublic readonly channel_types?: ApplicationCommandOptionAllowedChannelTypes[];\n\n\t/**\n\t * Adds channel types to this option.\n\t *\n\t * @param channelTypes - The channel types\n\t */\n\tpublic addChannelTypes(...channelTypes: ApplicationCommandOptionAllowedChannelTypes[]) {\n\t\tif (this.channel_types === undefined) {\n\t\t\tReflect.set(this, 'channel_types', []);\n\t\t}\n\n\t\tthis.channel_types!.push(...channelTypesPredicate.parse(channelTypes));\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandIntegerOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number.int;\n\n/**\n * A slash command integer option.\n */\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandIntegerOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Integer as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandIntegerOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandIntegerOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","/**\n * This mixin holds minimum and maximum symbols used for options.\n */\nexport abstract class ApplicationCommandNumericOptionMinMaxValueMixin {\n\t/**\n\t * The maximum value of this option.\n\t */\n\tpublic readonly max_value?: number;\n\n\t/**\n\t * The minimum value of this option.\n\t */\n\tpublic readonly min_value?: number;\n\n\t/**\n\t * Sets the maximum number value of this option.\n\t *\n\t * @param max - The maximum value this option can be\n\t */\n\tpublic abstract setMaxValue(max: number): this;\n\n\t/**\n\t * Sets the minimum number value of this option.\n\t *\n\t * @param min - The minimum value this option can be\n\t */\n\tpublic abstract setMinValue(min: number): this;\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandOptionChoice } from 'discord-api-types/v10';\nimport { localizationMapPredicate, validateChoicesLength } from '../Assertions.js';\n\nconst stringPredicate = s.string.lengthGreaterThanOrEqual(1).lengthLessThanOrEqual(100);\nconst numberPredicate = s.number.greaterThan(Number.NEGATIVE_INFINITY).lessThan(Number.POSITIVE_INFINITY);\nconst choicesPredicate = s.object({\n\tname: stringPredicate,\n\tname_localizations: localizationMapPredicate,\n\tvalue: s.union(stringPredicate, numberPredicate),\n}).array;\nconst booleanPredicate = s.boolean;\n\n/**\n * This mixin holds choices and autocomplete symbols used for options.\n */\nexport class ApplicationCommandOptionWithChoicesAndAutocompleteMixin {\n\t/**\n\t * The choices of this option.\n\t */\n\tpublic readonly choices?: APIApplicationCommandOptionChoice[];\n\n\t/**\n\t * Whether this option utilizes autocomplete.\n\t */\n\tpublic readonly autocomplete?: boolean;\n\n\t/**\n\t * The type of this option.\n\t *\n\t * @privateRemarks Since this is present and this is a mixin, this is needed.\n\t */\n\tpublic readonly type!: ApplicationCommandOptionType;\n\n\t/**\n\t * Adds multiple choices to this option.\n\t *\n\t * @param choices - The choices to add\n\t */\n\tpublic addChoices(...choices: APIApplicationCommandOptionChoice[]): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tif (this.choices === undefined) {\n\t\t\tReflect.set(this, 'choices', []);\n\t\t}\n\n\t\tvalidateChoicesLength(choices.length, this.choices);\n\n\t\tfor (const { name, name_localizations, value } of choices) {\n\t\t\t// Validate the value\n\t\t\tif (this.type === ApplicationCommandOptionType.String) {\n\t\t\t\tstringPredicate.parse(value);\n\t\t\t} else {\n\t\t\t\tnumberPredicate.parse(value);\n\t\t\t}\n\n\t\t\tthis.choices!.push({ name, name_localizations, value });\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets multiple choices for this option.\n\t *\n\t * @param choices - The choices to set\n\t */\n\tpublic setChoices[]>(...choices: Input): this {\n\t\tif (choices.length > 0 && this.autocomplete) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tchoicesPredicate.parse(choices);\n\n\t\tReflect.set(this, 'choices', []);\n\t\tthis.addChoices(...choices);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Whether this option uses autocomplete.\n\t *\n\t * @param autocomplete - Whether this option should use autocomplete\n\t */\n\tpublic setAutocomplete(autocomplete: boolean): this {\n\t\t// Assert that you actually passed a boolean\n\t\tbooleanPredicate.parse(autocomplete);\n\n\t\tif (autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\tReflect.set(this, 'autocomplete', autocomplete);\n\n\t\treturn this;\n\t}\n}\n","import { ApplicationCommandOptionType, type APIApplicationCommandMentionableOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command mentionable option.\n */\nexport class SlashCommandMentionableOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Mentionable as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandMentionableOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandNumberOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandNumericOptionMinMaxValueMixin } from '../mixins/ApplicationCommandNumericOptionMinMaxValueMixin.js';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst numberValidator = s.number;\n\n/**\n * A slash command number option.\n */\n@mix(ApplicationCommandNumericOptionMinMaxValueMixin, ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandNumberOption\n\textends ApplicationCommandOptionBase\n\timplements ApplicationCommandNumericOptionMinMaxValueMixin\n{\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.Number as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMaxValue}\n\t */\n\tpublic setMaxValue(max: number): this {\n\t\tnumberValidator.parse(max);\n\n\t\tReflect.set(this, 'max_value', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandNumericOptionMinMaxValueMixin.setMinValue}\n\t */\n\tpublic setMinValue(min: number): this {\n\t\tnumberValidator.parse(min);\n\n\t\tReflect.set(this, 'min_value', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandNumberOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandNumberOption\n\textends ApplicationCommandNumericOptionMinMaxValueMixin,\n\t\tApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandRoleOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command role option.\n */\nexport class SlashCommandRoleOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic override readonly type = ApplicationCommandOptionType.Role as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandRoleOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandOptionType, type APIApplicationCommandStringOption } from 'discord-api-types/v10';\nimport { mix } from 'ts-mixer';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\nimport { ApplicationCommandOptionWithChoicesAndAutocompleteMixin } from '../mixins/ApplicationCommandOptionWithChoicesAndAutocompleteMixin.js';\n\nconst minLengthValidator = s.number.greaterThanOrEqual(0).lessThanOrEqual(6_000);\nconst maxLengthValidator = s.number.greaterThanOrEqual(1).lessThanOrEqual(6_000);\n\n/**\n * A slash command string option.\n */\n@mix(ApplicationCommandOptionWithChoicesAndAutocompleteMixin)\nexport class SlashCommandStringOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.String as const;\n\n\t/**\n\t * The maximum length of this option.\n\t */\n\tpublic readonly max_length?: number;\n\n\t/**\n\t * The minimum length of this option.\n\t */\n\tpublic readonly min_length?: number;\n\n\t/**\n\t * Sets the maximum length of this string option.\n\t *\n\t * @param max - The maximum length this option can be\n\t */\n\tpublic setMaxLength(max: number): this {\n\t\tmaxLengthValidator.parse(max);\n\n\t\tReflect.set(this, 'max_length', max);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the minimum length of this string option.\n\t *\n\t * @param min - The minimum length this option can be\n\t */\n\tpublic setMinLength(min: number): this {\n\t\tminLengthValidator.parse(min);\n\n\t\tReflect.set(this, 'min_length', min);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandStringOption {\n\t\tthis.runRequiredValidations();\n\n\t\tif (this.autocomplete && Array.isArray(this.choices) && this.choices.length > 0) {\n\t\t\tthrow new RangeError('Autocomplete and choices are mutually exclusive to each other.');\n\t\t}\n\n\t\treturn { ...this };\n\t}\n}\n\nexport interface SlashCommandStringOption extends ApplicationCommandOptionWithChoicesAndAutocompleteMixin {}\n","import { ApplicationCommandOptionType, type APIApplicationCommandUserOption } from 'discord-api-types/v10';\nimport { ApplicationCommandOptionBase } from '../mixins/ApplicationCommandOptionBase.js';\n\n/**\n * A slash command user option.\n */\nexport class SlashCommandUserOption extends ApplicationCommandOptionBase {\n\t/**\n\t * The type of this option.\n\t */\n\tpublic readonly type = ApplicationCommandOptionType.User as const;\n\n\t/**\n\t * {@inheritDoc ApplicationCommandOptionBase.toJSON}\n\t */\n\tpublic toJSON(): APIApplicationCommandUserOption {\n\t\tthis.runRequiredValidations();\n\n\t\treturn { ...this };\n\t}\n}\n","import { assertReturnOfBuilder, validateMaxOptionsLength } from '../Assertions.js';\nimport type { ToAPIApplicationCommandOptions } from '../SlashCommandBuilder';\nimport { SlashCommandAttachmentOption } from '../options/attachment.js';\nimport { SlashCommandBooleanOption } from '../options/boolean.js';\nimport { SlashCommandChannelOption } from '../options/channel.js';\nimport { SlashCommandIntegerOption } from '../options/integer.js';\nimport { SlashCommandMentionableOption } from '../options/mentionable.js';\nimport { SlashCommandNumberOption } from '../options/number.js';\nimport { SlashCommandRoleOption } from '../options/role.js';\nimport { SlashCommandStringOption } from '../options/string.js';\nimport { SlashCommandUserOption } from '../options/user.js';\nimport type { ApplicationCommandOptionBase } from './ApplicationCommandOptionBase.js';\n\n/**\n * This mixin holds symbols that can be shared in slash command options.\n *\n * @typeParam ShouldOmitSubcommandFunctions - Whether to omit subcommand functions.\n */\nexport class SharedSlashCommandOptions {\n\tpublic readonly options!: ToAPIApplicationCommandOptions[];\n\n\t/**\n\t * Adds a boolean option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addBooleanOption(\n\t\tinput: SlashCommandBooleanOption | ((builder: SlashCommandBooleanOption) => SlashCommandBooleanOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandBooleanOption);\n\t}\n\n\t/**\n\t * Adds a user option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addUserOption(input: SlashCommandUserOption | ((builder: SlashCommandUserOption) => SlashCommandUserOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandUserOption);\n\t}\n\n\t/**\n\t * Adds a channel option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addChannelOption(\n\t\tinput: SlashCommandChannelOption | ((builder: SlashCommandChannelOption) => SlashCommandChannelOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandChannelOption);\n\t}\n\n\t/**\n\t * Adds a role option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addRoleOption(input: SlashCommandRoleOption | ((builder: SlashCommandRoleOption) => SlashCommandRoleOption)) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandRoleOption);\n\t}\n\n\t/**\n\t * Adds an attachment option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addAttachmentOption(\n\t\tinput: SlashCommandAttachmentOption | ((builder: SlashCommandAttachmentOption) => SlashCommandAttachmentOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandAttachmentOption);\n\t}\n\n\t/**\n\t * Adds a mentionable option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addMentionableOption(\n\t\tinput: SlashCommandMentionableOption | ((builder: SlashCommandMentionableOption) => SlashCommandMentionableOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandMentionableOption);\n\t}\n\n\t/**\n\t * Adds a string option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addStringOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandStringOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandStringOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandStringOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandStringOption);\n\t}\n\n\t/**\n\t * Adds an integer option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addIntegerOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandIntegerOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandIntegerOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandIntegerOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandIntegerOption);\n\t}\n\n\t/**\n\t * Adds a number option.\n\t *\n\t * @param input - A function that returns an option builder or an already built builder\n\t */\n\tpublic addNumberOption(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| SlashCommandNumberOption\n\t\t\t| ((\n\t\t\t\t\tbuilder: SlashCommandNumberOption,\n\t\t\t ) =>\n\t\t\t\t\t| Omit\n\t\t\t\t\t| Omit\n\t\t\t\t\t| SlashCommandNumberOption),\n\t) {\n\t\treturn this._sharedAddOptionMethod(input, SlashCommandNumberOption);\n\t}\n\n\t/**\n\t * Where the actual adding magic happens. ✨\n\t *\n\t * @param input - The input. What else?\n\t * @param Instance - The instance of whatever is being added\n\t * @internal\n\t */\n\tprivate _sharedAddOptionMethod(\n\t\tinput:\n\t\t\t| Omit\n\t\t\t| Omit\n\t\t\t| T\n\t\t\t| ((builder: T) => Omit | Omit | T),\n\t\tInstance: new () => T,\n\t): ShouldOmitSubcommandFunctions extends true ? Omit : this {\n\t\tconst { options } = this;\n\n\t\t// First, assert options conditions - we cannot have more than 25 options\n\t\tvalidateMaxOptionsLength(options);\n\n\t\t// Get the final result\n\t\tconst result = typeof input === 'function' ? input(new Instance()) : input;\n\n\t\tassertReturnOfBuilder(result, Instance);\n\n\t\t// Push it\n\t\toptions.push(result);\n\n\t\treturn this;\n\t}\n}\n","import { s } from '@sapphire/shapeshift';\nimport { ApplicationCommandType } from 'discord-api-types/v10';\nimport { isValidationEnabled } from '../../util/validation.js';\nimport type { ContextMenuCommandType } from './ContextMenuCommandBuilder.js';\n\nconst namePredicate = s.string\n\t.lengthGreaterThanOrEqual(1)\n\t.lengthLessThanOrEqual(32)\n\t// eslint-disable-next-line prefer-named-capture-group, unicorn/no-unsafe-regex\n\t.regex(/^( *[\\p{P}\\p{L}\\p{N}\\p{sc=Devanagari}\\p{sc=Thai}]+ *)+$/u)\n\t.setValidationEnabled(isValidationEnabled);\nconst typePredicate = s\n\t.union(s.literal(ApplicationCommandType.User), s.literal(ApplicationCommandType.Message))\n\t.setValidationEnabled(isValidationEnabled);\nconst booleanPredicate = s.boolean;\n\nexport function validateDefaultPermission(value: unknown): asserts value is boolean {\n\tbooleanPredicate.parse(value);\n}\n\nexport function validateName(name: unknown): asserts name is string {\n\tnamePredicate.parse(name);\n}\n\nexport function validateType(type: unknown): asserts type is ContextMenuCommandType {\n\ttypePredicate.parse(type);\n}\n\nexport function validateRequiredParameters(name: string, type: number) {\n\t// Assert name matches all conditions\n\tvalidateName(name);\n\n\t// Assert type is valid\n\tvalidateType(type);\n}\n\nconst dmPermissionPredicate = s.boolean.nullish;\n\nexport function validateDMPermission(value: unknown): asserts value is boolean | null | undefined {\n\tdmPermissionPredicate.parse(value);\n}\n\nconst memberPermissionPredicate = s.union(\n\ts.bigint.transform((value) => value.toString()),\n\ts.number.safeInt.transform((value) => value.toString()),\n\ts.string.regex(/^\\d+$/),\n).nullish;\n\nexport function validateDefaultMemberPermissions(permissions: unknown) {\n\treturn memberPermissionPredicate.parse(permissions);\n}\n","import type {\n\tApplicationCommandType,\n\tLocaleString,\n\tLocalizationMap,\n\tPermissions,\n\tRESTPostAPIContextMenuApplicationCommandsJSONBody,\n} from 'discord-api-types/v10';\nimport { validateLocale, validateLocalizationMap } from '../slashCommands/Assertions.js';\nimport {\n\tvalidateRequiredParameters,\n\tvalidateName,\n\tvalidateType,\n\tvalidateDefaultPermission,\n\tvalidateDefaultMemberPermissions,\n\tvalidateDMPermission,\n} from './Assertions.js';\n\n/**\n * The type a context menu command can be.\n */\nexport type ContextMenuCommandType = ApplicationCommandType.Message | ApplicationCommandType.User;\n\n/**\n * A builder that creates API-compatible JSON data for context menu commands.\n */\nexport class ContextMenuCommandBuilder {\n\t/**\n\t * The name of this command.\n\t */\n\tpublic readonly name: string = undefined!;\n\n\t/**\n\t * The name localizations of this command.\n\t */\n\tpublic readonly name_localizations?: LocalizationMap;\n\n\t/**\n\t * The type of this command.\n\t */\n\tpublic readonly type: ContextMenuCommandType = undefined!;\n\n\t/**\n\t * Whether this command is enabled by default when the application is added to a guild.\n\t *\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic readonly default_permission: boolean | undefined = undefined;\n\n\t/**\n\t * The set of permissions represented as a bit set for the command.\n\t */\n\tpublic readonly default_member_permissions: Permissions | null | undefined = undefined;\n\n\t/**\n\t * Indicates whether the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This property is only for global commands.\n\t */\n\tpublic readonly dm_permission: boolean | undefined = undefined;\n\n\t/**\n\t * Sets the name of this command.\n\t *\n\t * @param name - The name to use\n\t */\n\tpublic setName(name: string) {\n\t\t// Assert the name matches the conditions\n\t\tvalidateName(name);\n\n\t\tReflect.set(this, 'name', name);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the type of this command.\n\t *\n\t * @param type - The type to use\n\t */\n\tpublic setType(type: ContextMenuCommandType) {\n\t\t// Assert the type is valid\n\t\tvalidateType(type);\n\n\t\tReflect.set(this, 'type', type);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets whether the command is enabled by default when the application is added to a guild.\n\t *\n\t * @remarks\n\t * If set to `false`, you will have to later `PUT` the permissions for this command.\n\t * @param value - Whether to enable this command by default\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t * @deprecated Use {@link ContextMenuCommandBuilder.setDefaultMemberPermissions} or {@link ContextMenuCommandBuilder.setDMPermission} instead.\n\t */\n\tpublic setDefaultPermission(value: boolean) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDefaultPermission(value);\n\n\t\tReflect.set(this, 'default_permission', value);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the default permissions a member should have in order to run this command.\n\t *\n\t * @remarks\n\t * You can set this to `'0'` to disable the command by default.\n\t * @param permissions - The permissions bit field to set\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDefaultMemberPermissions(permissions: Permissions | bigint | number | null | undefined) {\n\t\t// Assert the value and parse it\n\t\tconst permissionValue = validateDefaultMemberPermissions(permissions);\n\n\t\tReflect.set(this, 'default_member_permissions', permissionValue);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets if the command is available in direct messages with the application.\n\t *\n\t * @remarks\n\t * By default, commands are visible. This method is only for global commands.\n\t * @param enabled - Whether the command should be enabled in direct messages\n\t * @see {@link https://discord.com/developers/docs/interactions/application-commands#permissions}\n\t */\n\tpublic setDMPermission(enabled: boolean | null | undefined) {\n\t\t// Assert the value matches the conditions\n\t\tvalidateDMPermission(enabled);\n\n\t\tReflect.set(this, 'dm_permission', enabled);\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets a name localization for this command.\n\t *\n\t * @param locale - The locale to set\n\t * @param localizedName - The localized name for the given `locale`\n\t */\n\tpublic setNameLocalization(locale: LocaleString, localizedName: string | null) {\n\t\tif (!this.name_localizations) {\n\t\t\tReflect.set(this, 'name_localizations', {});\n\t\t}\n\n\t\tconst parsedLocale = validateLocale(locale);\n\n\t\tif (localizedName === null) {\n\t\t\tthis.name_localizations![parsedLocale] = null;\n\t\t\treturn this;\n\t\t}\n\n\t\tvalidateName(localizedName);\n\n\t\tthis.name_localizations![parsedLocale] = localizedName;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the name localizations for this command.\n\t *\n\t * @param localizedNames - The object of localized names to set\n\t */\n\tpublic setNameLocalizations(localizedNames: LocalizationMap | null) {\n\t\tif (localizedNames === null) {\n\t\t\tReflect.set(this, 'name_localizations', null);\n\t\t\treturn this;\n\t\t}\n\n\t\tReflect.set(this, 'name_localizations', {});\n\n\t\tfor (const args of Object.entries(localizedNames))\n\t\t\tthis.setNameLocalization(...(args as [LocaleString, string | null]));\n\t\treturn this;\n\t}\n\n\t/**\n\t * Serializes this builder to API-compatible JSON data.\n\t *\n\t * @remarks\n\t * This method runs validations on the data before serializing it.\n\t * As such, it may throw an error if the data is invalid.\n\t */\n\tpublic toJSON(): RESTPostAPIContextMenuApplicationCommandsJSONBody {\n\t\tvalidateRequiredParameters(this.name, this.type);\n\n\t\tvalidateLocalizationMap(this.name_localizations);\n\n\t\treturn { ...this };\n\t}\n}\n","import type { APIEmbed } from 'discord-api-types/v10';\n\n/**\n * Calculates the length of the embed.\n *\n * @param data - The embed data to check\n */\nexport function embedLength(data: APIEmbed) {\n\treturn (\n\t\t(data.title?.length ?? 0) +\n\t\t(data.description?.length ?? 0) +\n\t\t(data.fields?.reduce((prev, curr) => prev + curr.name.length + curr.value.length, 0) ?? 0) +\n\t\t(data.footer?.text.length ?? 0) +\n\t\t(data.author?.name.length ?? 0)\n\t);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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R;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EASO,SAA4D;AAClE,IAAAI,4BAA2B,KAAK,MAAM,KAAK,IAAI;AAE/C,4BAAwB,KAAK,kBAAkB;AAE/C,WAAO,EAAE,GAAG,KAAK;AAAA,EAClB;AACD;AA5Ka;;;AClBN,SAAS,YAAY,MAAgB;AAC3C,UACE,KAAK,OAAO,UAAU,MACtB,KAAK,aAAa,UAAU,MAC5B,KAAK,QAAQ,OAAO,CAAC,MAAM,SAAS,OAAO,KAAK,KAAK,SAAS,KAAK,MAAM,QAAQ,CAAC,KAAK,MACvF,KAAK,QAAQ,KAAK,UAAU,MAC5B,KAAK,QAAQ,KAAK,UAAU;AAE/B;AARgB;;;ArC6DT,IAAM,UAAU;","names":["Assertions_exports","s","s","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","ComponentType","Assertions_exports","placeholderValidator","s","s","placeholderValidator","ComponentType","placeholderValidator","ComponentType","ComponentType","Assertions_exports","validateRequiredParameters","s","s","validateRequiredParameters","validateRequiredParameters","Assertions_exports","validateRequiredParameters","s","s","descriptionPredicate","validateRequiredParameters","mix","ApplicationCommandOptionType","mix","validateRequiredParameters","ApplicationCommandOptionType","ApplicationCommandOptionType","ApplicationCommandOptionType","s","ChannelType","ChannelType","s","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","s","ApplicationCommandOptionType","s","booleanPredicate","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","ApplicationCommandOptionType","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","numberValidator","s","ApplicationCommandOptionType","mix","ApplicationCommandOptionType","ApplicationCommandOptionType","s","ApplicationCommandOptionType","mix","minLengthValidator","s","maxLengthValidator","ApplicationCommandOptionType","mix","ApplicationCommandOptionType","ApplicationCommandOptionType","validateRequiredParameters","ApplicationCommandOptionType","mix","validateRequiredParameters","mix","Assertions_exports","validateDMPermission","validateDefaultMemberPermissions","validateDefaultPermission","validateName","validateRequiredParameters","s","namePredicate","s","booleanPredicate","validateDefaultPermission","validateName","validateRequiredParameters","dmPermissionPredicate","validateDMPermission","memberPermissionPredicate","validateDefaultMemberPermissions","validateName","validateDefaultPermission","validateDefaultMemberPermissions","validateDMPermission","validateRequiredParameters"]} \ No newline at end of file diff --git a/node_modules/@discordjs/builders/package.json b/node_modules/@discordjs/builders/package.json index 320b42d..da4ec0b 100644 --- a/node_modules/@discordjs/builders/package.json +++ b/node_modules/@discordjs/builders/package.json @@ -1,95 +1,42 @@ { - "_from": "@discordjs/builders@^1.4.0", - "_id": "@discordjs/builders@1.4.0", - "_inBundle": false, - "_integrity": "sha512-nEeTCheTTDw5kO93faM1j8ZJPonAX86qpq/QVoznnSa8WWcCgJpjlu6GylfINTDW6o7zZY0my2SYdxx2mfNwGA==", - "_location": "/@discordjs/builders", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@discordjs/builders@^1.4.0", - "name": "@discordjs/builders", - "escapedName": "@discordjs%2fbuilders", - "scope": "@discordjs", - "rawSpec": "^1.4.0", - "saveSpec": null, - "fetchSpec": "^1.4.0" - }, - "_requiredBy": [ - "/discord.js" - ], - "_resolved": "https://registry.npmjs.org/@discordjs/builders/-/builders-1.4.0.tgz", - "_shasum": "b951b5e6ce4e459cd06174ce50dbd51c254c1d47", - "_spec": "@discordjs/builders@^1.4.0", - "_where": "D:\\programmen\\Discord bot\\CAROLINE\\node_modules\\discord.js", - "bugs": { - "url": "https://github.com/discordjs/discord.js/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Vlad Frangu", - "email": "kingdgrizzle@gmail.com" - }, - { - "name": "Crawl", - "email": "icrawltogo@gmail.com" - }, - { - "name": "Amish Shah", - "email": "amishshah.2k@gmail.com" - }, - { - "name": "SpaceEEC", - "email": "spaceeec@yahoo.com" - }, - { - "name": "Aura RomΓ‘n", - "email": "kyradiscord@gmail.com" - } - ], - "dependencies": { - "@discordjs/util": "^0.1.0", - "@sapphire/shapeshift": "^3.7.1", - "discord-api-types": "^0.37.20", - "fast-deep-equal": "^3.1.3", - "ts-mixer": "^6.0.2", - "tslib": "^2.4.1" - }, - "deprecated": false, + "name": "@discordjs/builders", + "version": "1.6.3", "description": "A set of builders that you can use when creating your bot", - "devDependencies": { - "@favware/cliff-jumper": "^1.9.0", - "@microsoft/api-extractor": "^7.33.6", - "@types/node": "16.18.3", - "@vitest/coverage-c8": "^0.25.3", - "cross-env": "^7.0.3", - "esbuild-plugin-version-injector": "^1.0.2", - "eslint": "^8.28.0", - "eslint-config-neon": "^0.1.40", - "eslint-formatter-pretty": "^4.1.0", - "prettier": "^2.8.0", - "tsup": "^6.5.0", - "typescript": "^4.9.3", - "vitest": "^0.25.3" + "scripts": { + "test": "vitest run", + "build": "tsup", + "build:docs": "tsc -p tsconfig.docs.json && yarn downlevel-dts ./dist-docs ./dist-docs", + "lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty", + "format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty", + "fmt": "yarn format", + "docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json", + "prepack": "yarn lint && yarn test && yarn build", + "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/builders/*'", + "release": "cliff-jumper" + }, + "main": "./dist/index.js", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", + "exports": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" }, "directories": { "lib": "src", "test": "__tests__" }, - "engines": { - "node": ">=16.9.0" - }, - "exports": { - "import": "./dist/index.mjs", - "require": "./dist/index.js", - "types": "./dist/index.d.ts" - }, "files": [ "dist" ], - "homepage": "https://discord.js.org", + "contributors": [ + "Vlad Frangu ", + "Crawl ", + "Amish Shah ", + "SpaceEEC ", + "Aura RomΓ‘n " + ], + "license": "Apache-2.0", "keywords": [ "discord", "api", @@ -99,28 +46,44 @@ "discordapp", "discordjs" ], - "license": "Apache-2.0", - "main": "./dist/index.js", - "module": "./dist/index.mjs", - "name": "@discordjs/builders", - "publishConfig": { - "access": "public" - }, "repository": { "type": "git", - "url": "git+https://github.com/discordjs/discord.js.git" + "url": "https://github.com/discordjs/discord.js.git", + "directory": "packages/builders" }, - "scripts": { - "build": "tsup", - "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/builders/*'", - "docs": "api-extractor run --local", - "fmt": "yarn format", - "format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty", - "lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty", - "prepack": "yarn lint && yarn test && yarn build", - "release": "cliff-jumper", - "test": "vitest run" + "bugs": { + "url": "https://github.com/discordjs/discord.js/issues" }, - "types": "./dist/index.d.ts", - "version": "1.4.0" -} + "homepage": "https://discord.js.org", + "dependencies": { + "@discordjs/formatters": "^0.3.1", + "@discordjs/util": "^0.3.1", + "@sapphire/shapeshift": "^3.8.2", + "discord-api-types": "^0.37.41", + "fast-deep-equal": "^3.1.3", + "ts-mixer": "^6.0.3", + "tslib": "^2.5.0" + }, + "devDependencies": { + "@favware/cliff-jumper": "^2.0.0", + "@microsoft/api-extractor": "^7.34.6", + "@types/node": "16.18.25", + "@vitest/coverage-c8": "^0.30.1", + "cross-env": "^7.0.3", + "downlevel-dts": "^0.11.0", + "esbuild-plugin-version-injector": "^1.1.0", + "eslint": "^8.39.0", + "eslint-config-neon": "^0.1.42", + "eslint-formatter-pretty": "^5.0.0", + "prettier": "^2.8.8", + "tsup": "^6.7.0", + "typescript": "^5.0.4", + "vitest": "^0.29.8" + }, + "engines": { + "node": ">=16.9.0" + }, + "publishConfig": { + "access": "public" + } +} \ No newline at end of file diff --git a/node_modules/@discordjs/collection/CHANGELOG.md b/node_modules/@discordjs/collection/CHANGELOG.md index 6337754..726af82 100644 --- a/node_modules/@discordjs/collection/CHANGELOG.md +++ b/node_modules/@discordjs/collection/CHANGELOG.md @@ -2,6 +2,44 @@ All notable changes to this project will be documented in this file. +# [@discordjs/collection@1.5.1](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.5.0...@discordjs/collection@1.5.1) - (2023-05-01) + +## Bug Fixes + +- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2)) + +## Documentation + +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) + +# [@discordjs/collection@1.5.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.4.0...@discordjs/collection@1.5.0) - (2023-04-01) + +## Bug Fixes + +- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b)) + +## Features + +- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b)) + +## Refactor + +- **collection:** Fix/silence linter warnings (#9266) ([d6f4e60](https://github.com/discordjs/discord.js/commit/d6f4e60efd1a1796fc84dbbfbac4f9790e480a1c)) + +# [@discordjs/collection@1.4.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.3.0...@discordjs/collection@1.4.0) - (2023-03-12) + +## Documentation + +- Fix version export (#9049) ([8b70f49](https://github.com/discordjs/discord.js/commit/8b70f497a1207e30edebdecd12b926c981c13d28)) + +## Features + +- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38)) + +## Refactor + +- Compare with `undefined` directly (#9191) ([869153c](https://github.com/discordjs/discord.js/commit/869153c3fdf155783e7c0ecebd3627b087c3a026)) + # [@discordjs/collection@1.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/collection@1.2.0...@discordjs/collection@1.3.0) - (2022-11-28) ## Bug Fixes diff --git a/node_modules/@discordjs/collection/README.md b/node_modules/@discordjs/collection/README.md index 93c12e4..3e7b369 100644 --- a/node_modules/@discordjs/collection/README.md +++ b/node_modules/@discordjs/collection/README.md @@ -24,7 +24,7 @@ **Node.js 16.9.0 or newer is required.** -```sh-session +```sh npm install @discordjs/collection yarn add @discordjs/collection pnpm add @discordjs/collection @@ -35,7 +35,7 @@ pnpm add @discordjs/collection - [Website][website] ([source][website-source]) - [Documentation][documentation] - [Guide][guide] ([source][guide-source]) - See also the [Update Guide][guide-update], including updated and removed items in the library. + Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library. - [discord.js Discord server][discord] - [Discord API Discord server][discord-api] - [GitHub][source] @@ -50,12 +50,11 @@ See [the contribution guide][contributing] if you'd like to submit a PR. ## Help -If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle -nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. +If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. -[website]: https://discord.js.org/ +[website]: https://discord.js.org [website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website -[documentation]: https://discord.js.org/#/docs/collection +[documentation]: https://discord.js.org/docs/packages/collection/stable [guide]: https://discordjs.guide/ [guide-source]: https://github.com/discordjs/guide [guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html diff --git a/node_modules/@discordjs/collection/dist/index.js b/node_modules/@discordjs/collection/dist/index.js index af69471..6d459fa 100644 --- a/node_modules/@discordjs/collection/dist/index.js +++ b/node_modules/@discordjs/collection/dist/index.js @@ -28,6 +28,16 @@ module.exports = __toCommonJS(src_exports); // src/collection.ts var Collection = class extends Map { + /** + * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator. + * + * @param key - The key to get if it exists, or set otherwise + * @param defaultValueGenerator - A function that generates the default value + * @example + * ```ts + * collection.ensure(guildId, () => defaultGuildConfig); + * ``` + */ ensure(key, defaultValueGenerator) { if (this.has(key)) return this.get(key); @@ -37,14 +47,26 @@ var Collection = class extends Map { this.set(key, defaultValue); return defaultValue; } + /** + * Checks if all of the elements exist in the collection. + * + * @param keys - The keys of the elements to check for + * @returns `true` if all of the elements exist, `false` if at least one does not exist. + */ hasAll(...keys) { - return keys.every((k) => super.has(k)); - } + return keys.every((key) => super.has(key)); + } + /** + * Checks if any of the elements exist in the collection. + * + * @param keys - The keys of the elements to check for + * @returns `true` if any of the elements exist, `false` if none exist. + */ hasAny(...keys) { - return keys.some((k) => super.has(k)); + return keys.some((key) => super.has(key)); } first(amount) { - if (typeof amount === "undefined") + if (amount === void 0) return this.values().next().value; if (amount < 0) return this.last(amount * -1); @@ -53,7 +75,7 @@ var Collection = class extends Map { return Array.from({ length: amount }, () => iter.next().value); } firstKey(amount) { - if (typeof amount === "undefined") + if (amount === void 0) return this.keys().next().value; if (amount < 0) return this.lastKey(amount * -1); @@ -63,7 +85,7 @@ var Collection = class extends Map { } last(amount) { const arr = [...this.values()]; - if (typeof amount === "undefined") + if (amount === void 0) return arr[arr.length - 1]; if (amount < 0) return this.first(amount * -1); @@ -73,7 +95,7 @@ var Collection = class extends Map { } lastKey(amount) { const arr = [...this.keys()]; - if (typeof amount === "undefined") + if (amount === void 0) return arr[arr.length - 1]; if (amount < 0) return this.firstKey(amount * -1); @@ -81,11 +103,25 @@ var Collection = class extends Map { return []; return arr.slice(-amount); } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}. + * Returns the item at a given index, allowing for positive and negative integers. + * Negative integers count back from the last item in the collection. + * + * @param index - The index of the element to obtain + */ at(index) { index = Math.floor(index); const arr = [...this.values()]; return arr.at(index); } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}. + * Returns the key at a given index, allowing for positive and negative integers. + * Negative integers count back from the last item in the collection. + * + * @param index - The index of the key to obtain + */ keyAt(index) { index = Math.floor(index); const arr = [...this.keys()]; @@ -93,7 +129,7 @@ var Collection = class extends Map { } random(amount) { const arr = [...this.values()]; - if (typeof amount === "undefined") + if (amount === void 0) return arr[Math.floor(Math.random() * arr.length)]; if (!arr.length || !amount) return []; @@ -104,7 +140,7 @@ var Collection = class extends Map { } randomKey(amount) { const arr = [...this.keys()]; - if (typeof amount === "undefined") + if (amount === void 0) return arr[Math.floor(Math.random() * arr.length)]; if (!arr.length || !amount) return []; @@ -113,6 +149,10 @@ var Collection = class extends Map { () => arr.splice(Math.floor(Math.random() * arr.length), 1)[0] ); } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()} + * but returns a Collection instead of an Array. + */ reverse() { const entries = [...this.entries()].reverse(); this.clear(); @@ -123,7 +163,7 @@ var Collection = class extends Map { find(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); for (const [key, val] of this) { if (fn(val, key, this)) @@ -134,7 +174,7 @@ var Collection = class extends Map { findKey(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); for (const [key, val] of this) { if (fn(val, key, this)) @@ -145,7 +185,7 @@ var Collection = class extends Map { sweep(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const previousSize = this.size; for (const [key, val] of this) { @@ -157,7 +197,7 @@ var Collection = class extends Map { filter(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const results = new this.constructor[Symbol.species](); for (const [key, val] of this) { @@ -169,7 +209,7 @@ var Collection = class extends Map { partition(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const results = [ new this.constructor[Symbol.species](), @@ -191,7 +231,7 @@ var Collection = class extends Map { map(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const iter = this.entries(); return Array.from({ length: this.size }, () => { @@ -202,7 +242,7 @@ var Collection = class extends Map { mapValues(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const coll = new this.constructor[Symbol.species](); for (const [key, val] of this) @@ -212,7 +252,7 @@ var Collection = class extends Map { some(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); for (const [key, val] of this) { if (fn(val, key, this)) @@ -223,7 +263,7 @@ var Collection = class extends Map { every(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); for (const [key, val] of this) { if (!fn(val, key, this)) @@ -231,11 +271,23 @@ var Collection = class extends Map { } return true; } + /** + * Applies a function to produce a single value. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}. + * + * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`, + * and `collection` + * @param initialValue - Starting value for the accumulator + * @example + * ```ts + * collection.reduce((acc, guild) => acc + guild.memberCount, 0); + * ``` + */ reduce(fn, initialValue) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); let accumulator; - if (typeof initialValue !== "undefined") { + if (initialValue !== void 0) { accumulator = initialValue; for (const [key, val] of this) accumulator = fn(accumulator, val, key, this); @@ -258,20 +310,41 @@ var Collection = class extends Map { each(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - this.forEach(fn, thisArg); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, value] of this) { + fn(value, key, this); + } return this; } tap(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); fn(this); return this; } + /** + * Creates an identical shallow copy of this collection. + * + * @example + * ```ts + * const newColl = someColl.clone(); + * ``` + */ clone() { return new this.constructor[Symbol.species](this); } + /** + * Combines this collection with others into a new collection. None of the source collections are modified. + * + * @param collections - Collections to merge + * @example + * ```ts + * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl); + * ``` + */ concat(...collections) { const newColl = this.clone(); for (const coll of collections) { @@ -280,6 +353,14 @@ var Collection = class extends Map { } return newColl; } + /** + * Checks if this collection shares identical items with another. + * This is different to checking for equality using equal-signs, because + * the collections may be different objects, but contain the same data. + * + * @param collection - Collection to compare with + * @returns Whether the collections have identical contents + */ equals(collection) { if (!collection) return false; @@ -294,67 +375,135 @@ var Collection = class extends Map { } return true; } + /** + * The sort method sorts the items of a collection in place and returns it. + * The sort is not necessarily stable in Node 10 or older. + * The default sort order is according to string Unicode code points. + * + * @param compareFunction - Specifies a function that defines the sort order. + * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element. + * @example + * ```ts + * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); + * ``` + */ sort(compareFunction = Collection.defaultSort) { const entries = [...this.entries()]; entries.sort((a, b) => compareFunction(a[1], b[1], a[0], b[0])); super.clear(); - for (const [k, v] of entries) { - super.set(k, v); + for (const [key, value] of entries) { + super.set(key, value); } return this; } + /** + * The intersect method returns a new structure containing items where the keys and values are present in both original structures. + * + * @param other - The other Collection to filter against + */ intersect(other) { const coll = new this.constructor[Symbol.species](); - for (const [k, v] of other) { - if (this.has(k) && Object.is(v, this.get(k))) { - coll.set(k, v); + for (const [key, value] of other) { + if (this.has(key) && Object.is(value, this.get(key))) { + coll.set(key, value); } } return coll; } + /** + * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other. + * + * @param other - The other Collection to filter against + */ subtract(other) { const coll = new this.constructor[Symbol.species](); - for (const [k, v] of this) { - if (!other.has(k) || !Object.is(v, other.get(k))) { - coll.set(k, v); + for (const [key, value] of this) { + if (!other.has(key) || !Object.is(value, other.get(key))) { + coll.set(key, value); } } return coll; } + /** + * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other. + * + * @param other - The other Collection to filter against + */ difference(other) { const coll = new this.constructor[Symbol.species](); - for (const [k, v] of other) { - if (!this.has(k)) - coll.set(k, v); + for (const [key, value] of other) { + if (!this.has(key)) + coll.set(key, value); } - for (const [k, v] of this) { - if (!other.has(k)) - coll.set(k, v); + for (const [key, value] of this) { + if (!other.has(key)) + coll.set(key, value); } return coll; } + /** + * Merges two Collections together into a new Collection. + * + * @param other - The other Collection to merge with + * @param whenInSelf - Function getting the result if the entry only exists in this Collection + * @param whenInOther - Function getting the result if the entry only exists in the other Collection + * @param whenInBoth - Function getting the result if the entry exists in both Collections + * @example + * ```ts + * // Sums up the entries in two collections. + * coll.merge( + * other, + * x => ({ keep: true, value: x }), + * y => ({ keep: true, value: y }), + * (x, y) => ({ keep: true, value: x + y }), + * ); + * ``` + * @example + * ```ts + * // Intersects two collections in a left-biased manner. + * coll.merge( + * other, + * x => ({ keep: false }), + * y => ({ keep: false }), + * (x, _) => ({ keep: true, value: x }), + * ); + * ``` + */ merge(other, whenInSelf, whenInOther, whenInBoth) { const coll = new this.constructor[Symbol.species](); const keys = /* @__PURE__ */ new Set([...this.keys(), ...other.keys()]); - for (const k of keys) { - const hasInSelf = this.has(k); - const hasInOther = other.has(k); + for (const key of keys) { + const hasInSelf = this.has(key); + const hasInOther = other.has(key); if (hasInSelf && hasInOther) { - const r = whenInBoth(this.get(k), other.get(k), k); - if (r.keep) - coll.set(k, r.value); + const result = whenInBoth(this.get(key), other.get(key), key); + if (result.keep) + coll.set(key, result.value); } else if (hasInSelf) { - const r = whenInSelf(this.get(k), k); - if (r.keep) - coll.set(k, r.value); + const result = whenInSelf(this.get(key), key); + if (result.keep) + coll.set(key, result.value); } else if (hasInOther) { - const r = whenInOther(other.get(k), k); - if (r.keep) - coll.set(k, r.value); + const result = whenInOther(other.get(key), key); + if (result.keep) + coll.set(key, result.value); } } return coll; } + /** + * The sorted method sorts the items of a collection and returns it. + * The sort is not necessarily stable in Node 10 or older. + * The default sort order is according to string Unicode code points. + * + * @param compareFunction - Specifies a function that defines the sort order. + * If omitted, the collection is sorted according to each character's Unicode code point value, + * according to the string conversion of each element. + * @example + * ```ts + * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); + * ``` + */ sorted(compareFunction = Collection.defaultSort) { return new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk)); } @@ -364,13 +513,24 @@ var Collection = class extends Map { static defaultSort(firstValue, secondValue) { return Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1; } + /** + * Creates a Collection from a list of entries. + * + * @param entries - The list of entries + * @param combine - Function to combine an existing entry with a new one + * @example + * ```ts + * Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y); + * // returns Collection { "a" => 3, "b" => 2 } + * ``` + */ static combineEntries(entries, combine) { const coll = new Collection(); - for (const [k, v] of entries) { - if (coll.has(k)) { - coll.set(k, combine(coll.get(k), v, k)); + for (const [key, value] of entries) { + if (coll.has(key)) { + coll.set(key, combine(coll.get(key), value, key)); } else { - coll.set(k, v); + coll.set(key, value); } } return coll; @@ -379,7 +539,7 @@ var Collection = class extends Map { __name(Collection, "Collection"); // src/index.ts -var version = "1.3.0"; +var version = "1.5.1"; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { Collection, diff --git a/node_modules/@discordjs/collection/dist/index.js.map b/node_modules/@discordjs/collection/dist/index.js.map index 2f95d14..dee559b 100644 --- a/node_modules/@discordjs/collection/dist/index.js.map +++ b/node_modules/@discordjs/collection/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.ts","../src/collection.ts"],"sourcesContent":["export * from './collection.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/collection/#readme | @discordjs/collection} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const version: string = '1.3.0';\n","/* eslint-disable id-length */\n/* eslint-disable no-param-reassign */\n/**\n * @internal\n */\nexport interface CollectionConstructor {\n\tnew (): Collection;\n\tnew (entries?: readonly (readonly [K, V])[] | null): Collection;\n\tnew (iterable: Iterable): Collection;\n\treadonly prototype: Collection;\n\treadonly [Symbol.species]: CollectionConstructor;\n}\n\n/**\n * Represents an immutable version of a collection\n */\nexport type ReadonlyCollection = Omit<\n\tCollection,\n\t'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'\n> &\n\tReadonlyMap;\n\n/**\n * Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself\n *\n * @internal\n */\nexport interface Collection extends Map {\n\tconstructor: CollectionConstructor;\n}\n\n/**\n * A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has\n * an ID, for significantly improved performance and ease-of-use.\n *\n * @typeParam K - The key type this collection holds\n * @typeParam V - The value type this collection holds\n */\nexport class Collection extends Map {\n\t/**\n\t * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.\n\t *\n\t * @param key - The key to get if it exists, or set otherwise\n\t * @param defaultValueGenerator - A function that generates the default value\n\t * @example\n\t * ```ts\n\t * collection.ensure(guildId, () => defaultGuildConfig);\n\t * ```\n\t */\n\tpublic ensure(key: K, defaultValueGenerator: (key: K, collection: this) => V): V {\n\t\tif (this.has(key)) return this.get(key)!;\n\t\tif (typeof defaultValueGenerator !== 'function') throw new TypeError(`${defaultValueGenerator} is not a function`);\n\t\tconst defaultValue = defaultValueGenerator(key, this);\n\t\tthis.set(key, defaultValue);\n\t\treturn defaultValue;\n\t}\n\n\t/**\n\t * Checks if all of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if all of the elements exist, `false` if at least one does not exist.\n\t */\n\tpublic hasAll(...keys: K[]) {\n\t\treturn keys.every((k) => super.has(k));\n\t}\n\n\t/**\n\t * Checks if any of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if any of the elements exist, `false` if none exist.\n\t */\n\tpublic hasAny(...keys: K[]) {\n\t\treturn keys.some((k) => super.has(k));\n\t}\n\n\t/**\n\t * Obtains the first value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the beginning\n\t * @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative\n\t */\n\tpublic first(): V | undefined;\n\tpublic first(amount: number): V[];\n\tpublic first(amount?: number): V | V[] | undefined {\n\t\tif (typeof amount === 'undefined') return this.values().next().value;\n\t\tif (amount < 0) return this.last(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.values();\n\t\treturn Array.from({ length: amount }, (): V => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the first key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the beginning\n\t * @returns A single key if no amount is provided or an array of keys, starting from the end if\n\t * amount is negative\n\t */\n\tpublic firstKey(): K | undefined;\n\tpublic firstKey(amount: number): K[];\n\tpublic firstKey(amount?: number): K | K[] | undefined {\n\t\tif (typeof amount === 'undefined') return this.keys().next().value;\n\t\tif (amount < 0) return this.lastKey(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.keys();\n\t\treturn Array.from({ length: amount }, (): K => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the last value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the end\n\t * @returns A single value if no amount is provided or an array of values, starting from the start if\n\t * amount is negative\n\t */\n\tpublic last(): V | undefined;\n\tpublic last(amount: number): V[];\n\tpublic last(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (typeof amount === 'undefined') return arr[arr.length - 1];\n\t\tif (amount < 0) return this.first(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Obtains the last key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the end\n\t * @returns A single key if no amount is provided or an array of keys, starting from the start if\n\t * amount is negative\n\t */\n\tpublic lastKey(): K | undefined;\n\tpublic lastKey(amount: number): K[];\n\tpublic lastKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (typeof amount === 'undefined') return arr[arr.length - 1];\n\t\tif (amount < 0) return this.firstKey(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the item at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the element to obtain\n\t */\n\tpublic at(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.values()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the key at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the key to obtain\n\t */\n\tpublic keyAt(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.keys()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Obtains unique random value(s) from this collection.\n\t *\n\t * @param amount - Amount of values to obtain randomly\n\t * @returns A single value if no amount is provided or an array of values\n\t */\n\tpublic random(): V | undefined;\n\tpublic random(amount: number): V[];\n\tpublic random(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (typeof amount === 'undefined') return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): V => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Obtains unique random key(s) from this collection.\n\t *\n\t * @param amount - Amount of keys to obtain randomly\n\t * @returns A single key if no amount is provided or an array\n\t */\n\tpublic randomKey(): K | undefined;\n\tpublic randomKey(amount: number): K[];\n\tpublic randomKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (typeof amount === 'undefined') return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): K => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}\n\t * but returns a Collection instead of an Array.\n\t */\n\tpublic reverse() {\n\t\tconst entries = [...this.entries()].reverse();\n\t\tthis.clear();\n\t\tfor (const [key, value] of entries) this.set(key, value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Searches for a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.find()}.\n\t * All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you\n\t * should use the `get` method. See\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | MDN} for details.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.find(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic find(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown): V | undefined;\n\tpublic find(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): V2 | undefined;\n\tpublic find(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): V | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return val;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Searches for the key of a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.findIndex()},\n\t * but returns the key rather than the positional index.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.findKey(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic findKey(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined;\n\tpublic findKey(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): K2 | undefined;\n\tpublic findKey(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): K | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): K | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return key;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Removes items that satisfy the provided filter function.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @returns The number of removed entries\n\t */\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown): number;\n\tpublic sweep(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): number;\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): number {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst previousSize = this.size;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) this.delete(key);\n\t\t}\n\n\t\treturn previousSize - this.size;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.filter()},\n\t * but returns a Collection instead of an Array.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.filter(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic filter(fn: (value: V, key: K, collection: this) => key is K2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => value is V2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst results = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) results.set(key, val);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Partitions the collection into two collections where the first collection\n\t * contains the items that passed and the second contains the items that failed.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * const [big, small] = collection.partition(guild => guild.memberCount > 250);\n\t * ```\n\t */\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => key is K2,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => value is V2,\n\t): [Collection, Collection>];\n\tpublic partition(fn: (value: V, key: K, collection: this) => unknown): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): [Collection, Collection>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => unknown,\n\t\tthisArg: This,\n\t): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => unknown,\n\t\tthisArg?: unknown,\n\t): [Collection, Collection] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst results: [Collection, Collection] = [\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t];\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) {\n\t\t\t\tresults[0].set(key, val);\n\t\t\t} else {\n\t\t\t\tresults[1].set(key, val);\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.flatMap()}.\n\t *\n\t * @param fn - Function that produces a new Collection\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.flatMap(guild => guild.members.cache);\n\t * ```\n\t */\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection): Collection;\n\tpublic flatMap(\n\t\tfn: (this: This, value: V, key: K, collection: this) => Collection,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection, thisArg?: unknown): Collection {\n\t\t// eslint-disable-next-line unicorn/no-array-method-this-argument\n\t\tconst collections = this.map(fn, thisArg);\n\t\treturn new this.constructor[Symbol.species]().concat(...collections);\n\t}\n\n\t/**\n\t * Maps each item to another value into an array. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new array, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.map(user => user.tag);\n\t * ```\n\t */\n\tpublic map(fn: (value: V, key: K, collection: this) => T): T[];\n\tpublic map(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[];\n\tpublic map(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): T[] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst iter = this.entries();\n\t\treturn Array.from({ length: this.size }, (): T => {\n\t\t\tconst [key, value] = iter.next().value;\n\t\t\treturn fn(value, key, this);\n\t\t});\n\t}\n\n\t/**\n\t * Maps each item to another value into a collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new collection, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.mapValues(user => user.tag);\n\t * ```\n\t */\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T): Collection;\n\tpublic mapValues(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection;\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) coll.set(key, fn(val, key, this));\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Checks if there exists an item that passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.some()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.some(user => user.discriminator === '0000');\n\t * ```\n\t */\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic some(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): boolean;\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if all items passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.every()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.every(user => !user.bot);\n\t * ```\n\t */\n\tpublic every(fn: (value: V, key: K, collection: this) => key is K2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => value is V2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): boolean;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (!fn(val, key, this)) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Applies a function to produce a single value. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.\n\t *\n\t * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,\n\t * and `collection`\n\t * @param initialValue - Starting value for the accumulator\n\t * @example\n\t * ```ts\n\t * collection.reduce((acc, guild) => acc + guild.memberCount, 0);\n\t * ```\n\t */\n\tpublic reduce(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tlet accumulator!: T;\n\n\t\tif (typeof initialValue !== 'undefined') {\n\t\t\taccumulator = initialValue;\n\t\t\tfor (const [key, val] of this) accumulator = fn(accumulator, val, key, this);\n\t\t\treturn accumulator;\n\t\t}\n\n\t\tlet first = true;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (first) {\n\t\t\t\taccumulator = val as unknown as T;\n\t\t\t\tfirst = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\taccumulator = fn(accumulator, val, key, this);\n\t\t}\n\n\t\t// No items iterated.\n\t\tif (first) {\n\t\t\tthrow new TypeError('Reduce of empty collection with no initial value');\n\t\t}\n\n\t\treturn accumulator;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()},\n\t * but returns the collection instead of undefined.\n\t *\n\t * @param fn - Function to execute for each element\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .each(user => console.log(user.username))\n\t * .filter(user => user.bot)\n\t * .each(user => console.log(user.username));\n\t * ```\n\t */\n\tpublic each(fn: (value: V, key: K, collection: this) => void): this;\n\tpublic each(fn: (this: T, value: V, key: K, collection: this) => void, thisArg: T): this;\n\tpublic each(fn: (value: V, key: K, collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\t// eslint-disable-next-line unicorn/no-array-method-this-argument\n\t\tthis.forEach(fn as (value: V, key: K, map: Map) => void, thisArg);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a function on the collection and returns the collection.\n\t *\n\t * @param fn - Function to execute\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .tap(coll => console.log(coll.size))\n\t * .filter(user => user.bot)\n\t * .tap(coll => console.log(coll.size))\n\t * ```\n\t */\n\tpublic tap(fn: (collection: this) => void): this;\n\tpublic tap(fn: (this: T, collection: this) => void, thisArg: T): this;\n\tpublic tap(fn: (collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfn(this);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Creates an identical shallow copy of this collection.\n\t *\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.clone();\n\t * ```\n\t */\n\tpublic clone(): Collection {\n\t\treturn new this.constructor[Symbol.species](this);\n\t}\n\n\t/**\n\t * Combines this collection with others into a new collection. None of the source collections are modified.\n\t *\n\t * @param collections - Collections to merge\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);\n\t * ```\n\t */\n\tpublic concat(...collections: ReadonlyCollection[]) {\n\t\tconst newColl = this.clone();\n\t\tfor (const coll of collections) {\n\t\t\tfor (const [key, val] of coll) newColl.set(key, val);\n\t\t}\n\n\t\treturn newColl;\n\t}\n\n\t/**\n\t * Checks if this collection shares identical items with another.\n\t * This is different to checking for equality using equal-signs, because\n\t * the collections may be different objects, but contain the same data.\n\t *\n\t * @param collection - Collection to compare with\n\t * @returns Whether the collections have identical contents\n\t */\n\tpublic equals(collection: ReadonlyCollection) {\n\t\tif (!collection) return false; // runtime check\n\t\tif (this === collection) return true;\n\t\tif (this.size !== collection.size) return false;\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!collection.has(key) || value !== collection.get(key)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * The sort method sorts the items of a collection in place and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sort(compareFunction: Comparator = Collection.defaultSort) {\n\t\tconst entries = [...this.entries()];\n\t\tentries.sort((a, b): number => compareFunction(a[1], b[1], a[0], b[0]));\n\n\t\t// Perform clean-up\n\t\tsuper.clear();\n\n\t\t// Set the new entries\n\t\tfor (const [k, v] of entries) {\n\t\t\tsuper.set(k, v);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * The intersect method returns a new structure containing items where the keys and values are present in both original structures.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic intersect(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [k, v] of other) {\n\t\t\tif (this.has(k) && Object.is(v, this.get(k))) {\n\t\t\t\tcoll.set(k, v);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic subtract(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [k, v] of this) {\n\t\t\tif (!other.has(k) || !Object.is(v, other.get(k))) {\n\t\t\t\tcoll.set(k, v);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic difference(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [k, v] of other) {\n\t\t\tif (!this.has(k)) coll.set(k, v);\n\t\t}\n\n\t\tfor (const [k, v] of this) {\n\t\t\tif (!other.has(k)) coll.set(k, v);\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Merges two Collections together into a new Collection.\n\t *\n\t * @param other - The other Collection to merge with\n\t * @param whenInSelf - Function getting the result if the entry only exists in this Collection\n\t * @param whenInOther - Function getting the result if the entry only exists in the other Collection\n\t * @param whenInBoth - Function getting the result if the entry exists in both Collections\n\t * @example\n\t * ```ts\n\t * // Sums up the entries in two collections.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: true, value: x }),\n\t * y => ({ keep: true, value: y }),\n\t * (x, y) => ({ keep: true, value: x + y }),\n\t * );\n\t * ```\n\t * @example\n\t * ```ts\n\t * // Intersects two collections in a left-biased manner.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: false }),\n\t * y => ({ keep: false }),\n\t * (x, _) => ({ keep: true, value: x }),\n\t * );\n\t * ```\n\t */\n\tpublic merge(\n\t\tother: ReadonlyCollection,\n\t\twhenInSelf: (value: V, key: K) => Keep,\n\t\twhenInOther: (valueOther: T, key: K) => Keep,\n\t\twhenInBoth: (value: V, valueOther: T, key: K) => Keep,\n\t): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tconst keys = new Set([...this.keys(), ...other.keys()]);\n\t\tfor (const k of keys) {\n\t\t\tconst hasInSelf = this.has(k);\n\t\t\tconst hasInOther = other.has(k);\n\n\t\t\tif (hasInSelf && hasInOther) {\n\t\t\t\tconst r = whenInBoth(this.get(k)!, other.get(k)!, k);\n\t\t\t\tif (r.keep) coll.set(k, r.value);\n\t\t\t} else if (hasInSelf) {\n\t\t\t\tconst r = whenInSelf(this.get(k)!, k);\n\t\t\t\tif (r.keep) coll.set(k, r.value);\n\t\t\t} else if (hasInOther) {\n\t\t\t\tconst r = whenInOther(other.get(k)!, k);\n\t\t\t\tif (r.keep) coll.set(k, r.value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The sorted method sorts the items of a collection and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value,\n\t * according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sorted(compareFunction: Comparator = Collection.defaultSort) {\n\t\treturn new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk));\n\t}\n\n\tpublic toJSON() {\n\t\t// toJSON is called recursively by JSON.stringify.\n\t\treturn [...this.values()];\n\t}\n\n\tprivate static defaultSort(firstValue: V, secondValue: V): number {\n\t\treturn Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1;\n\t}\n\n\t/**\n\t * Creates a Collection from a list of entries.\n\t *\n\t * @param entries - The list of entries\n\t * @param combine - Function to combine an existing entry with a new one\n\t * @example\n\t * ```ts\n\t * Collection.combineEntries([[\"a\", 1], [\"b\", 2], [\"a\", 2]], (x, y) => x + y);\n\t * // returns Collection { \"a\" => 3, \"b\" => 2 }\n\t * ```\n\t */\n\tpublic static combineEntries(\n\t\tentries: Iterable<[K, V]>,\n\t\tcombine: (firstValue: V, secondValue: V, key: K) => V,\n\t): Collection {\n\t\tconst coll = new Collection();\n\t\tfor (const [k, v] of entries) {\n\t\t\tif (coll.has(k)) {\n\t\t\t\tcoll.set(k, combine(coll.get(k)!, v, k));\n\t\t\t} else {\n\t\t\t\tcoll.set(k, v);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n}\n\n/**\n * @internal\n */\nexport type Keep = { keep: false } | { keep: true; value: V };\n\n/**\n * @internal\n */\nexport type Comparator = (firstValue: V, secondValue: V, firstKey: K, secondKey: K) => number;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACsCO,IAAM,aAAN,cAA+B,IAAU;AAAA,EAWxC,OAAO,KAAQ,uBAA2D;AAChF,QAAI,KAAK,IAAI,GAAG;AAAG,aAAO,KAAK,IAAI,GAAG;AACtC,QAAI,OAAO,0BAA0B;AAAY,YAAM,IAAI,UAAU,GAAG,yCAAyC;AACjH,UAAM,eAAe,sBAAsB,KAAK,IAAI;AACpD,SAAK,IAAI,KAAK,YAAY;AAC1B,WAAO;AAAA,EACR;AAAA,EAQO,UAAU,MAAW;AAC3B,WAAO,KAAK,MAAM,CAAC,MAAM,MAAM,IAAI,CAAC,CAAC;AAAA,EACtC;AAAA,EAQO,UAAU,MAAW;AAC3B,WAAO,KAAK,KAAK,CAAC,MAAM,MAAM,IAAI,CAAC,CAAC;AAAA,EACrC;AAAA,EAUO,MAAM,QAAsC;AAClD,QAAI,OAAO,WAAW;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AAA,MAChC,WAAW,WAAW;AACrB,cAAM,IAAI,WAAW,KAAK,IAAI,CAAC,GAAI,CAAC;AACpC,YAAI,EAAE;AAAM,eAAK,IAAI,GAAG,EAAE,KAAK;AAAA,MAChC,WAAW,YAAY;AACtB,cAAM,IAAI,YAAY,MAAM,IAAI,CAAC,GAAI,CAAC;AACtC,YAAI,EAAE;AAAM,eAAK,IAAI,GAAG,EAAE,KAAK;AAAA,MAChC;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AAAA,EAeO,OAAO,kBAAoC,WAAW,aAAa;AACzE,WAAO,IAAI,KAAK,YAAY,OAAO,SAAS,IAAI,EAAE,KAAK,CAAC,IAAI,IAAI,IAAI,OAAO,gBAAgB,IAAI,IAAI,IAAI,EAAE,CAAC;AAAA,EAC3G;AAAA,EAEO,SAAS;AAEf,WAAO,CAAC,GAAG,KAAK,OAAO,CAAC;AAAA,EACzB;AAAA,EAEA,OAAe,YAAe,YAAe,aAAwB;AACpE,WAAO,OAAO,aAAa,WAAW,KAAK,OAAO,eAAe,WAAW,IAAI;AAAA,EACjF;AAAA,EAaA,OAAc,eACb,SACA,SACmB;AACnB,UAAM,OAAO,IAAI,WAAiB;AAClC,eAAW,CAAC,GAAG,CAAC,KAAK,SAAS;AAC7B,UAAI,KAAK,IAAI,CAAC,GAAG;AAChB,aAAK,IAAI,GAAG,QAAQ,KAAK,IAAI,CAAC,GAAI,GAAG,CAAC,CAAC;AAAA,MACxC,OAAO;AACN,aAAK,IAAI,GAAG,CAAC;AAAA,MACd;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AACD;AArxBa;;;AD9BN,IAAM,UAAkB;","names":[]} \ No newline at end of file +{"version":3,"sources":["../src/index.ts","../src/collection.ts"],"sourcesContent":["export * from './collection.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/collection/#readme | @discordjs/collection} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\nexport const version = '1.5.1' as string;\n","/* eslint-disable no-param-reassign */\n/**\n * @internal\n */\nexport interface CollectionConstructor {\n\tnew (): Collection;\n\tnew (entries?: readonly (readonly [K, V])[] | null): Collection;\n\tnew (iterable: Iterable): Collection;\n\treadonly prototype: Collection;\n\treadonly [Symbol.species]: CollectionConstructor;\n}\n\n/**\n * Represents an immutable version of a collection\n */\nexport type ReadonlyCollection = Omit<\n\tCollection,\n\t'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'\n> &\n\tReadonlyMap;\n\n/**\n * Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself\n *\n * @internal\n */\nexport interface Collection extends Map {\n\tconstructor: CollectionConstructor;\n}\n\n/**\n * A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has\n * an ID, for significantly improved performance and ease-of-use.\n *\n * @typeParam K - The key type this collection holds\n * @typeParam V - The value type this collection holds\n */\nexport class Collection extends Map {\n\t/**\n\t * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.\n\t *\n\t * @param key - The key to get if it exists, or set otherwise\n\t * @param defaultValueGenerator - A function that generates the default value\n\t * @example\n\t * ```ts\n\t * collection.ensure(guildId, () => defaultGuildConfig);\n\t * ```\n\t */\n\tpublic ensure(key: K, defaultValueGenerator: (key: K, collection: this) => V): V {\n\t\tif (this.has(key)) return this.get(key)!;\n\t\tif (typeof defaultValueGenerator !== 'function') throw new TypeError(`${defaultValueGenerator} is not a function`);\n\t\tconst defaultValue = defaultValueGenerator(key, this);\n\t\tthis.set(key, defaultValue);\n\t\treturn defaultValue;\n\t}\n\n\t/**\n\t * Checks if all of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if all of the elements exist, `false` if at least one does not exist.\n\t */\n\tpublic hasAll(...keys: K[]) {\n\t\treturn keys.every((key) => super.has(key));\n\t}\n\n\t/**\n\t * Checks if any of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if any of the elements exist, `false` if none exist.\n\t */\n\tpublic hasAny(...keys: K[]) {\n\t\treturn keys.some((key) => super.has(key));\n\t}\n\n\t/**\n\t * Obtains the first value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the beginning\n\t * @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative\n\t */\n\tpublic first(): V | undefined;\n\tpublic first(amount: number): V[];\n\tpublic first(amount?: number): V | V[] | undefined {\n\t\tif (amount === undefined) return this.values().next().value;\n\t\tif (amount < 0) return this.last(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.values();\n\t\treturn Array.from({ length: amount }, (): V => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the first key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the beginning\n\t * @returns A single key if no amount is provided or an array of keys, starting from the end if\n\t * amount is negative\n\t */\n\tpublic firstKey(): K | undefined;\n\tpublic firstKey(amount: number): K[];\n\tpublic firstKey(amount?: number): K | K[] | undefined {\n\t\tif (amount === undefined) return this.keys().next().value;\n\t\tif (amount < 0) return this.lastKey(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.keys();\n\t\treturn Array.from({ length: amount }, (): K => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the last value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the end\n\t * @returns A single value if no amount is provided or an array of values, starting from the start if\n\t * amount is negative\n\t */\n\tpublic last(): V | undefined;\n\tpublic last(amount: number): V[];\n\tpublic last(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (amount === undefined) return arr[arr.length - 1];\n\t\tif (amount < 0) return this.first(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Obtains the last key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the end\n\t * @returns A single key if no amount is provided or an array of keys, starting from the start if\n\t * amount is negative\n\t */\n\tpublic lastKey(): K | undefined;\n\tpublic lastKey(amount: number): K[];\n\tpublic lastKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (amount === undefined) return arr[arr.length - 1];\n\t\tif (amount < 0) return this.firstKey(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the item at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the element to obtain\n\t */\n\tpublic at(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.values()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the key at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the key to obtain\n\t */\n\tpublic keyAt(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.keys()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Obtains unique random value(s) from this collection.\n\t *\n\t * @param amount - Amount of values to obtain randomly\n\t * @returns A single value if no amount is provided or an array of values\n\t */\n\tpublic random(): V | undefined;\n\tpublic random(amount: number): V[];\n\tpublic random(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): V => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Obtains unique random key(s) from this collection.\n\t *\n\t * @param amount - Amount of keys to obtain randomly\n\t * @returns A single key if no amount is provided or an array\n\t */\n\tpublic randomKey(): K | undefined;\n\tpublic randomKey(amount: number): K[];\n\tpublic randomKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): K => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}\n\t * but returns a Collection instead of an Array.\n\t */\n\tpublic reverse() {\n\t\tconst entries = [...this.entries()].reverse();\n\t\tthis.clear();\n\t\tfor (const [key, value] of entries) this.set(key, value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Searches for a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.find()}.\n\t * All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you\n\t * should use the `get` method. See\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | MDN} for details.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.find(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic find(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown): V | undefined;\n\tpublic find(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): V2 | undefined;\n\tpublic find(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): V | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return val;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Searches for the key of a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.findIndex()},\n\t * but returns the key rather than the positional index.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.findKey(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic findKey(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined;\n\tpublic findKey(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): K2 | undefined;\n\tpublic findKey(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): K | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): K | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return key;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Removes items that satisfy the provided filter function.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @returns The number of removed entries\n\t */\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown): number;\n\tpublic sweep(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): number;\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): number {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst previousSize = this.size;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) this.delete(key);\n\t\t}\n\n\t\treturn previousSize - this.size;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.filter()},\n\t * but returns a Collection instead of an Array.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.filter(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic filter(fn: (value: V, key: K, collection: this) => key is K2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => value is V2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst results = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) results.set(key, val);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Partitions the collection into two collections where the first collection\n\t * contains the items that passed and the second contains the items that failed.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * const [big, small] = collection.partition(guild => guild.memberCount > 250);\n\t * ```\n\t */\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => key is K2,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => value is V2,\n\t): [Collection, Collection>];\n\tpublic partition(fn: (value: V, key: K, collection: this) => unknown): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): [Collection, Collection>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => unknown,\n\t\tthisArg: This,\n\t): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => unknown,\n\t\tthisArg?: unknown,\n\t): [Collection, Collection] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst results: [Collection, Collection] = [\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t];\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) {\n\t\t\t\tresults[0].set(key, val);\n\t\t\t} else {\n\t\t\t\tresults[1].set(key, val);\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.flatMap()}.\n\t *\n\t * @param fn - Function that produces a new Collection\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.flatMap(guild => guild.members.cache);\n\t * ```\n\t */\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection): Collection;\n\tpublic flatMap(\n\t\tfn: (this: This, value: V, key: K, collection: this) => Collection,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection, thisArg?: unknown): Collection {\n\t\t// eslint-disable-next-line unicorn/no-array-method-this-argument\n\t\tconst collections = this.map(fn, thisArg);\n\t\treturn new this.constructor[Symbol.species]().concat(...collections);\n\t}\n\n\t/**\n\t * Maps each item to another value into an array. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new array, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.map(user => user.tag);\n\t * ```\n\t */\n\tpublic map(fn: (value: V, key: K, collection: this) => T): T[];\n\tpublic map(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[];\n\tpublic map(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): T[] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst iter = this.entries();\n\t\treturn Array.from({ length: this.size }, (): T => {\n\t\t\tconst [key, value] = iter.next().value;\n\t\t\treturn fn(value, key, this);\n\t\t});\n\t}\n\n\t/**\n\t * Maps each item to another value into a collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new collection, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.mapValues(user => user.tag);\n\t * ```\n\t */\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T): Collection;\n\tpublic mapValues(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection;\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) coll.set(key, fn(val, key, this));\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Checks if there exists an item that passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.some()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.some(user => user.discriminator === '0000');\n\t * ```\n\t */\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic some(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): boolean;\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if all items passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.every()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.every(user => !user.bot);\n\t * ```\n\t */\n\tpublic every(fn: (value: V, key: K, collection: this) => key is K2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => value is V2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): boolean;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (!fn(val, key, this)) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Applies a function to produce a single value. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.\n\t *\n\t * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,\n\t * and `collection`\n\t * @param initialValue - Starting value for the accumulator\n\t * @example\n\t * ```ts\n\t * collection.reduce((acc, guild) => acc + guild.memberCount, 0);\n\t * ```\n\t */\n\tpublic reduce(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tlet accumulator!: T;\n\n\t\tif (initialValue !== undefined) {\n\t\t\taccumulator = initialValue;\n\t\t\tfor (const [key, val] of this) accumulator = fn(accumulator, val, key, this);\n\t\t\treturn accumulator;\n\t\t}\n\n\t\tlet first = true;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (first) {\n\t\t\t\taccumulator = val as unknown as T;\n\t\t\t\tfirst = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\taccumulator = fn(accumulator, val, key, this);\n\t\t}\n\n\t\t// No items iterated.\n\t\tif (first) {\n\t\t\tthrow new TypeError('Reduce of empty collection with no initial value');\n\t\t}\n\n\t\treturn accumulator;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()},\n\t * but returns the collection instead of undefined.\n\t *\n\t * @param fn - Function to execute for each element\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .each(user => console.log(user.username))\n\t * .filter(user => user.bot)\n\t * .each(user => console.log(user.username));\n\t * ```\n\t */\n\tpublic each(fn: (value: V, key: K, collection: this) => void): this;\n\tpublic each(fn: (this: T, value: V, key: K, collection: this) => void, thisArg: T): this;\n\tpublic each(fn: (value: V, key: K, collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\n\t\tfor (const [key, value] of this) {\n\t\t\tfn(value, key, this);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a function on the collection and returns the collection.\n\t *\n\t * @param fn - Function to execute\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .tap(coll => console.log(coll.size))\n\t * .filter(user => user.bot)\n\t * .tap(coll => console.log(coll.size))\n\t * ```\n\t */\n\tpublic tap(fn: (collection: this) => void): this;\n\tpublic tap(fn: (this: T, collection: this) => void, thisArg: T): this;\n\tpublic tap(fn: (collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfn(this);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Creates an identical shallow copy of this collection.\n\t *\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.clone();\n\t * ```\n\t */\n\tpublic clone(): Collection {\n\t\treturn new this.constructor[Symbol.species](this);\n\t}\n\n\t/**\n\t * Combines this collection with others into a new collection. None of the source collections are modified.\n\t *\n\t * @param collections - Collections to merge\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);\n\t * ```\n\t */\n\tpublic concat(...collections: ReadonlyCollection[]) {\n\t\tconst newColl = this.clone();\n\t\tfor (const coll of collections) {\n\t\t\tfor (const [key, val] of coll) newColl.set(key, val);\n\t\t}\n\n\t\treturn newColl;\n\t}\n\n\t/**\n\t * Checks if this collection shares identical items with another.\n\t * This is different to checking for equality using equal-signs, because\n\t * the collections may be different objects, but contain the same data.\n\t *\n\t * @param collection - Collection to compare with\n\t * @returns Whether the collections have identical contents\n\t */\n\tpublic equals(collection: ReadonlyCollection) {\n\t\tif (!collection) return false; // runtime check\n\t\tif (this === collection) return true;\n\t\tif (this.size !== collection.size) return false;\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!collection.has(key) || value !== collection.get(key)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * The sort method sorts the items of a collection in place and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sort(compareFunction: Comparator = Collection.defaultSort) {\n\t\tconst entries = [...this.entries()];\n\t\tentries.sort((a, b): number => compareFunction(a[1], b[1], a[0], b[0]));\n\n\t\t// Perform clean-up\n\t\tsuper.clear();\n\n\t\t// Set the new entries\n\t\tfor (const [key, value] of entries) {\n\t\t\tsuper.set(key, value);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * The intersect method returns a new structure containing items where the keys and values are present in both original structures.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic intersect(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of other) {\n\t\t\tif (this.has(key) && Object.is(value, this.get(key))) {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic subtract(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!other.has(key) || !Object.is(value, other.get(key))) {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic difference(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of other) {\n\t\t\tif (!this.has(key)) coll.set(key, value);\n\t\t}\n\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!other.has(key)) coll.set(key, value);\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Merges two Collections together into a new Collection.\n\t *\n\t * @param other - The other Collection to merge with\n\t * @param whenInSelf - Function getting the result if the entry only exists in this Collection\n\t * @param whenInOther - Function getting the result if the entry only exists in the other Collection\n\t * @param whenInBoth - Function getting the result if the entry exists in both Collections\n\t * @example\n\t * ```ts\n\t * // Sums up the entries in two collections.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: true, value: x }),\n\t * y => ({ keep: true, value: y }),\n\t * (x, y) => ({ keep: true, value: x + y }),\n\t * );\n\t * ```\n\t * @example\n\t * ```ts\n\t * // Intersects two collections in a left-biased manner.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: false }),\n\t * y => ({ keep: false }),\n\t * (x, _) => ({ keep: true, value: x }),\n\t * );\n\t * ```\n\t */\n\tpublic merge(\n\t\tother: ReadonlyCollection,\n\t\twhenInSelf: (value: V, key: K) => Keep,\n\t\twhenInOther: (valueOther: T, key: K) => Keep,\n\t\twhenInBoth: (value: V, valueOther: T, key: K) => Keep,\n\t): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tconst keys = new Set([...this.keys(), ...other.keys()]);\n\n\t\tfor (const key of keys) {\n\t\t\tconst hasInSelf = this.has(key);\n\t\t\tconst hasInOther = other.has(key);\n\n\t\t\tif (hasInSelf && hasInOther) {\n\t\t\t\tconst result = whenInBoth(this.get(key)!, other.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t} else if (hasInSelf) {\n\t\t\t\tconst result = whenInSelf(this.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t} else if (hasInOther) {\n\t\t\t\tconst result = whenInOther(other.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The sorted method sorts the items of a collection and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value,\n\t * according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sorted(compareFunction: Comparator = Collection.defaultSort) {\n\t\treturn new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk));\n\t}\n\n\tpublic toJSON() {\n\t\t// toJSON is called recursively by JSON.stringify.\n\t\treturn [...this.values()];\n\t}\n\n\tprivate static defaultSort(firstValue: V, secondValue: V): number {\n\t\treturn Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1;\n\t}\n\n\t/**\n\t * Creates a Collection from a list of entries.\n\t *\n\t * @param entries - The list of entries\n\t * @param combine - Function to combine an existing entry with a new one\n\t * @example\n\t * ```ts\n\t * Collection.combineEntries([[\"a\", 1], [\"b\", 2], [\"a\", 2]], (x, y) => x + y);\n\t * // returns Collection { \"a\" => 3, \"b\" => 2 }\n\t * ```\n\t */\n\tpublic static combineEntries(\n\t\tentries: Iterable<[K, V]>,\n\t\tcombine: (firstValue: V, secondValue: V, key: K) => V,\n\t): Collection {\n\t\tconst coll = new Collection();\n\t\tfor (const [key, value] of entries) {\n\t\t\tif (coll.has(key)) {\n\t\t\t\tcoll.set(key, combine(coll.get(key)!, value, key));\n\t\t\t} else {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n}\n\n/**\n * @internal\n */\nexport type Keep = { keep: false } | { keep: true; value: V };\n\n/**\n * @internal\n */\nexport type Comparator = (firstValue: V, secondValue: V, firstKey: K, secondKey: K) => number;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqCO,IAAM,aAAN,cAA+B,IAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWxC,OAAO,KAAQ,uBAA2D;AAChF,QAAI,KAAK,IAAI,GAAG;AAAG,aAAO,KAAK,IAAI,GAAG;AACtC,QAAI,OAAO,0BAA0B;AAAY,YAAM,IAAI,UAAU,GAAG,yCAAyC;AACjH,UAAM,eAAe,sBAAsB,KAAK,IAAI;AACpD,SAAK,IAAI,KAAK,YAAY;AAC1B,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQO,UAAU,MAAW;AAC3B,WAAO,KAAK,MAAM,CAAC,QAAQ,MAAM,IAAI,GAAG,CAAC;AAAA,EAC1C;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQO,UAAU,MAAW;AAC3B,WAAO,KAAK,KAAK,CAAC,QAAQ,MAAM,IAAI,GAAG,CAAC;AAAA,EACzC;AAAA,EAUO,MAAM,QAAsC;AAClD,QAAI,WAAW;AAAW,aAAO,KAAK,OAAO,EAAE,KAAK,EAAE;AACtD,QAAI,SAAS;AAAG,aAAO,KAAK,KAAK,SAAS,EAAE;AAC5C,aAAS,KAAK,IAAI,KAAK,MAAM,MAAM;AACnC,UAAM,OAAO,KAAK,OAAO;AACzB,WAAO,MAAM,KAAK,EAAE,QAAQ,OAAO,GAAG,MAAS,KAAK,KAAK,EAAE,KAAK;AAAA,EACjE;AAAA,EAWO,SAAS,QAAsC;AACrD,QAAI,WAAW;AAAW,aAAO,KAAK,KAAK,EAAE,KAAK,EAAE;AACpD,QAAI,SAAS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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,OAAc,eACb,SACA,SACmB;AACnB,UAAM,OAAO,IAAI,WAAiB;AAClC,eAAW,CAAC,KAAK,KAAK,KAAK,SAAS;AACnC,UAAI,KAAK,IAAI,GAAG,GAAG;AAClB,aAAK,IAAI,KAAK,QAAQ,KAAK,IAAI,GAAG,GAAI,OAAO,GAAG,CAAC;AAAA,MAClD,OAAO;AACN,aAAK,IAAI,KAAK,KAAK;AAAA,MACpB;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AACD;AA1xBa;;;AD9BN,IAAM,UAAU;","names":[]} \ No newline at end of file diff --git a/node_modules/@discordjs/collection/dist/index.mjs b/node_modules/@discordjs/collection/dist/index.mjs index 356e945..e968033 100644 --- a/node_modules/@discordjs/collection/dist/index.mjs +++ b/node_modules/@discordjs/collection/dist/index.mjs @@ -3,6 +3,16 @@ var __name = (target, value) => __defProp(target, "name", { value, configurable: // src/collection.ts var Collection = class extends Map { + /** + * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator. + * + * @param key - The key to get if it exists, or set otherwise + * @param defaultValueGenerator - A function that generates the default value + * @example + * ```ts + * collection.ensure(guildId, () => defaultGuildConfig); + * ``` + */ ensure(key, defaultValueGenerator) { if (this.has(key)) return this.get(key); @@ -12,14 +22,26 @@ var Collection = class extends Map { this.set(key, defaultValue); return defaultValue; } + /** + * Checks if all of the elements exist in the collection. + * + * @param keys - The keys of the elements to check for + * @returns `true` if all of the elements exist, `false` if at least one does not exist. + */ hasAll(...keys) { - return keys.every((k) => super.has(k)); - } + return keys.every((key) => super.has(key)); + } + /** + * Checks if any of the elements exist in the collection. + * + * @param keys - The keys of the elements to check for + * @returns `true` if any of the elements exist, `false` if none exist. + */ hasAny(...keys) { - return keys.some((k) => super.has(k)); + return keys.some((key) => super.has(key)); } first(amount) { - if (typeof amount === "undefined") + if (amount === void 0) return this.values().next().value; if (amount < 0) return this.last(amount * -1); @@ -28,7 +50,7 @@ var Collection = class extends Map { return Array.from({ length: amount }, () => iter.next().value); } firstKey(amount) { - if (typeof amount === "undefined") + if (amount === void 0) return this.keys().next().value; if (amount < 0) return this.lastKey(amount * -1); @@ -38,7 +60,7 @@ var Collection = class extends Map { } last(amount) { const arr = [...this.values()]; - if (typeof amount === "undefined") + if (amount === void 0) return arr[arr.length - 1]; if (amount < 0) return this.first(amount * -1); @@ -48,7 +70,7 @@ var Collection = class extends Map { } lastKey(amount) { const arr = [...this.keys()]; - if (typeof amount === "undefined") + if (amount === void 0) return arr[arr.length - 1]; if (amount < 0) return this.firstKey(amount * -1); @@ -56,11 +78,25 @@ var Collection = class extends Map { return []; return arr.slice(-amount); } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}. + * Returns the item at a given index, allowing for positive and negative integers. + * Negative integers count back from the last item in the collection. + * + * @param index - The index of the element to obtain + */ at(index) { index = Math.floor(index); const arr = [...this.values()]; return arr.at(index); } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}. + * Returns the key at a given index, allowing for positive and negative integers. + * Negative integers count back from the last item in the collection. + * + * @param index - The index of the key to obtain + */ keyAt(index) { index = Math.floor(index); const arr = [...this.keys()]; @@ -68,7 +104,7 @@ var Collection = class extends Map { } random(amount) { const arr = [...this.values()]; - if (typeof amount === "undefined") + if (amount === void 0) return arr[Math.floor(Math.random() * arr.length)]; if (!arr.length || !amount) return []; @@ -79,7 +115,7 @@ var Collection = class extends Map { } randomKey(amount) { const arr = [...this.keys()]; - if (typeof amount === "undefined") + if (amount === void 0) return arr[Math.floor(Math.random() * arr.length)]; if (!arr.length || !amount) return []; @@ -88,6 +124,10 @@ var Collection = class extends Map { () => arr.splice(Math.floor(Math.random() * arr.length), 1)[0] ); } + /** + * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()} + * but returns a Collection instead of an Array. + */ reverse() { const entries = [...this.entries()].reverse(); this.clear(); @@ -98,7 +138,7 @@ var Collection = class extends Map { find(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); for (const [key, val] of this) { if (fn(val, key, this)) @@ -109,7 +149,7 @@ var Collection = class extends Map { findKey(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); for (const [key, val] of this) { if (fn(val, key, this)) @@ -120,7 +160,7 @@ var Collection = class extends Map { sweep(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const previousSize = this.size; for (const [key, val] of this) { @@ -132,7 +172,7 @@ var Collection = class extends Map { filter(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const results = new this.constructor[Symbol.species](); for (const [key, val] of this) { @@ -144,7 +184,7 @@ var Collection = class extends Map { partition(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const results = [ new this.constructor[Symbol.species](), @@ -166,7 +206,7 @@ var Collection = class extends Map { map(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const iter = this.entries(); return Array.from({ length: this.size }, () => { @@ -177,7 +217,7 @@ var Collection = class extends Map { mapValues(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); const coll = new this.constructor[Symbol.species](); for (const [key, val] of this) @@ -187,7 +227,7 @@ var Collection = class extends Map { some(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); for (const [key, val] of this) { if (fn(val, key, this)) @@ -198,7 +238,7 @@ var Collection = class extends Map { every(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); for (const [key, val] of this) { if (!fn(val, key, this)) @@ -206,11 +246,23 @@ var Collection = class extends Map { } return true; } + /** + * Applies a function to produce a single value. Identical in behavior to + * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}. + * + * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`, + * and `collection` + * @param initialValue - Starting value for the accumulator + * @example + * ```ts + * collection.reduce((acc, guild) => acc + guild.memberCount, 0); + * ``` + */ reduce(fn, initialValue) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); let accumulator; - if (typeof initialValue !== "undefined") { + if (initialValue !== void 0) { accumulator = initialValue; for (const [key, val] of this) accumulator = fn(accumulator, val, key, this); @@ -233,20 +285,41 @@ var Collection = class extends Map { each(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - this.forEach(fn, thisArg); + if (thisArg !== void 0) + fn = fn.bind(thisArg); + for (const [key, value] of this) { + fn(value, key, this); + } return this; } tap(fn, thisArg) { if (typeof fn !== "function") throw new TypeError(`${fn} is not a function`); - if (typeof thisArg !== "undefined") + if (thisArg !== void 0) fn = fn.bind(thisArg); fn(this); return this; } + /** + * Creates an identical shallow copy of this collection. + * + * @example + * ```ts + * const newColl = someColl.clone(); + * ``` + */ clone() { return new this.constructor[Symbol.species](this); } + /** + * Combines this collection with others into a new collection. None of the source collections are modified. + * + * @param collections - Collections to merge + * @example + * ```ts + * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl); + * ``` + */ concat(...collections) { const newColl = this.clone(); for (const coll of collections) { @@ -255,6 +328,14 @@ var Collection = class extends Map { } return newColl; } + /** + * Checks if this collection shares identical items with another. + * This is different to checking for equality using equal-signs, because + * the collections may be different objects, but contain the same data. + * + * @param collection - Collection to compare with + * @returns Whether the collections have identical contents + */ equals(collection) { if (!collection) return false; @@ -269,67 +350,135 @@ var Collection = class extends Map { } return true; } + /** + * The sort method sorts the items of a collection in place and returns it. + * The sort is not necessarily stable in Node 10 or older. + * The default sort order is according to string Unicode code points. + * + * @param compareFunction - Specifies a function that defines the sort order. + * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element. + * @example + * ```ts + * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); + * ``` + */ sort(compareFunction = Collection.defaultSort) { const entries = [...this.entries()]; entries.sort((a, b) => compareFunction(a[1], b[1], a[0], b[0])); super.clear(); - for (const [k, v] of entries) { - super.set(k, v); + for (const [key, value] of entries) { + super.set(key, value); } return this; } + /** + * The intersect method returns a new structure containing items where the keys and values are present in both original structures. + * + * @param other - The other Collection to filter against + */ intersect(other) { const coll = new this.constructor[Symbol.species](); - for (const [k, v] of other) { - if (this.has(k) && Object.is(v, this.get(k))) { - coll.set(k, v); + for (const [key, value] of other) { + if (this.has(key) && Object.is(value, this.get(key))) { + coll.set(key, value); } } return coll; } + /** + * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other. + * + * @param other - The other Collection to filter against + */ subtract(other) { const coll = new this.constructor[Symbol.species](); - for (const [k, v] of this) { - if (!other.has(k) || !Object.is(v, other.get(k))) { - coll.set(k, v); + for (const [key, value] of this) { + if (!other.has(key) || !Object.is(value, other.get(key))) { + coll.set(key, value); } } return coll; } + /** + * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other. + * + * @param other - The other Collection to filter against + */ difference(other) { const coll = new this.constructor[Symbol.species](); - for (const [k, v] of other) { - if (!this.has(k)) - coll.set(k, v); + for (const [key, value] of other) { + if (!this.has(key)) + coll.set(key, value); } - for (const [k, v] of this) { - if (!other.has(k)) - coll.set(k, v); + for (const [key, value] of this) { + if (!other.has(key)) + coll.set(key, value); } return coll; } + /** + * Merges two Collections together into a new Collection. + * + * @param other - The other Collection to merge with + * @param whenInSelf - Function getting the result if the entry only exists in this Collection + * @param whenInOther - Function getting the result if the entry only exists in the other Collection + * @param whenInBoth - Function getting the result if the entry exists in both Collections + * @example + * ```ts + * // Sums up the entries in two collections. + * coll.merge( + * other, + * x => ({ keep: true, value: x }), + * y => ({ keep: true, value: y }), + * (x, y) => ({ keep: true, value: x + y }), + * ); + * ``` + * @example + * ```ts + * // Intersects two collections in a left-biased manner. + * coll.merge( + * other, + * x => ({ keep: false }), + * y => ({ keep: false }), + * (x, _) => ({ keep: true, value: x }), + * ); + * ``` + */ merge(other, whenInSelf, whenInOther, whenInBoth) { const coll = new this.constructor[Symbol.species](); const keys = /* @__PURE__ */ new Set([...this.keys(), ...other.keys()]); - for (const k of keys) { - const hasInSelf = this.has(k); - const hasInOther = other.has(k); + for (const key of keys) { + const hasInSelf = this.has(key); + const hasInOther = other.has(key); if (hasInSelf && hasInOther) { - const r = whenInBoth(this.get(k), other.get(k), k); - if (r.keep) - coll.set(k, r.value); + const result = whenInBoth(this.get(key), other.get(key), key); + if (result.keep) + coll.set(key, result.value); } else if (hasInSelf) { - const r = whenInSelf(this.get(k), k); - if (r.keep) - coll.set(k, r.value); + const result = whenInSelf(this.get(key), key); + if (result.keep) + coll.set(key, result.value); } else if (hasInOther) { - const r = whenInOther(other.get(k), k); - if (r.keep) - coll.set(k, r.value); + const result = whenInOther(other.get(key), key); + if (result.keep) + coll.set(key, result.value); } } return coll; } + /** + * The sorted method sorts the items of a collection and returns it. + * The sort is not necessarily stable in Node 10 or older. + * The default sort order is according to string Unicode code points. + * + * @param compareFunction - Specifies a function that defines the sort order. + * If omitted, the collection is sorted according to each character's Unicode code point value, + * according to the string conversion of each element. + * @example + * ```ts + * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp); + * ``` + */ sorted(compareFunction = Collection.defaultSort) { return new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk)); } @@ -339,13 +488,24 @@ var Collection = class extends Map { static defaultSort(firstValue, secondValue) { return Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1; } + /** + * Creates a Collection from a list of entries. + * + * @param entries - The list of entries + * @param combine - Function to combine an existing entry with a new one + * @example + * ```ts + * Collection.combineEntries([["a", 1], ["b", 2], ["a", 2]], (x, y) => x + y); + * // returns Collection { "a" => 3, "b" => 2 } + * ``` + */ static combineEntries(entries, combine) { const coll = new Collection(); - for (const [k, v] of entries) { - if (coll.has(k)) { - coll.set(k, combine(coll.get(k), v, k)); + for (const [key, value] of entries) { + if (coll.has(key)) { + coll.set(key, combine(coll.get(key), value, key)); } else { - coll.set(k, v); + coll.set(key, value); } } return coll; @@ -354,7 +514,7 @@ var Collection = class extends Map { __name(Collection, "Collection"); // src/index.ts -var version = "1.3.0"; +var version = "1.5.1"; export { Collection, version diff --git a/node_modules/@discordjs/collection/dist/index.mjs.map b/node_modules/@discordjs/collection/dist/index.mjs.map index be1999d..b736a28 100644 --- a/node_modules/@discordjs/collection/dist/index.mjs.map +++ b/node_modules/@discordjs/collection/dist/index.mjs.map @@ -1 +1 @@ -{"version":3,"sources":["../src/collection.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable id-length */\n/* eslint-disable no-param-reassign */\n/**\n * @internal\n */\nexport interface CollectionConstructor {\n\tnew (): Collection;\n\tnew (entries?: readonly (readonly [K, V])[] | null): Collection;\n\tnew (iterable: Iterable): Collection;\n\treadonly prototype: Collection;\n\treadonly [Symbol.species]: CollectionConstructor;\n}\n\n/**\n * Represents an immutable version of a collection\n */\nexport type ReadonlyCollection = Omit<\n\tCollection,\n\t'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'\n> &\n\tReadonlyMap;\n\n/**\n * Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself\n *\n * @internal\n */\nexport interface Collection extends Map {\n\tconstructor: CollectionConstructor;\n}\n\n/**\n * A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has\n * an ID, for significantly improved performance and ease-of-use.\n *\n * @typeParam K - The key type this collection holds\n * @typeParam V - The value type this collection holds\n */\nexport class Collection extends Map {\n\t/**\n\t * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.\n\t *\n\t * @param key - The key to get if it exists, or set otherwise\n\t * @param defaultValueGenerator - A function that generates the default value\n\t * @example\n\t * ```ts\n\t * collection.ensure(guildId, () => defaultGuildConfig);\n\t * ```\n\t */\n\tpublic ensure(key: K, defaultValueGenerator: (key: K, collection: this) => V): V {\n\t\tif (this.has(key)) return this.get(key)!;\n\t\tif (typeof defaultValueGenerator !== 'function') throw new TypeError(`${defaultValueGenerator} is not a function`);\n\t\tconst defaultValue = defaultValueGenerator(key, this);\n\t\tthis.set(key, defaultValue);\n\t\treturn defaultValue;\n\t}\n\n\t/**\n\t * Checks if all of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if all of the elements exist, `false` if at least one does not exist.\n\t */\n\tpublic hasAll(...keys: K[]) {\n\t\treturn keys.every((k) => super.has(k));\n\t}\n\n\t/**\n\t * Checks if any of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if any of the elements exist, `false` if none exist.\n\t */\n\tpublic hasAny(...keys: K[]) {\n\t\treturn keys.some((k) => super.has(k));\n\t}\n\n\t/**\n\t * Obtains the first value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the beginning\n\t * @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative\n\t */\n\tpublic first(): V | undefined;\n\tpublic first(amount: number): V[];\n\tpublic first(amount?: number): V | V[] | undefined {\n\t\tif (typeof amount === 'undefined') return this.values().next().value;\n\t\tif (amount < 0) return this.last(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.values();\n\t\treturn Array.from({ length: amount }, (): V => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the first key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the beginning\n\t * @returns A single key if no amount is provided or an array of keys, starting from the end if\n\t * amount is negative\n\t */\n\tpublic firstKey(): K | undefined;\n\tpublic firstKey(amount: number): K[];\n\tpublic firstKey(amount?: number): K | K[] | undefined {\n\t\tif (typeof amount === 'undefined') return this.keys().next().value;\n\t\tif (amount < 0) return this.lastKey(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.keys();\n\t\treturn Array.from({ length: amount }, (): K => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the last value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the end\n\t * @returns A single value if no amount is provided or an array of values, starting from the start if\n\t * amount is negative\n\t */\n\tpublic last(): V | undefined;\n\tpublic last(amount: number): V[];\n\tpublic last(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (typeof amount === 'undefined') return arr[arr.length - 1];\n\t\tif (amount < 0) return this.first(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Obtains the last key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the end\n\t * @returns A single key if no amount is provided or an array of keys, starting from the start if\n\t * amount is negative\n\t */\n\tpublic lastKey(): K | undefined;\n\tpublic lastKey(amount: number): K[];\n\tpublic lastKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (typeof amount === 'undefined') return arr[arr.length - 1];\n\t\tif (amount < 0) return this.firstKey(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the item at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the element to obtain\n\t */\n\tpublic at(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.values()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the key at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the key to obtain\n\t */\n\tpublic keyAt(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.keys()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Obtains unique random value(s) from this collection.\n\t *\n\t * @param amount - Amount of values to obtain randomly\n\t * @returns A single value if no amount is provided or an array of values\n\t */\n\tpublic random(): V | undefined;\n\tpublic random(amount: number): V[];\n\tpublic random(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (typeof amount === 'undefined') return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): V => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Obtains unique random key(s) from this collection.\n\t *\n\t * @param amount - Amount of keys to obtain randomly\n\t * @returns A single key if no amount is provided or an array\n\t */\n\tpublic randomKey(): K | undefined;\n\tpublic randomKey(amount: number): K[];\n\tpublic randomKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (typeof amount === 'undefined') return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): K => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}\n\t * but returns a Collection instead of an Array.\n\t */\n\tpublic reverse() {\n\t\tconst entries = [...this.entries()].reverse();\n\t\tthis.clear();\n\t\tfor (const [key, value] of entries) this.set(key, value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Searches for a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.find()}.\n\t * All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you\n\t * should use the `get` method. See\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | MDN} for details.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.find(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic find(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown): V | undefined;\n\tpublic find(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): V2 | undefined;\n\tpublic find(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): V | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return val;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Searches for the key of a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.findIndex()},\n\t * but returns the key rather than the positional index.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.findKey(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic findKey(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined;\n\tpublic findKey(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): K2 | undefined;\n\tpublic findKey(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): K | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): K | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return key;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Removes items that satisfy the provided filter function.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @returns The number of removed entries\n\t */\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown): number;\n\tpublic sweep(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): number;\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): number {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst previousSize = this.size;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) this.delete(key);\n\t\t}\n\n\t\treturn previousSize - this.size;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.filter()},\n\t * but returns a Collection instead of an Array.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.filter(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic filter(fn: (value: V, key: K, collection: this) => key is K2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => value is V2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst results = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) results.set(key, val);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Partitions the collection into two collections where the first collection\n\t * contains the items that passed and the second contains the items that failed.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * const [big, small] = collection.partition(guild => guild.memberCount > 250);\n\t * ```\n\t */\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => key is K2,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => value is V2,\n\t): [Collection, Collection>];\n\tpublic partition(fn: (value: V, key: K, collection: this) => unknown): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): [Collection, Collection>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => unknown,\n\t\tthisArg: This,\n\t): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => unknown,\n\t\tthisArg?: unknown,\n\t): [Collection, Collection] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst results: [Collection, Collection] = [\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t];\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) {\n\t\t\t\tresults[0].set(key, val);\n\t\t\t} else {\n\t\t\t\tresults[1].set(key, val);\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.flatMap()}.\n\t *\n\t * @param fn - Function that produces a new Collection\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.flatMap(guild => guild.members.cache);\n\t * ```\n\t */\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection): Collection;\n\tpublic flatMap(\n\t\tfn: (this: This, value: V, key: K, collection: this) => Collection,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection, thisArg?: unknown): Collection {\n\t\t// eslint-disable-next-line unicorn/no-array-method-this-argument\n\t\tconst collections = this.map(fn, thisArg);\n\t\treturn new this.constructor[Symbol.species]().concat(...collections);\n\t}\n\n\t/**\n\t * Maps each item to another value into an array. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new array, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.map(user => user.tag);\n\t * ```\n\t */\n\tpublic map(fn: (value: V, key: K, collection: this) => T): T[];\n\tpublic map(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[];\n\tpublic map(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): T[] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst iter = this.entries();\n\t\treturn Array.from({ length: this.size }, (): T => {\n\t\t\tconst [key, value] = iter.next().value;\n\t\t\treturn fn(value, key, this);\n\t\t});\n\t}\n\n\t/**\n\t * Maps each item to another value into a collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new collection, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.mapValues(user => user.tag);\n\t * ```\n\t */\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T): Collection;\n\tpublic mapValues(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection;\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) coll.set(key, fn(val, key, this));\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Checks if there exists an item that passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.some()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.some(user => user.discriminator === '0000');\n\t * ```\n\t */\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic some(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): boolean;\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if all items passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.every()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.every(user => !user.bot);\n\t * ```\n\t */\n\tpublic every(fn: (value: V, key: K, collection: this) => key is K2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => value is V2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): boolean;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (!fn(val, key, this)) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Applies a function to produce a single value. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.\n\t *\n\t * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,\n\t * and `collection`\n\t * @param initialValue - Starting value for the accumulator\n\t * @example\n\t * ```ts\n\t * collection.reduce((acc, guild) => acc + guild.memberCount, 0);\n\t * ```\n\t */\n\tpublic reduce(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tlet accumulator!: T;\n\n\t\tif (typeof initialValue !== 'undefined') {\n\t\t\taccumulator = initialValue;\n\t\t\tfor (const [key, val] of this) accumulator = fn(accumulator, val, key, this);\n\t\t\treturn accumulator;\n\t\t}\n\n\t\tlet first = true;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (first) {\n\t\t\t\taccumulator = val as unknown as T;\n\t\t\t\tfirst = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\taccumulator = fn(accumulator, val, key, this);\n\t\t}\n\n\t\t// No items iterated.\n\t\tif (first) {\n\t\t\tthrow new TypeError('Reduce of empty collection with no initial value');\n\t\t}\n\n\t\treturn accumulator;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()},\n\t * but returns the collection instead of undefined.\n\t *\n\t * @param fn - Function to execute for each element\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .each(user => console.log(user.username))\n\t * .filter(user => user.bot)\n\t * .each(user => console.log(user.username));\n\t * ```\n\t */\n\tpublic each(fn: (value: V, key: K, collection: this) => void): this;\n\tpublic each(fn: (this: T, value: V, key: K, collection: this) => void, thisArg: T): this;\n\tpublic each(fn: (value: V, key: K, collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\t// eslint-disable-next-line unicorn/no-array-method-this-argument\n\t\tthis.forEach(fn as (value: V, key: K, map: Map) => void, thisArg);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a function on the collection and returns the collection.\n\t *\n\t * @param fn - Function to execute\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .tap(coll => console.log(coll.size))\n\t * .filter(user => user.bot)\n\t * .tap(coll => console.log(coll.size))\n\t * ```\n\t */\n\tpublic tap(fn: (collection: this) => void): this;\n\tpublic tap(fn: (this: T, collection: this) => void, thisArg: T): this;\n\tpublic tap(fn: (collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (typeof thisArg !== 'undefined') fn = fn.bind(thisArg);\n\t\tfn(this);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Creates an identical shallow copy of this collection.\n\t *\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.clone();\n\t * ```\n\t */\n\tpublic clone(): Collection {\n\t\treturn new this.constructor[Symbol.species](this);\n\t}\n\n\t/**\n\t * Combines this collection with others into a new collection. None of the source collections are modified.\n\t *\n\t * @param collections - Collections to merge\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);\n\t * ```\n\t */\n\tpublic concat(...collections: ReadonlyCollection[]) {\n\t\tconst newColl = this.clone();\n\t\tfor (const coll of collections) {\n\t\t\tfor (const [key, val] of coll) newColl.set(key, val);\n\t\t}\n\n\t\treturn newColl;\n\t}\n\n\t/**\n\t * Checks if this collection shares identical items with another.\n\t * This is different to checking for equality using equal-signs, because\n\t * the collections may be different objects, but contain the same data.\n\t *\n\t * @param collection - Collection to compare with\n\t * @returns Whether the collections have identical contents\n\t */\n\tpublic equals(collection: ReadonlyCollection) {\n\t\tif (!collection) return false; // runtime check\n\t\tif (this === collection) return true;\n\t\tif (this.size !== collection.size) return false;\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!collection.has(key) || value !== collection.get(key)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * The sort method sorts the items of a collection in place and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sort(compareFunction: Comparator = Collection.defaultSort) {\n\t\tconst entries = [...this.entries()];\n\t\tentries.sort((a, b): number => compareFunction(a[1], b[1], a[0], b[0]));\n\n\t\t// Perform clean-up\n\t\tsuper.clear();\n\n\t\t// Set the new entries\n\t\tfor (const [k, v] of entries) {\n\t\t\tsuper.set(k, v);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * The intersect method returns a new structure containing items where the keys and values are present in both original structures.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic intersect(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [k, v] of other) {\n\t\t\tif (this.has(k) && Object.is(v, this.get(k))) {\n\t\t\t\tcoll.set(k, v);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic subtract(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [k, v] of this) {\n\t\t\tif (!other.has(k) || !Object.is(v, other.get(k))) {\n\t\t\t\tcoll.set(k, v);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic difference(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [k, v] of other) {\n\t\t\tif (!this.has(k)) coll.set(k, v);\n\t\t}\n\n\t\tfor (const [k, v] of this) {\n\t\t\tif (!other.has(k)) coll.set(k, v);\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Merges two Collections together into a new Collection.\n\t *\n\t * @param other - The other Collection to merge with\n\t * @param whenInSelf - Function getting the result if the entry only exists in this Collection\n\t * @param whenInOther - Function getting the result if the entry only exists in the other Collection\n\t * @param whenInBoth - Function getting the result if the entry exists in both Collections\n\t * @example\n\t * ```ts\n\t * // Sums up the entries in two collections.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: true, value: x }),\n\t * y => ({ keep: true, value: y }),\n\t * (x, y) => ({ keep: true, value: x + y }),\n\t * );\n\t * ```\n\t * @example\n\t * ```ts\n\t * // Intersects two collections in a left-biased manner.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: false }),\n\t * y => ({ keep: false }),\n\t * (x, _) => ({ keep: true, value: x }),\n\t * );\n\t * ```\n\t */\n\tpublic merge(\n\t\tother: ReadonlyCollection,\n\t\twhenInSelf: (value: V, key: K) => Keep,\n\t\twhenInOther: (valueOther: T, key: K) => Keep,\n\t\twhenInBoth: (value: V, valueOther: T, key: K) => Keep,\n\t): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tconst keys = new Set([...this.keys(), ...other.keys()]);\n\t\tfor (const k of keys) {\n\t\t\tconst hasInSelf = this.has(k);\n\t\t\tconst hasInOther = other.has(k);\n\n\t\t\tif (hasInSelf && hasInOther) {\n\t\t\t\tconst r = whenInBoth(this.get(k)!, other.get(k)!, k);\n\t\t\t\tif (r.keep) coll.set(k, r.value);\n\t\t\t} else if (hasInSelf) {\n\t\t\t\tconst r = whenInSelf(this.get(k)!, k);\n\t\t\t\tif (r.keep) coll.set(k, r.value);\n\t\t\t} else if (hasInOther) {\n\t\t\t\tconst r = whenInOther(other.get(k)!, k);\n\t\t\t\tif (r.keep) coll.set(k, r.value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The sorted method sorts the items of a collection and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value,\n\t * according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sorted(compareFunction: Comparator = Collection.defaultSort) {\n\t\treturn new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk));\n\t}\n\n\tpublic toJSON() {\n\t\t// toJSON is called recursively by JSON.stringify.\n\t\treturn [...this.values()];\n\t}\n\n\tprivate static defaultSort(firstValue: V, secondValue: V): number {\n\t\treturn Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1;\n\t}\n\n\t/**\n\t * Creates a Collection from a list of entries.\n\t *\n\t * @param entries - The list of entries\n\t * @param combine - Function to combine an existing entry with a new one\n\t * @example\n\t * ```ts\n\t * Collection.combineEntries([[\"a\", 1], [\"b\", 2], [\"a\", 2]], (x, y) => x + y);\n\t * // returns Collection { \"a\" => 3, \"b\" => 2 }\n\t * ```\n\t */\n\tpublic static combineEntries(\n\t\tentries: Iterable<[K, V]>,\n\t\tcombine: (firstValue: V, secondValue: V, key: K) => V,\n\t): Collection {\n\t\tconst coll = new Collection();\n\t\tfor (const [k, v] of entries) {\n\t\t\tif (coll.has(k)) {\n\t\t\t\tcoll.set(k, combine(coll.get(k)!, v, k));\n\t\t\t} else {\n\t\t\t\tcoll.set(k, v);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n}\n\n/**\n * @internal\n */\nexport type Keep = { keep: false } | { keep: true; value: V };\n\n/**\n * @internal\n */\nexport type Comparator = (firstValue: V, secondValue: V, firstKey: K, secondKey: K) => number;\n","export * from './collection.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/collection/#readme | @discordjs/collection} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const version: string = '1.3.0';\n"],"mappings":";;;;AAsCO,IAAM,aAAN,cAA+B,IAAU;AAAA,EAWxC,OAAO,KAAQ,uBAA2D;AAChF,QAAI,KAAK,IAAI,GAAG;AAAG,aAAO,KAAK,IAAI,GAAG;AACtC,QAAI,OAAO,0BAA0B;AAAY,YAAM,IAAI,UAAU,GAAG,yCAAyC;AACjH,UAAM,eAAe,sBAAsB,KAAK,IAAI;AACpD,SAAK,IAAI,KAAK,YAAY;AAC1B,WAAO;AAAA,EACR;AAAA,EAQO,UAAU,MAAW;AAC3B,WAAO,KAAK,MAAM,CAAC,MAAM,MAAM,IAAI,CAAC,CAAC;AAAA,EACtC;AAAA,EAQO,UAAU,MAAW;AAC3B,WAAO,KAAK,KAAK,CAAC,MAAM,MAAM,IAAI,CAAC,CAAC;AAAA,EACrC;AAAA,EAUO,MAAM,QAAsC;AAClD,QAAI,OAAO,WAAW;AAAa,aAAO,KAAK,OAAO,EAAE,KAAK,EAAE;AAC/D,QAAI,SAAS;AAAG,aAAO,KAAK,KAAK,SAAS,EAAE;AAC5C,aAAS,KAAK,IAAI,KAAK,MAAM,MAAM;AACnC,UAAM,OAAO,KAAK,OAAO;AACzB,WAAO,MAAM,KAAK,EAAE,QAAQ,OAAO,GAAG,MAAS,KAAK,KAAK,EAAE,KAAK;AAAA,EACjE;AAAA,EAWO,SAAS,QAAsC;AACrD,QAAI,OAAO,WAAW;AAAa,aAAO,KAAK,KAAK,EAAE,KAAK,EAAE;AAC7D,QAAI,SAAS;AAAG,aAAO,KAAK,QAAQ,SAAS,EAAE;AAC/C,aAAS,KAAK,IAAI,KAAK,MAAM,MAAM;AACnC,UAAM,OAAO,KAAK,KAAK;AACvB,WAAO,MAAM,KAAK,EAAE,QAAQ,OAAO,GAAG,MAAS,KAAK,KAAK,EAAE,KAAK;AAAA,EACjE;AAAA,EAWO,KAAK,QAAsC;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ACpE,WAAO,OAAO,aAAa,WAAW,KAAK,OAAO,eAAe,WAAW,IAAI;AAAA,EACjF;AAAA,EAaA,OAAc,eACb,SACA,SACmB;AACnB,UAAM,OAAO,IAAI,WAAiB;AAClC,eAAW,CAAC,GAAG,CAAC,KAAK,SAAS;AAC7B,UAAI,KAAK,IAAI,CAAC,GAAG;AAChB,aAAK,IAAI,GAAG,QAAQ,KAAK,IAAI,CAAC,GAAI,GAAG,CAAC,CAAC;AAAA,MACxC,OAAO;AACN,aAAK,IAAI,GAAG,CAAC;AAAA,MACd;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AACD;AArxBa;;;AC9BN,IAAM,UAAkB;","names":[]} \ No newline at end of file +{"version":3,"sources":["../src/collection.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable no-param-reassign */\n/**\n * @internal\n */\nexport interface CollectionConstructor {\n\tnew (): Collection;\n\tnew (entries?: readonly (readonly [K, V])[] | null): Collection;\n\tnew (iterable: Iterable): Collection;\n\treadonly prototype: Collection;\n\treadonly [Symbol.species]: CollectionConstructor;\n}\n\n/**\n * Represents an immutable version of a collection\n */\nexport type ReadonlyCollection = Omit<\n\tCollection,\n\t'delete' | 'ensure' | 'forEach' | 'get' | 'reverse' | 'set' | 'sort' | 'sweep'\n> &\n\tReadonlyMap;\n\n/**\n * Separate interface for the constructor so that emitted js does not have a constructor that overwrites itself\n *\n * @internal\n */\nexport interface Collection extends Map {\n\tconstructor: CollectionConstructor;\n}\n\n/**\n * A Map with additional utility methods. This is used throughout discord.js rather than Arrays for anything that has\n * an ID, for significantly improved performance and ease-of-use.\n *\n * @typeParam K - The key type this collection holds\n * @typeParam V - The value type this collection holds\n */\nexport class Collection extends Map {\n\t/**\n\t * Obtains the value of the given key if it exists, otherwise sets and returns the value provided by the default value generator.\n\t *\n\t * @param key - The key to get if it exists, or set otherwise\n\t * @param defaultValueGenerator - A function that generates the default value\n\t * @example\n\t * ```ts\n\t * collection.ensure(guildId, () => defaultGuildConfig);\n\t * ```\n\t */\n\tpublic ensure(key: K, defaultValueGenerator: (key: K, collection: this) => V): V {\n\t\tif (this.has(key)) return this.get(key)!;\n\t\tif (typeof defaultValueGenerator !== 'function') throw new TypeError(`${defaultValueGenerator} is not a function`);\n\t\tconst defaultValue = defaultValueGenerator(key, this);\n\t\tthis.set(key, defaultValue);\n\t\treturn defaultValue;\n\t}\n\n\t/**\n\t * Checks if all of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if all of the elements exist, `false` if at least one does not exist.\n\t */\n\tpublic hasAll(...keys: K[]) {\n\t\treturn keys.every((key) => super.has(key));\n\t}\n\n\t/**\n\t * Checks if any of the elements exist in the collection.\n\t *\n\t * @param keys - The keys of the elements to check for\n\t * @returns `true` if any of the elements exist, `false` if none exist.\n\t */\n\tpublic hasAny(...keys: K[]) {\n\t\treturn keys.some((key) => super.has(key));\n\t}\n\n\t/**\n\t * Obtains the first value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the beginning\n\t * @returns A single value if no amount is provided or an array of values, starting from the end if amount is negative\n\t */\n\tpublic first(): V | undefined;\n\tpublic first(amount: number): V[];\n\tpublic first(amount?: number): V | V[] | undefined {\n\t\tif (amount === undefined) return this.values().next().value;\n\t\tif (amount < 0) return this.last(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.values();\n\t\treturn Array.from({ length: amount }, (): V => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the first key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the beginning\n\t * @returns A single key if no amount is provided or an array of keys, starting from the end if\n\t * amount is negative\n\t */\n\tpublic firstKey(): K | undefined;\n\tpublic firstKey(amount: number): K[];\n\tpublic firstKey(amount?: number): K | K[] | undefined {\n\t\tif (amount === undefined) return this.keys().next().value;\n\t\tif (amount < 0) return this.lastKey(amount * -1);\n\t\tamount = Math.min(this.size, amount);\n\t\tconst iter = this.keys();\n\t\treturn Array.from({ length: amount }, (): K => iter.next().value);\n\t}\n\n\t/**\n\t * Obtains the last value(s) in this collection.\n\t *\n\t * @param amount - Amount of values to obtain from the end\n\t * @returns A single value if no amount is provided or an array of values, starting from the start if\n\t * amount is negative\n\t */\n\tpublic last(): V | undefined;\n\tpublic last(amount: number): V[];\n\tpublic last(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (amount === undefined) return arr[arr.length - 1];\n\t\tif (amount < 0) return this.first(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Obtains the last key(s) in this collection.\n\t *\n\t * @param amount - Amount of keys to obtain from the end\n\t * @returns A single key if no amount is provided or an array of keys, starting from the start if\n\t * amount is negative\n\t */\n\tpublic lastKey(): K | undefined;\n\tpublic lastKey(amount: number): K[];\n\tpublic lastKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (amount === undefined) return arr[arr.length - 1];\n\t\tif (amount < 0) return this.firstKey(amount * -1);\n\t\tif (!amount) return [];\n\t\treturn arr.slice(-amount);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the item at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the element to obtain\n\t */\n\tpublic at(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.values()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at | Array.at()}.\n\t * Returns the key at a given index, allowing for positive and negative integers.\n\t * Negative integers count back from the last item in the collection.\n\t *\n\t * @param index - The index of the key to obtain\n\t */\n\tpublic keyAt(index: number) {\n\t\tindex = Math.floor(index);\n\t\tconst arr = [...this.keys()];\n\t\treturn arr.at(index);\n\t}\n\n\t/**\n\t * Obtains unique random value(s) from this collection.\n\t *\n\t * @param amount - Amount of values to obtain randomly\n\t * @returns A single value if no amount is provided or an array of values\n\t */\n\tpublic random(): V | undefined;\n\tpublic random(amount: number): V[];\n\tpublic random(amount?: number): V | V[] | undefined {\n\t\tconst arr = [...this.values()];\n\t\tif (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): V => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Obtains unique random key(s) from this collection.\n\t *\n\t * @param amount - Amount of keys to obtain randomly\n\t * @returns A single key if no amount is provided or an array\n\t */\n\tpublic randomKey(): K | undefined;\n\tpublic randomKey(amount: number): K[];\n\tpublic randomKey(amount?: number): K | K[] | undefined {\n\t\tconst arr = [...this.keys()];\n\t\tif (amount === undefined) return arr[Math.floor(Math.random() * arr.length)];\n\t\tif (!arr.length || !amount) return [];\n\t\treturn Array.from(\n\t\t\t{ length: Math.min(amount, arr.length) },\n\t\t\t(): K => arr.splice(Math.floor(Math.random() * arr.length), 1)[0]!,\n\t\t);\n\t}\n\n\t/**\n\t * Identical to {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse | Array.reverse()}\n\t * but returns a Collection instead of an Array.\n\t */\n\tpublic reverse() {\n\t\tconst entries = [...this.entries()].reverse();\n\t\tthis.clear();\n\t\tfor (const [key, value] of entries) this.set(key, value);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Searches for a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find | Array.find()}.\n\t * All collections used in Discord.js are mapped using their `id` property, and if you want to find by id you\n\t * should use the `get` method. See\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/get | MDN} for details.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.find(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic find(fn: (value: V, key: K, collection: this) => value is V2): V2 | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown): V | undefined;\n\tpublic find(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): V2 | undefined;\n\tpublic find(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): V | undefined;\n\tpublic find(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): V | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return val;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Searches for the key of a single item where the given function returns a truthy value. This behaves like\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex | Array.findIndex()},\n\t * but returns the key rather than the positional index.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.findKey(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic findKey(fn: (value: V, key: K, collection: this) => key is K2): K2 | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown): K | undefined;\n\tpublic findKey(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): K2 | undefined;\n\tpublic findKey(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): K | undefined;\n\tpublic findKey(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): K | undefined {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return key;\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Removes items that satisfy the provided filter function.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @returns The number of removed entries\n\t */\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown): number;\n\tpublic sweep(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): number;\n\tpublic sweep(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): number {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst previousSize = this.size;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) this.delete(key);\n\t\t}\n\n\t\treturn previousSize - this.size;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter | Array.filter()},\n\t * but returns a Collection instead of an Array.\n\t *\n\t * @param fn - The function to test with (should return boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.filter(user => user.username === 'Bob');\n\t * ```\n\t */\n\tpublic filter(fn: (value: V, key: K, collection: this) => key is K2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => value is V2): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic filter(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): Collection;\n\tpublic filter(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst results = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) results.set(key, val);\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Partitions the collection into two collections where the first collection\n\t * contains the items that passed and the second contains the items that failed.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * const [big, small] = collection.partition(guild => guild.memberCount > 250);\n\t * ```\n\t */\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => key is K2,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => value is V2,\n\t): [Collection, Collection>];\n\tpublic partition(fn: (value: V, key: K, collection: this) => unknown): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): [Collection, Collection, V>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): [Collection, Collection>];\n\tpublic partition(\n\t\tfn: (this: This, value: V, key: K, collection: this) => unknown,\n\t\tthisArg: This,\n\t): [Collection, Collection];\n\tpublic partition(\n\t\tfn: (value: V, key: K, collection: this) => unknown,\n\t\tthisArg?: unknown,\n\t): [Collection, Collection] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst results: [Collection, Collection] = [\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t\tnew this.constructor[Symbol.species](),\n\t\t];\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) {\n\t\t\t\tresults[0].set(key, val);\n\t\t\t} else {\n\t\t\t\tresults[1].set(key, val);\n\t\t\t}\n\t\t}\n\n\t\treturn results;\n\t}\n\n\t/**\n\t * Maps each item into a Collection, then joins the results into a single Collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/flatMap | Array.flatMap()}.\n\t *\n\t * @param fn - Function that produces a new Collection\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.flatMap(guild => guild.members.cache);\n\t * ```\n\t */\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection): Collection;\n\tpublic flatMap(\n\t\tfn: (this: This, value: V, key: K, collection: this) => Collection,\n\t\tthisArg: This,\n\t): Collection;\n\tpublic flatMap(fn: (value: V, key: K, collection: this) => Collection, thisArg?: unknown): Collection {\n\t\t// eslint-disable-next-line unicorn/no-array-method-this-argument\n\t\tconst collections = this.map(fn, thisArg);\n\t\treturn new this.constructor[Symbol.species]().concat(...collections);\n\t}\n\n\t/**\n\t * Maps each item to another value into an array. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new array, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.map(user => user.tag);\n\t * ```\n\t */\n\tpublic map(fn: (value: V, key: K, collection: this) => T): T[];\n\tpublic map(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): T[];\n\tpublic map(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): T[] {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst iter = this.entries();\n\t\treturn Array.from({ length: this.size }, (): T => {\n\t\t\tconst [key, value] = iter.next().value;\n\t\t\treturn fn(value, key, this);\n\t\t});\n\t}\n\n\t/**\n\t * Maps each item to another value into a collection. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map | Array.map()}.\n\t *\n\t * @param fn - Function that produces an element of the new collection, taking three arguments\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.mapValues(user => user.tag);\n\t * ```\n\t */\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T): Collection;\n\tpublic mapValues(fn: (this: This, value: V, key: K, collection: this) => T, thisArg: This): Collection;\n\tpublic mapValues(fn: (value: V, key: K, collection: this) => T, thisArg?: unknown): Collection {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, val] of this) coll.set(key, fn(val, key, this));\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Checks if there exists an item that passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some | Array.some()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.some(user => user.discriminator === '0000');\n\t * ```\n\t */\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic some(fn: (this: T, value: V, key: K, collection: this) => unknown, thisArg: T): boolean;\n\tpublic some(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (fn(val, key, this)) return true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Checks if all items passes a test. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every | Array.every()}.\n\t *\n\t * @param fn - Function used to test (should return a boolean)\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection.every(user => !user.bot);\n\t * ```\n\t */\n\tpublic every(fn: (value: V, key: K, collection: this) => key is K2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => value is V2): this is Collection;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown): boolean;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => key is K2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(\n\t\tfn: (this: This, value: V, key: K, collection: this) => value is V2,\n\t\tthisArg: This,\n\t): this is Collection;\n\tpublic every(fn: (this: This, value: V, key: K, collection: this) => unknown, thisArg: This): boolean;\n\tpublic every(fn: (value: V, key: K, collection: this) => unknown, thisArg?: unknown): boolean {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfor (const [key, val] of this) {\n\t\t\tif (!fn(val, key, this)) return false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Applies a function to produce a single value. Identical in behavior to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce | Array.reduce()}.\n\t *\n\t * @param fn - Function used to reduce, taking four arguments; `accumulator`, `currentValue`, `currentKey`,\n\t * and `collection`\n\t * @param initialValue - Starting value for the accumulator\n\t * @example\n\t * ```ts\n\t * collection.reduce((acc, guild) => acc + guild.memberCount, 0);\n\t * ```\n\t */\n\tpublic reduce(fn: (accumulator: T, value: V, key: K, collection: this) => T, initialValue?: T): T {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tlet accumulator!: T;\n\n\t\tif (initialValue !== undefined) {\n\t\t\taccumulator = initialValue;\n\t\t\tfor (const [key, val] of this) accumulator = fn(accumulator, val, key, this);\n\t\t\treturn accumulator;\n\t\t}\n\n\t\tlet first = true;\n\t\tfor (const [key, val] of this) {\n\t\t\tif (first) {\n\t\t\t\taccumulator = val as unknown as T;\n\t\t\t\tfirst = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\taccumulator = fn(accumulator, val, key, this);\n\t\t}\n\n\t\t// No items iterated.\n\t\tif (first) {\n\t\t\tthrow new TypeError('Reduce of empty collection with no initial value');\n\t\t}\n\n\t\treturn accumulator;\n\t}\n\n\t/**\n\t * Identical to\n\t * {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map/forEach | Map.forEach()},\n\t * but returns the collection instead of undefined.\n\t *\n\t * @param fn - Function to execute for each element\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .each(user => console.log(user.username))\n\t * .filter(user => user.bot)\n\t * .each(user => console.log(user.username));\n\t * ```\n\t */\n\tpublic each(fn: (value: V, key: K, collection: this) => void): this;\n\tpublic each(fn: (this: T, value: V, key: K, collection: this) => void, thisArg: T): this;\n\tpublic each(fn: (value: V, key: K, collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\n\t\tfor (const [key, value] of this) {\n\t\t\tfn(value, key, this);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a function on the collection and returns the collection.\n\t *\n\t * @param fn - Function to execute\n\t * @param thisArg - Value to use as `this` when executing function\n\t * @example\n\t * ```ts\n\t * collection\n\t * .tap(coll => console.log(coll.size))\n\t * .filter(user => user.bot)\n\t * .tap(coll => console.log(coll.size))\n\t * ```\n\t */\n\tpublic tap(fn: (collection: this) => void): this;\n\tpublic tap(fn: (this: T, collection: this) => void, thisArg: T): this;\n\tpublic tap(fn: (collection: this) => void, thisArg?: unknown): this {\n\t\tif (typeof fn !== 'function') throw new TypeError(`${fn} is not a function`);\n\t\tif (thisArg !== undefined) fn = fn.bind(thisArg);\n\t\tfn(this);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Creates an identical shallow copy of this collection.\n\t *\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.clone();\n\t * ```\n\t */\n\tpublic clone(): Collection {\n\t\treturn new this.constructor[Symbol.species](this);\n\t}\n\n\t/**\n\t * Combines this collection with others into a new collection. None of the source collections are modified.\n\t *\n\t * @param collections - Collections to merge\n\t * @example\n\t * ```ts\n\t * const newColl = someColl.concat(someOtherColl, anotherColl, ohBoyAColl);\n\t * ```\n\t */\n\tpublic concat(...collections: ReadonlyCollection[]) {\n\t\tconst newColl = this.clone();\n\t\tfor (const coll of collections) {\n\t\t\tfor (const [key, val] of coll) newColl.set(key, val);\n\t\t}\n\n\t\treturn newColl;\n\t}\n\n\t/**\n\t * Checks if this collection shares identical items with another.\n\t * This is different to checking for equality using equal-signs, because\n\t * the collections may be different objects, but contain the same data.\n\t *\n\t * @param collection - Collection to compare with\n\t * @returns Whether the collections have identical contents\n\t */\n\tpublic equals(collection: ReadonlyCollection) {\n\t\tif (!collection) return false; // runtime check\n\t\tif (this === collection) return true;\n\t\tif (this.size !== collection.size) return false;\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!collection.has(key) || value !== collection.get(key)) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * The sort method sorts the items of a collection in place and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value, according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sort((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sort(compareFunction: Comparator = Collection.defaultSort) {\n\t\tconst entries = [...this.entries()];\n\t\tentries.sort((a, b): number => compareFunction(a[1], b[1], a[0], b[0]));\n\n\t\t// Perform clean-up\n\t\tsuper.clear();\n\n\t\t// Set the new entries\n\t\tfor (const [key, value] of entries) {\n\t\t\tsuper.set(key, value);\n\t\t}\n\n\t\treturn this;\n\t}\n\n\t/**\n\t * The intersect method returns a new structure containing items where the keys and values are present in both original structures.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic intersect(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of other) {\n\t\t\tif (this.has(key) && Object.is(value, this.get(key))) {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The subtract method returns a new structure containing items where the keys and values of the original structure are not present in the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic subtract(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!other.has(key) || !Object.is(value, other.get(key))) {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The difference method returns a new structure containing items where the key is present in one of the original structures but not the other.\n\t *\n\t * @param other - The other Collection to filter against\n\t */\n\tpublic difference(other: ReadonlyCollection): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tfor (const [key, value] of other) {\n\t\t\tif (!this.has(key)) coll.set(key, value);\n\t\t}\n\n\t\tfor (const [key, value] of this) {\n\t\t\tif (!other.has(key)) coll.set(key, value);\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * Merges two Collections together into a new Collection.\n\t *\n\t * @param other - The other Collection to merge with\n\t * @param whenInSelf - Function getting the result if the entry only exists in this Collection\n\t * @param whenInOther - Function getting the result if the entry only exists in the other Collection\n\t * @param whenInBoth - Function getting the result if the entry exists in both Collections\n\t * @example\n\t * ```ts\n\t * // Sums up the entries in two collections.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: true, value: x }),\n\t * y => ({ keep: true, value: y }),\n\t * (x, y) => ({ keep: true, value: x + y }),\n\t * );\n\t * ```\n\t * @example\n\t * ```ts\n\t * // Intersects two collections in a left-biased manner.\n\t * coll.merge(\n\t * other,\n\t * x => ({ keep: false }),\n\t * y => ({ keep: false }),\n\t * (x, _) => ({ keep: true, value: x }),\n\t * );\n\t * ```\n\t */\n\tpublic merge(\n\t\tother: ReadonlyCollection,\n\t\twhenInSelf: (value: V, key: K) => Keep,\n\t\twhenInOther: (valueOther: T, key: K) => Keep,\n\t\twhenInBoth: (value: V, valueOther: T, key: K) => Keep,\n\t): Collection {\n\t\tconst coll = new this.constructor[Symbol.species]();\n\t\tconst keys = new Set([...this.keys(), ...other.keys()]);\n\n\t\tfor (const key of keys) {\n\t\t\tconst hasInSelf = this.has(key);\n\t\t\tconst hasInOther = other.has(key);\n\n\t\t\tif (hasInSelf && hasInOther) {\n\t\t\t\tconst result = whenInBoth(this.get(key)!, other.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t} else if (hasInSelf) {\n\t\t\t\tconst result = whenInSelf(this.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t} else if (hasInOther) {\n\t\t\t\tconst result = whenInOther(other.get(key)!, key);\n\t\t\t\tif (result.keep) coll.set(key, result.value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n\n\t/**\n\t * The sorted method sorts the items of a collection and returns it.\n\t * The sort is not necessarily stable in Node 10 or older.\n\t * The default sort order is according to string Unicode code points.\n\t *\n\t * @param compareFunction - Specifies a function that defines the sort order.\n\t * If omitted, the collection is sorted according to each character's Unicode code point value,\n\t * according to the string conversion of each element.\n\t * @example\n\t * ```ts\n\t * collection.sorted((userA, userB) => userA.createdTimestamp - userB.createdTimestamp);\n\t * ```\n\t */\n\tpublic sorted(compareFunction: Comparator = Collection.defaultSort) {\n\t\treturn new this.constructor[Symbol.species](this).sort((av, bv, ak, bk) => compareFunction(av, bv, ak, bk));\n\t}\n\n\tpublic toJSON() {\n\t\t// toJSON is called recursively by JSON.stringify.\n\t\treturn [...this.values()];\n\t}\n\n\tprivate static defaultSort(firstValue: V, secondValue: V): number {\n\t\treturn Number(firstValue > secondValue) || Number(firstValue === secondValue) - 1;\n\t}\n\n\t/**\n\t * Creates a Collection from a list of entries.\n\t *\n\t * @param entries - The list of entries\n\t * @param combine - Function to combine an existing entry with a new one\n\t * @example\n\t * ```ts\n\t * Collection.combineEntries([[\"a\", 1], [\"b\", 2], [\"a\", 2]], (x, y) => x + y);\n\t * // returns Collection { \"a\" => 3, \"b\" => 2 }\n\t * ```\n\t */\n\tpublic static combineEntries(\n\t\tentries: Iterable<[K, V]>,\n\t\tcombine: (firstValue: V, secondValue: V, key: K) => V,\n\t): Collection {\n\t\tconst coll = new Collection();\n\t\tfor (const [key, value] of entries) {\n\t\t\tif (coll.has(key)) {\n\t\t\t\tcoll.set(key, combine(coll.get(key)!, value, key));\n\t\t\t} else {\n\t\t\t\tcoll.set(key, value);\n\t\t\t}\n\t\t}\n\n\t\treturn coll;\n\t}\n}\n\n/**\n * @internal\n */\nexport type Keep = { keep: false } | { keep: true; value: V };\n\n/**\n * @internal\n */\nexport type Comparator = (firstValue: V, secondValue: V, firstKey: K, secondKey: K) => number;\n","export * from './collection.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/collection/#readme | @discordjs/collection} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\nexport const version = '1.5.1' as string;\n"],"mappings":";;;;AAqCO,IAAM,aAAN,cAA+B,IAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAWxC,OAAO,KAAQ,uBAA2D;AAChF,QAAI,KAAK,IAAI,GAAG;AAAG,aAAO,KAAK,IAAI,GAAG;AACtC,QAAI,OAAO,0BAA0B;AAAY,YAAM,IAAI,UAAU,GAAG,yCAAyC;AACjH,UAAM,eAAe,sBAAsB,KAAK,IAAI;AACpD,SAAK,IAAI,KAAK,YAAY;AAC1B,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQO,UAAU,MAAW;AAC3B,WAAO,KAAK,MAAM,CAAC,QAAQ,MAAM,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,GAAG;AAC/C,YAAI,OAAO;AAAM,eAAK,IAAI,KAAK,OAAO,KAAK;AAAA,MAC5C;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAeO,OAAO,kBAAoC,WAAW,aAAa;AACzE,WAAO,IAAI,KAAK,YAAY,OAAO,OAAO,EAAE,IAAI,EAAE,KAAK,CAAC,IAAI,IAAI,IAAI,OAAO,gBAAgB,IAAI,IAAI,IAAI,EAAE,CAAC;AAAA,EAC3G;AAAA,EAEO,SAAS;AAEf,WAAO,CAAC,GAAG,KAAK,OAAO,CAAC;AAAA,EACzB;AAAA,EAEA,OAAe,YAAe,YAAe,aAAwB;AACpE,WAAO,OAAO,aAAa,WAAW,KAAK,OAAO,eAAe,WAAW,IAAI;AAAA,EACjF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAaA,OAAc,eACb,SACA,SACmB;AACnB,UAAM,OAAO,IAAI,WAAiB;AAClC,eAAW,CAAC,KAAK,KAAK,KAAK,SAAS;AACnC,UAAI,KAAK,IAAI,GAAG,GAAG;AAClB,aAAK,IAAI,KAAK,QAAQ,KAAK,IAAI,GAAG,GAAI,OAAO,GAAG,CAAC;AAAA,MAClD,OAAO;AACN,aAAK,IAAI,KAAK,KAAK;AAAA,MACpB;AAAA,IACD;AAEA,WAAO;AAAA,EACR;AACD;AA1xBa;;;AC9BN,IAAM,UAAU;","names":[]} \ No newline at end of file diff --git a/node_modules/@discordjs/collection/package.json b/node_modules/@discordjs/collection/package.json index b32766a..adbf426 100644 --- a/node_modules/@discordjs/collection/package.json +++ b/node_modules/@discordjs/collection/package.json @@ -1,115 +1,75 @@ { - "_from": "@discordjs/collection@^1.3.0", - "_id": "@discordjs/collection@1.3.0", - "_inBundle": false, - "_integrity": "sha512-ylt2NyZ77bJbRij4h9u/wVy7qYw/aDqQLWnadjvDqW/WoWCxrsX6M3CIw9GVP5xcGCDxsrKj5e0r5evuFYwrKg==", - "_location": "/@discordjs/collection", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@discordjs/collection@^1.3.0", - "name": "@discordjs/collection", - "escapedName": "@discordjs%2fcollection", - "scope": "@discordjs", - "rawSpec": "^1.3.0", - "saveSpec": null, - "fetchSpec": "^1.3.0" - }, - "_requiredBy": [ - "/@discordjs/rest", - "/discord.js" - ], - "_resolved": "https://registry.npmjs.org/@discordjs/collection/-/collection-1.3.0.tgz", - "_shasum": "65bf9674db72f38c25212be562bb28fa0dba6aa3", - "_spec": "@discordjs/collection@^1.3.0", - "_where": "D:\\programmen\\Discord bot\\CAROLINE\\node_modules\\discord.js", - "bugs": { - "url": "https://github.com/discordjs/discord.js/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Crawl", - "email": "icrawltogo@gmail.com" - }, - { - "name": "Amish Shah", - "email": "amishshah.2k@gmail.com" - }, - { - "name": "SpaceEEC", - "email": "spaceeec@yahoo.com" - }, - { - "name": "Vlad Frangu", - "email": "kingdgrizzle@gmail.com" - }, - { - "name": "Aura RomΓ‘n", - "email": "kyradiscord@gmail.com" - } - ], - "deprecated": false, + "name": "@discordjs/collection", + "version": "1.5.1", "description": "Utility data structure used in discord.js", - "devDependencies": { - "@favware/cliff-jumper": "^1.9.0", - "@microsoft/api-extractor": "^7.33.6", - "@types/node": "16.18.3", - "@vitest/coverage-c8": "^0.25.3", - "cross-env": "^7.0.3", - "esbuild-plugin-version-injector": "^1.0.2", - "eslint": "^8.28.0", - "eslint-config-neon": "^0.1.40", - "eslint-formatter-pretty": "^4.1.0", - "prettier": "^2.8.0", - "tsup": "^6.5.0", - "typescript": "^4.9.3", - "vitest": "^0.25.3" + "scripts": { + "test": "vitest run", + "build": "tsup", + "build:docs": "tsc -p tsconfig.docs.json", + "lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty", + "format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty", + "fmt": "yarn format", + "docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json", + "prepack": "yarn lint && yarn test && yarn build", + "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/collection/*'", + "release": "cliff-jumper" + }, + "main": "./dist/index.js", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", + "exports": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" }, "directories": { "lib": "src", "test": "__tests__" }, - "engines": { - "node": ">=16.9.0" - }, - "exports": { - "import": "./dist/index.mjs", - "require": "./dist/index.js", - "types": "./dist/index.d.ts" - }, "files": [ "dist" ], - "homepage": "https://discord.js.org", + "contributors": [ + "Crawl ", + "Amish Shah ", + "SpaceEEC ", + "Vlad Frangu ", + "Aura RomΓ‘n " + ], + "license": "Apache-2.0", "keywords": [ "map", "collection", "utility" ], - "license": "Apache-2.0", - "main": "./dist/index.js", - "module": "./dist/index.mjs", - "name": "@discordjs/collection", - "publishConfig": { - "access": "public" - }, "repository": { "type": "git", - "url": "git+https://github.com/discordjs/discord.js.git" + "url": "https://github.com/discordjs/discord.js.git", + "directory": "packages/collection" }, - "scripts": { - "build": "tsup", - "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/collection/*'", - "docs": "api-extractor run --local", - "fmt": "yarn format", - "format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty", - "lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty", - "prepack": "yarn lint && yarn test && yarn build", - "release": "cliff-jumper", - "test": "vitest run" + "bugs": { + "url": "https://github.com/discordjs/discord.js/issues" }, - "types": "./dist/index.d.ts", - "version": "1.3.0" -} + "homepage": "https://discord.js.org", + "devDependencies": { + "@favware/cliff-jumper": "^2.0.0", + "@microsoft/api-extractor": "^7.34.6", + "@types/node": "16.18.25", + "@vitest/coverage-c8": "^0.30.1", + "cross-env": "^7.0.3", + "esbuild-plugin-version-injector": "^1.1.0", + "eslint": "^8.39.0", + "eslint-config-neon": "^0.1.42", + "eslint-formatter-pretty": "^5.0.0", + "prettier": "^2.8.8", + "tsup": "^6.7.0", + "typescript": "^5.0.4", + "vitest": "^0.29.8" + }, + "engines": { + "node": ">=16.9.0" + }, + "publishConfig": { + "access": "public" + } +} \ No newline at end of file diff --git a/node_modules/@discordjs/formatters/CHANGELOG.md b/node_modules/@discordjs/formatters/CHANGELOG.md new file mode 100644 index 0000000..0eb93f0 --- /dev/null +++ b/node_modules/@discordjs/formatters/CHANGELOG.md @@ -0,0 +1,42 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +# [@discordjs/formatters@0.3.1](https://github.com/discordjs/discord.js/compare/@discordjs/formatters@0.3.0...@discordjs/formatters@0.3.1) - (2023-05-01) + +## Documentation + +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) +- **formatters:** Enhance the documentation (#9364) ([23e0ac5](https://github.com/discordjs/discord.js/commit/23e0ac56f456c39d925e2644ec3ca209d4410a99)) + +# [@discordjs/formatters@0.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/formatters@0.2.0...@discordjs/formatters@0.3.0) - (2023-04-01) + +## Bug Fixes + +- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b)) + +## Features + +- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b)) + +# [@discordjs/formatters@0.2.0](https://github.com/discordjs/discord.js/compare/@discordjs/formatters@0.1.0...@discordjs/formatters@0.2.0) - (2023-03-12) + +## Features + +- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38)) + +## Refactor + +- Compare with `undefined` directly (#9191) ([869153c](https://github.com/discordjs/discord.js/commit/869153c3fdf155783e7c0ecebd3627b087c3a026)) +- Moved the escapeX functions from discord.js to @discord.js/formatters (#8957) ([13ce78a](https://github.com/discordjs/discord.js/commit/13ce78af6e3aedc793f53a099a6a615df44311f7)) + +## Styling + +- Run prettier (#9041) ([2798ba1](https://github.com/discordjs/discord.js/commit/2798ba1eb3d734f0cf2eeccd2e16cfba6804873b)) + +# [@discordjs/formatters@0.1.0](https://github.com/discordjs/discord.js/tree/@discordjs/formatters@0.1.0) - (2022-12-16) + +## Features + +- Add `@discordjs/formatters` (#8889) ([3fca638](https://github.com/discordjs/discord.js/commit/3fca638a8470dcea2f79ddb9f18526dbc0017c88)) + diff --git a/node_modules/@discordjs/formatters/LICENSE b/node_modules/@discordjs/formatters/LICENSE new file mode 100644 index 0000000..e2baac1 --- /dev/null +++ b/node_modules/@discordjs/formatters/LICENSE @@ -0,0 +1,191 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + Copyright 2021 Noel Buechler + Copyright 2021 Vlad Frangu + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@discordjs/formatters/README.md b/node_modules/@discordjs/formatters/README.md new file mode 100644 index 0000000..92798d6 --- /dev/null +++ b/node_modules/@discordjs/formatters/README.md @@ -0,0 +1,80 @@ +
+
+

+ discord.js +

+
+

+ Discord server + npm version + npm downloads + Build status + Code coverage +

+

+ Vercel +

+
+ +## About + +`@discordjs/formatters` is a collection of functions for formatting strings to be used on Discord. + +## Installation + +**Node.js 16.9.0 or newer is required.** + +```sh +npm install @discordjs/formatters +yarn add @discordjs/formatters +pnpm add @discordjs/formatters +``` + +## Example usage + +````ts +import { codeBlock } from '@discordjs/formatters'; + +const formattedCode = codeBlock('hello world!'); +console.log(formattedCode); + +// Prints: +// ``` +// hello world! +// ``` +```` + +## Links + +- [Website][website] ([source][website-source]) +- [Documentation][documentation] +- [Guide][guide] ([source][guide-source]) + Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library. +- [discord.js Discord server][discord] +- [Discord API Discord server][discord-api] +- [GitHub][source] +- [npm][npm] +- [Related libraries][related-libs] + +## Contributing + +Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the +[documentation][documentation]. +See [the contribution guide][contributing] if you'd like to submit a PR. + +## Help + +If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. + +[website]: https://discord.js.org +[website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website +[documentation]: https://discord.js.org/docs/packages/formatters/stable +[guide]: https://discordjs.guide/ +[guide-source]: https://github.com/discordjs/guide +[guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html +[discord]: https://discord.gg/djs +[discord-api]: https://discord.gg/discord-api +[source]: https://github.com/discordjs/discord.js/tree/main/packages/formatters +[npm]: https://www.npmjs.com/package/@discordjs/formatters +[related-libs]: https://discord.com/developers/docs/topics/community-resources#libraries +[contributing]: https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md diff --git a/node_modules/@discordjs/formatters/dist/index.d.ts b/node_modules/@discordjs/formatters/dist/index.d.ts new file mode 100644 index 0000000..383d71a --- /dev/null +++ b/node_modules/@discordjs/formatters/dist/index.d.ts @@ -0,0 +1,511 @@ +import { URL } from 'node:url'; +import { Snowflake } from 'discord-api-types/globals'; + +/** + * The options that affect what will be escaped. + */ +interface EscapeMarkdownOptions { + /** + * Whether to escape bold text. + * + * @defaultValue `true` + */ + bold?: boolean; + /** + * Whether to escape bulleted lists. + * + * @defaultValue `false` + */ + bulletedList?: boolean; + /** + * Whether to escape code blocks. + * + * @defaultValue `true` + */ + codeBlock?: boolean; + /** + * Whether to escape text inside code blocks. + * + * @defaultValue `true` + */ + codeBlockContent?: boolean; + /** + * Whether to escape `\`. + * + * @defaultValue `true` + */ + escape?: boolean; + /** + * Whether to escape headings. + * + * @defaultValue `false` + */ + heading?: boolean; + /** + * Whether to escape inline code. + * + * @defaultValue `true` + */ + inlineCode?: boolean; + /** + * Whether to escape text inside inline code. + * + * @defaultValue `true` + */ + inlineCodeContent?: boolean; + /** + * Whether to escape italics. + * + * @defaultValue `true` + */ + italic?: boolean; + /** + * Whether to escape masked links. + * + * @defaultValue `false` + */ + maskedLink?: boolean; + /** + * Whether to escape numbered lists. + * + * @defaultValue `false` + */ + numberedList?: boolean; + /** + * Whether to escape spoilers. + * + * @defaultValue `true` + */ + spoiler?: boolean; + /** + * Whether to escape strikethroughs. + * + * @defaultValue `true` + */ + strikethrough?: boolean; + /** + * Whether to escape underlines. + * + * @defaultValue `true` + */ + underline?: boolean; +} +/** + * Escapes any Discord-flavored markdown in a string. + * + * @param text - Content to escape + * @param options - Options for escaping the markdown + */ +declare function escapeMarkdown(text: string, options?: EscapeMarkdownOptions): string; +/** + * Escapes code block markdown in a string. + * + * @param text - Content to escape + */ +declare function escapeCodeBlock(text: string): string; +/** + * Escapes inline code markdown in a string. + * + * @param text - Content to escape + */ +declare function escapeInlineCode(text: string): string; +/** + * Escapes italic markdown in a string. + * + * @param text - Content to escape + */ +declare function escapeItalic(text: string): string; +/** + * Escapes bold markdown in a string. + * + * @param text - Content to escape + */ +declare function escapeBold(text: string): string; +/** + * Escapes underline markdown in a string. + * + * @param text - Content to escape + */ +declare function escapeUnderline(text: string): string; +/** + * Escapes strikethrough markdown in a string. + * + * @param text - Content to escape + */ +declare function escapeStrikethrough(text: string): string; +/** + * Escapes spoiler markdown in a string. + * + * @param text - Content to escape + */ +declare function escapeSpoiler(text: string): string; +/** + * Escapes escape characters in a string. + * + * @param text - Content to escape + */ +declare function escapeEscape(text: string): string; +/** + * Escapes heading characters in a string. + * + * @param text - Content to escape + */ +declare function escapeHeading(text: string): string; +/** + * Escapes bulleted list characters in a string. + * + * @param text - Content to escape + */ +declare function escapeBulletedList(text: string): string; +/** + * Escapes numbered list characters in a string. + * + * @param text - Content to escape + */ +declare function escapeNumberedList(text: string): string; +/** + * Escapes masked link characters in a string. + * + * @param text - Content to escape + */ +declare function escapeMaskedLink(text: string): string; + +/** + * Wraps the content inside a code block with no language. + * + * @typeParam C - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function codeBlock(content: C): `\`\`\`\n${C}\n\`\`\``; +/** + * Wraps the content inside a code block with the specified language. + * + * @typeParam L - This is inferred by the supplied language + * @typeParam C - This is inferred by the supplied content + * @param language - The language for the code block + * @param content - The content to wrap + */ +declare function codeBlock(language: L, content: C): `\`\`\`${L}\n${C}\n\`\`\``; +/** + * Wraps the content inside \`backticks\` which formats it as inline code. + * + * @typeParam C - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function inlineCode(content: C): `\`${C}\``; +/** + * Formats the content into italic text. + * + * @typeParam C - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function italic(content: C): `_${C}_`; +/** + * Formats the content into bold text. + * + * @typeParam C - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function bold(content: C): `**${C}**`; +/** + * Formats the content into underscored text. + * + * @typeParam C - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function underscore(content: C): `__${C}__`; +/** + * Formats the content into strike-through text. + * + * @typeParam C - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function strikethrough(content: C): `~~${C}~~`; +/** + * Formats the content into a quote. + * + * @remarks This needs to be at the start of the line for Discord to format it. + * @typeParam C - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function quote(content: C): `> ${C}`; +/** + * Formats the content into a block quote. + * + * @remarks This needs to be at the start of the line for Discord to format it. + * @typeParam C - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function blockQuote(content: C): `>>> ${C}`; +/** + * Wraps the URL into `<>` which stops it from embedding. + * + * @typeParam C - This is inferred by the supplied content + * @param url - The URL to wrap + */ +declare function hideLinkEmbed(url: C): `<${C}>`; +/** + * Wraps the URL into `<>` which stops it from embedding. + * + * @param url - The URL to wrap + */ +declare function hideLinkEmbed(url: URL): `<${string}>`; +/** + * Formats the content and the URL into a masked URL. + * + * @typeParam C - This is inferred by the supplied content + * @param content - The content to display + * @param url - The URL the content links to + */ +declare function hyperlink(content: C, url: URL): `[${C}](${string})`; +/** + * Formats the content and the URL into a masked URL. + * + * @typeParam C - This is inferred by the supplied content + * @typeParam U - This is inferred by the supplied URL + * @param content - The content to display + * @param url - The URL the content links to + */ +declare function hyperlink(content: C, url: U): `[${C}](${U})`; +/** + * Formats the content and the URL into a masked URL with a custom tooltip. + * + * @typeParam C - This is inferred by the supplied content + * @typeParam T - This is inferred by the supplied title + * @param content - The content to display + * @param url - The URL the content links to + * @param title - The title shown when hovering on the masked link + */ +declare function hyperlink(content: C, url: URL, title: T): `[${C}](${string} "${T}")`; +/** + * Formats the content and the URL into a masked URL with a custom tooltip. + * + * @typeParam C - This is inferred by the supplied content + * @typeParam U - This is inferred by the supplied URL + * @typeParam T - This is inferred by the supplied title + * @param content - The content to display + * @param url - The URL the content links to + * @param title - The title shown when hovering on the masked link + */ +declare function hyperlink(content: C, url: U, title: T): `[${C}](${U} "${T}")`; +/** + * Formats the content into a spoiler. + * + * @typeParam C - This is inferred by the supplied content + * @param content - The content to wrap + */ +declare function spoiler(content: C): `||${C}||`; +/** + * Formats a user id into a user mention. + * + * @typeParam C - This is inferred by the supplied user id + * @param userId - The user id to format + */ +declare function userMention(userId: C): `<@${C}>`; +/** + * Formats a channel id into a channel mention. + * + * @typeParam C - This is inferred by the supplied channel id + * @param channelId - The channel id to format + */ +declare function channelMention(channelId: C): `<#${C}>`; +/** + * Formats a role id into a role mention. + * + * @typeParam C - This is inferred by the supplied role id + * @param roleId - The role id to format + */ +declare function roleMention(roleId: C): `<@&${C}>`; +/** + * Formats an application command name, subcommand group name, subcommand name, and id into an application command mention. + * + * @typeParam N - This is inferred by the supplied command name + * @typeParam G - This is inferred by the supplied subcommand group name + * @typeParam S - This is inferred by the supplied subcommand name + * @typeParam I - This is inferred by the supplied command id + * @param commandName - The application command name to format + * @param subcommandGroupName - The subcommand group name to format + * @param subcommandName - The subcommand name to format + * @param commandId - The application command id to format + */ +declare function chatInputApplicationCommandMention(commandName: N, subcommandGroupName: G, subcommandName: S, commandId: I): ``; +/** + * Formats an application command name, subcommand name, and id into an application command mention. + * + * @typeParam N - This is inferred by the supplied command name + * @typeParam S - This is inferred by the supplied subcommand name + * @typeParam I - This is inferred by the supplied command id + * @param commandName - The application command name to format + * @param subcommandName - The subcommand name to format + * @param commandId - The application command id to format + */ +declare function chatInputApplicationCommandMention(commandName: N, subcommandName: S, commandId: I): ``; +/** + * Formats an application command name and id into an application command mention. + * + * @typeParam N - This is inferred by the supplied command name + * @typeParam I - This is inferred by the supplied command id + * @param commandName - The application command name to format + * @param commandId - The application command id to format + */ +declare function chatInputApplicationCommandMention(commandName: N, commandId: I): ``; +/** + * Formats a non-animated emoji id into a fully qualified emoji identifier. + * + * @typeParam C - This is inferred by the supplied emoji id + * @param emojiId - The emoji id to format + */ +declare function formatEmoji(emojiId: C, animated?: false): `<:_:${C}>`; +/** + * Formats an animated emoji id into a fully qualified emoji identifier. + * + * @typeParam C - This is inferred by the supplied emoji id + * @param emojiId - The emoji id to format + * @param animated - Whether the emoji is animated + */ +declare function formatEmoji(emojiId: C, animated?: true): ``; +/** + * Formats an emoji id into a fully qualified emoji identifier. + * + * @typeParam C - This is inferred by the supplied emoji id + * @param emojiId - The emoji id to format + * @param animated - Whether the emoji is animated + */ +declare function formatEmoji(emojiId: C, animated?: boolean): `<:_:${C}>` | ``; +/** + * Formats a channel link for a direct message channel. + * + * @typeParam C - This is inferred by the supplied channel id + * @param channelId - The channel's id + */ +declare function channelLink(channelId: C): `https://discord.com/channels/@me/${C}`; +/** + * Formats a channel link for a guild channel. + * + * @typeParam C - This is inferred by the supplied channel id + * @typeParam G - This is inferred by the supplied guild id + * @param channelId - The channel's id + * @param guildId - The guild's id + */ +declare function channelLink(channelId: C, guildId: G): `https://discord.com/channels/${G}/${C}`; +/** + * Formats a message link for a direct message channel. + * + * @typeParam C - This is inferred by the supplied channel id + * @typeParam M - This is inferred by the supplied message id + * @param channelId - The channel's id + * @param messageId - The message's id + */ +declare function messageLink(channelId: C, messageId: M): `https://discord.com/channels/@me/${C}/${M}`; +/** + * Formats a message link for a guild channel. + * + * @typeParam C - This is inferred by the supplied channel id + * @typeParam M - This is inferred by the supplied message id + * @typeParam G - This is inferred by the supplied guild id + * @param channelId - The channel's id + * @param messageId - The message's id + * @param guildId - The guild's id + */ +declare function messageLink(channelId: C, messageId: M, guildId: G): `https://discord.com/channels/${G}/${C}/${M}`; +/** + * Formats a date into a short date-time string. + * + * @param date - The date to format. Defaults to the current time + */ +declare function time(date?: Date): ``; +/** + * Formats a date given a format style. + * + * @typeParam S - This is inferred by the supplied {@link TimestampStylesString} + * @param date - The date to format + * @param style - The style to use + */ +declare function time(date: Date, style: S): ``; +/** + * Formats the given timestamp into a short date-time string. + * + * @typeParam C - This is inferred by the supplied timestamp + * @param seconds - A Unix timestamp in seconds + */ +declare function time(seconds: C): ``; +/** + * Formats the given timestamp into a short date-time string. + * + * @typeParam C - This is inferred by the supplied timestamp + * @typeParam S - This is inferred by the supplied {@link TimestampStylesString} + * @param seconds - A Unix timestamp in seconds + * @param style - The style to use + */ +declare function time(seconds: C, style: S): ``; +/** + * The {@link https://discord.com/developers/docs/reference#message-formatting-timestamp-styles | message formatting timestamp styles} + * supported by Discord. + */ +declare const TimestampStyles: { + /** + * Short time format, consisting of hours and minutes. + * + * @example `16:20` + */ + readonly ShortTime: "t"; + /** + * Long time format, consisting of hours, minutes, and seconds. + * + * @example `16:20:30` + */ + readonly LongTime: "T"; + /** + * Short date format, consisting of day, month, and year. + * + * @example `20/04/2021` + */ + readonly ShortDate: "d"; + /** + * Long date format, consisting of day, month, and year. + * + * @example `20 April 2021` + */ + readonly LongDate: "D"; + /** + * Short date-time format, consisting of short date and short time formats. + * + * @example `20 April 2021 16:20` + */ + readonly ShortDateTime: "f"; + /** + * Long date-time format, consisting of long date and short time formats. + * + * @example `Tuesday, 20 April 2021 16:20` + */ + readonly LongDateTime: "F"; + /** + * Relative time format, consisting of a relative duration format. + * + * @example `2 months ago` + */ + readonly RelativeTime: "R"; +}; +/** + * The possible {@link TimestampStyles} values. + */ +type TimestampStylesString = (typeof TimestampStyles)[keyof typeof TimestampStyles]; +/** + * All the available faces from Discord's native slash commands. + */ +declare enum Faces { + /** + * `Β―\_(ツ)_/Β―` + */ + Shrug = "\u00AF_(\u30C4)_/\u00AF", + /** + * `(β•―Β°β–‘Β°)β•―οΈ΅ ┻━┻` + */ + Tableflip = "(\u256F\u00B0\u25A1\u00B0)\u256F\uFE35 \u253B\u2501\u253B", + /** + * `β”¬β”€β”¬γƒŽ( ΒΊ _ ΒΊγƒŽ)` + */ + Unflip = "\u252C\u2500\u252C\u30CE( \u00BA _ \u00BA\u30CE)" +} + +export { EscapeMarkdownOptions, Faces, TimestampStyles, TimestampStylesString, blockQuote, bold, channelLink, channelMention, chatInputApplicationCommandMention, codeBlock, escapeBold, escapeBulletedList, escapeCodeBlock, escapeEscape, escapeHeading, escapeInlineCode, escapeItalic, escapeMarkdown, escapeMaskedLink, escapeNumberedList, escapeSpoiler, escapeStrikethrough, escapeUnderline, formatEmoji, hideLinkEmbed, hyperlink, inlineCode, italic, messageLink, quote, roleMention, spoiler, strikethrough, time, underscore, userMention }; diff --git a/node_modules/@discordjs/formatters/dist/index.js b/node_modules/@discordjs/formatters/dist/index.js new file mode 100644 index 0000000..6fd2653 --- /dev/null +++ b/node_modules/@discordjs/formatters/dist/index.js @@ -0,0 +1,393 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/index.ts +var src_exports = {}; +__export(src_exports, { + Faces: () => Faces, + TimestampStyles: () => TimestampStyles, + blockQuote: () => blockQuote, + bold: () => bold, + channelLink: () => channelLink, + channelMention: () => channelMention, + chatInputApplicationCommandMention: () => chatInputApplicationCommandMention, + codeBlock: () => codeBlock, + escapeBold: () => escapeBold, + escapeBulletedList: () => escapeBulletedList, + escapeCodeBlock: () => escapeCodeBlock, + escapeEscape: () => escapeEscape, + escapeHeading: () => escapeHeading, + escapeInlineCode: () => escapeInlineCode, + escapeItalic: () => escapeItalic, + escapeMarkdown: () => escapeMarkdown, + escapeMaskedLink: () => escapeMaskedLink, + escapeNumberedList: () => escapeNumberedList, + escapeSpoiler: () => escapeSpoiler, + escapeStrikethrough: () => escapeStrikethrough, + escapeUnderline: () => escapeUnderline, + formatEmoji: () => formatEmoji, + hideLinkEmbed: () => hideLinkEmbed, + hyperlink: () => hyperlink, + inlineCode: () => inlineCode, + italic: () => italic, + messageLink: () => messageLink, + quote: () => quote, + roleMention: () => roleMention, + spoiler: () => spoiler, + strikethrough: () => strikethrough, + time: () => time, + underscore: () => underscore, + userMention: () => userMention +}); +module.exports = __toCommonJS(src_exports); + +// src/escapers.ts +function escapeMarkdown(text, options = {}) { + const { + codeBlock: codeBlock2 = true, + inlineCode: inlineCode2 = true, + bold: bold2 = true, + italic: italic2 = true, + underline = true, + strikethrough: strikethrough2 = true, + spoiler: spoiler2 = true, + codeBlockContent = true, + inlineCodeContent = true, + escape = true, + heading = false, + bulletedList = false, + numberedList = false, + maskedLink = false + } = options; + if (!codeBlockContent) { + return text.split("```").map((subString, index, array) => { + if (index % 2 && index !== array.length - 1) + return subString; + return escapeMarkdown(subString, { + inlineCode: inlineCode2, + bold: bold2, + italic: italic2, + underline, + strikethrough: strikethrough2, + spoiler: spoiler2, + inlineCodeContent, + escape, + heading, + bulletedList, + numberedList, + maskedLink + }); + }).join(codeBlock2 ? "\\`\\`\\`" : "```"); + } + if (!inlineCodeContent) { + return text.split(/(?<=^|[^`])`(?=[^`]|$)/g).map((subString, index, array) => { + if (index % 2 && index !== array.length - 1) + return subString; + return escapeMarkdown(subString, { + codeBlock: codeBlock2, + bold: bold2, + italic: italic2, + underline, + strikethrough: strikethrough2, + spoiler: spoiler2, + escape, + heading, + bulletedList, + numberedList, + maskedLink + }); + }).join(inlineCode2 ? "\\`" : "`"); + } + let res = text; + if (escape) + res = escapeEscape(res); + if (inlineCode2) + res = escapeInlineCode(res); + if (codeBlock2) + res = escapeCodeBlock(res); + if (italic2) + res = escapeItalic(res); + if (bold2) + res = escapeBold(res); + if (underline) + res = escapeUnderline(res); + if (strikethrough2) + res = escapeStrikethrough(res); + if (spoiler2) + 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; +} +__name(escapeMarkdown, "escapeMarkdown"); +function escapeCodeBlock(text) { + return text.replaceAll("```", "\\`\\`\\`"); +} +__name(escapeCodeBlock, "escapeCodeBlock"); +function escapeInlineCode(text) { + return text.replaceAll(/(?<=^|[^`])``?(?=[^`]|$)/g, (match) => match.length === 2 ? "\\`\\`" : "\\`"); +} +__name(escapeInlineCode, "escapeInlineCode"); +function escapeItalic(text) { + let idx = 0; + const newText = text.replaceAll(/(?<=^|[^*])\*([^*]|\*\*|$)/g, (_, match) => { + if (match === "**") + return ++idx % 2 ? `\\*${match}` : `${match}\\*`; + return `\\*${match}`; + }); + idx = 0; + return newText.replaceAll(/(?<=^|[^_])(?)([^_]|__|$)/g, (_, match) => { + if (match === "__") + return ++idx % 2 ? `\\_${match}` : `${match}\\_`; + return `\\_${match}`; + }); +} +__name(escapeItalic, "escapeItalic"); +function escapeBold(text) { + let idx = 0; + return text.replaceAll(/\*\*(\*)?/g, (_, match) => { + if (match) + return ++idx % 2 ? `${match}\\*\\*` : `\\*\\*${match}`; + return "\\*\\*"; + }); +} +__name(escapeBold, "escapeBold"); +function escapeUnderline(text) { + let idx = 0; + return text.replaceAll(/(?)/g, (_, match) => { + if (match) + return ++idx % 2 ? `${match}\\_\\_` : `\\_\\_${match}`; + return "\\_\\_"; + }); +} +__name(escapeUnderline, "escapeUnderline"); +function escapeStrikethrough(text) { + return text.replaceAll("~~", "\\~\\~"); +} +__name(escapeStrikethrough, "escapeStrikethrough"); +function escapeSpoiler(text) { + return text.replaceAll("||", "\\|\\|"); +} +__name(escapeSpoiler, "escapeSpoiler"); +function escapeEscape(text) { + return text.replaceAll("\\", "\\\\"); +} +__name(escapeEscape, "escapeEscape"); +function escapeHeading(text) { + return text.replaceAll(/^( {0,2})([*-] )?( *)(#{1,3} )/gm, "$1$2$3\\$4"); +} +__name(escapeHeading, "escapeHeading"); +function escapeBulletedList(text) { + return text.replaceAll(/^( *)([*-])( +)/gm, "$1\\$2$3"); +} +__name(escapeBulletedList, "escapeBulletedList"); +function escapeNumberedList(text) { + return text.replaceAll(/^( *\d+)\./gm, "$1\\."); +} +__name(escapeNumberedList, "escapeNumberedList"); +function escapeMaskedLink(text) { + return text.replaceAll(/\[.+]\(.+\)/gm, "\\$&"); +} +__name(escapeMaskedLink, "escapeMaskedLink"); + +// src/formatters.ts +function codeBlock(language, content) { + return content === void 0 ? `\`\`\` +${language} +\`\`\`` : `\`\`\`${language} +${content} +\`\`\``; +} +__name(codeBlock, "codeBlock"); +function inlineCode(content) { + return `\`${content}\``; +} +__name(inlineCode, "inlineCode"); +function italic(content) { + return `_${content}_`; +} +__name(italic, "italic"); +function bold(content) { + return `**${content}**`; +} +__name(bold, "bold"); +function underscore(content) { + return `__${content}__`; +} +__name(underscore, "underscore"); +function strikethrough(content) { + return `~~${content}~~`; +} +__name(strikethrough, "strikethrough"); +function quote(content) { + return `> ${content}`; +} +__name(quote, "quote"); +function blockQuote(content) { + return `>>> ${content}`; +} +__name(blockQuote, "blockQuote"); +function hideLinkEmbed(url) { + return `<${url}>`; +} +__name(hideLinkEmbed, "hideLinkEmbed"); +function hyperlink(content, url, title) { + return title ? `[${content}](${url} "${title}")` : `[${content}](${url})`; +} +__name(hyperlink, "hyperlink"); +function spoiler(content) { + return `||${content}||`; +} +__name(spoiler, "spoiler"); +function userMention(userId) { + return `<@${userId}>`; +} +__name(userMention, "userMention"); +function channelMention(channelId) { + return `<#${channelId}>`; +} +__name(channelMention, "channelMention"); +function roleMention(roleId) { + return `<@&${roleId}>`; +} +__name(roleMention, "roleMention"); +function chatInputApplicationCommandMention(commandName, subcommandGroupName, subcommandName, commandId) { + if (commandId !== void 0) { + return ``; + } + if (subcommandName !== void 0) { + return ``; + } + return ``; +} +__name(chatInputApplicationCommandMention, "chatInputApplicationCommandMention"); +function formatEmoji(emojiId, animated = false) { + return `<${animated ? "a" : ""}:_:${emojiId}>`; +} +__name(formatEmoji, "formatEmoji"); +function channelLink(channelId, guildId) { + return `https://discord.com/channels/${guildId ?? "@me"}/${channelId}`; +} +__name(channelLink, "channelLink"); +function messageLink(channelId, messageId, guildId) { + return `${guildId === void 0 ? channelLink(channelId) : channelLink(channelId, guildId)}/${messageId}`; +} +__name(messageLink, "messageLink"); +function time(timeOrSeconds, style) { + if (typeof timeOrSeconds !== "number") { + timeOrSeconds = Math.floor((timeOrSeconds?.getTime() ?? Date.now()) / 1e3); + } + return typeof style === "string" ? `` : ``; +} +__name(time, "time"); +var TimestampStyles = { + /** + * Short time format, consisting of hours and minutes. + * + * @example `16:20` + */ + ShortTime: "t", + /** + * Long time format, consisting of hours, minutes, and seconds. + * + * @example `16:20:30` + */ + LongTime: "T", + /** + * Short date format, consisting of day, month, and year. + * + * @example `20/04/2021` + */ + ShortDate: "d", + /** + * Long date format, consisting of day, month, and year. + * + * @example `20 April 2021` + */ + LongDate: "D", + /** + * Short date-time format, consisting of short date and short time formats. + * + * @example `20 April 2021 16:20` + */ + ShortDateTime: "f", + /** + * Long date-time format, consisting of long date and short time formats. + * + * @example `Tuesday, 20 April 2021 16:20` + */ + LongDateTime: "F", + /** + * Relative time format, consisting of a relative duration format. + * + * @example `2 months ago` + */ + RelativeTime: "R" +}; +var Faces = /* @__PURE__ */ ((Faces2) => { + Faces2["Shrug"] = "\xAF_(\u30C4)_/\xAF"; + Faces2["Tableflip"] = "(\u256F\xB0\u25A1\xB0)\u256F\uFE35 \u253B\u2501\u253B"; + Faces2["Unflip"] = "\u252C\u2500\u252C\u30CE( \xBA _ \xBA\u30CE)"; + return Faces2; +})(Faces || {}); +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + Faces, + TimestampStyles, + blockQuote, + bold, + channelLink, + channelMention, + chatInputApplicationCommandMention, + codeBlock, + escapeBold, + escapeBulletedList, + escapeCodeBlock, + escapeEscape, + escapeHeading, + escapeInlineCode, + escapeItalic, + escapeMarkdown, + escapeMaskedLink, + escapeNumberedList, + escapeSpoiler, + escapeStrikethrough, + escapeUnderline, + formatEmoji, + hideLinkEmbed, + hyperlink, + inlineCode, + italic, + messageLink, + quote, + roleMention, + spoiler, + strikethrough, + time, + underscore, + userMention +}); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@discordjs/formatters/dist/index.js.map b/node_modules/@discordjs/formatters/dist/index.js.map new file mode 100644 index 0000000..e65aa6c --- /dev/null +++ b/node_modules/@discordjs/formatters/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/index.ts","../src/escapers.ts","../src/formatters.ts"],"sourcesContent":["export * from './escapers.js';\nexport * from './formatters.js';\n","/* eslint-disable prefer-named-capture-group */\n\n/**\n * The options that affect what will be escaped.\n */\nexport interface EscapeMarkdownOptions {\n\t/**\n\t * Whether to escape bold text.\n\t *\n\t * @defaultValue `true`\n\t */\n\tbold?: boolean;\n\n\t/**\n\t * Whether to escape bulleted lists.\n\t *\n\t * @defaultValue `false`\n\t */\n\tbulletedList?: boolean;\n\n\t/**\n\t * Whether to escape code blocks.\n\t *\n\t * @defaultValue `true`\n\t */\n\tcodeBlock?: boolean;\n\n\t/**\n\t * Whether to escape text inside code blocks.\n\t *\n\t * @defaultValue `true`\n\t */\n\tcodeBlockContent?: boolean;\n\n\t/**\n\t * Whether to escape `\\`.\n\t *\n\t * @defaultValue `true`\n\t */\n\tescape?: boolean;\n\n\t/**\n\t * Whether to escape headings.\n\t *\n\t * @defaultValue `false`\n\t */\n\theading?: boolean;\n\n\t/**\n\t * Whether to escape inline code.\n\t *\n\t * @defaultValue `true`\n\t */\n\tinlineCode?: boolean;\n\n\t/**\n\t * Whether to escape text inside inline code.\n\t *\n\t * @defaultValue `true`\n\t */\n\tinlineCodeContent?: boolean;\n\t/**\n\t * Whether to escape italics.\n\t *\n\t * @defaultValue `true`\n\t */\n\titalic?: boolean;\n\n\t/**\n\t * Whether to escape masked links.\n\t *\n\t * @defaultValue `false`\n\t */\n\tmaskedLink?: boolean;\n\n\t/**\n\t * Whether to escape numbered lists.\n\t *\n\t * @defaultValue `false`\n\t */\n\tnumberedList?: boolean;\n\n\t/**\n\t * Whether to escape spoilers.\n\t *\n\t * @defaultValue `true`\n\t */\n\tspoiler?: boolean;\n\n\t/**\n\t * Whether to escape strikethroughs.\n\t *\n\t * @defaultValue `true`\n\t */\n\tstrikethrough?: boolean;\n\n\t/**\n\t * Whether to escape underlines.\n\t *\n\t * @defaultValue `true`\n\t */\n\tunderline?: boolean;\n}\n\n/**\n * Escapes any Discord-flavored markdown in a string.\n *\n * @param text - Content to escape\n * @param options - Options for escaping the markdown\n */\nexport function escapeMarkdown(text: string, options: EscapeMarkdownOptions = {}): string {\n\tconst {\n\t\tcodeBlock = true,\n\t\tinlineCode = true,\n\t\tbold = true,\n\t\titalic = true,\n\t\tunderline = true,\n\t\tstrikethrough = true,\n\t\tspoiler = true,\n\t\tcodeBlockContent = true,\n\t\tinlineCodeContent = true,\n\t\tescape = true,\n\t\theading = false,\n\t\tbulletedList = false,\n\t\tnumberedList = false,\n\t\tmaskedLink = false,\n\t} = options;\n\n\tif (!codeBlockContent) {\n\t\treturn text\n\t\t\t.split('```')\n\t\t\t.map((subString, index, array) => {\n\t\t\t\tif (index % 2 && index !== array.length - 1) return subString;\n\t\t\t\treturn escapeMarkdown(subString, {\n\t\t\t\t\tinlineCode,\n\t\t\t\t\tbold,\n\t\t\t\t\titalic,\n\t\t\t\t\tunderline,\n\t\t\t\t\tstrikethrough,\n\t\t\t\t\tspoiler,\n\t\t\t\t\tinlineCodeContent,\n\t\t\t\t\tescape,\n\t\t\t\t\theading,\n\t\t\t\t\tbulletedList,\n\t\t\t\t\tnumberedList,\n\t\t\t\t\tmaskedLink,\n\t\t\t\t});\n\t\t\t})\n\t\t\t.join(codeBlock ? '\\\\`\\\\`\\\\`' : '```');\n\t}\n\n\tif (!inlineCodeContent) {\n\t\treturn text\n\t\t\t.split(/(?<=^|[^`])`(?=[^`]|$)/g)\n\t\t\t.map((subString, index, array) => {\n\t\t\t\tif (index % 2 && index !== array.length - 1) return subString;\n\t\t\t\treturn escapeMarkdown(subString, {\n\t\t\t\t\tcodeBlock,\n\t\t\t\t\tbold,\n\t\t\t\t\titalic,\n\t\t\t\t\tunderline,\n\t\t\t\t\tstrikethrough,\n\t\t\t\t\tspoiler,\n\t\t\t\t\tescape,\n\t\t\t\t\theading,\n\t\t\t\t\tbulletedList,\n\t\t\t\t\tnumberedList,\n\t\t\t\t\tmaskedLink,\n\t\t\t\t});\n\t\t\t})\n\t\t\t.join(inlineCode ? '\\\\`' : '`');\n\t}\n\n\tlet res = text;\n\tif (escape) res = escapeEscape(res);\n\tif (inlineCode) res = escapeInlineCode(res);\n\tif (codeBlock) res = escapeCodeBlock(res);\n\tif (italic) res = escapeItalic(res);\n\tif (bold) res = escapeBold(res);\n\tif (underline) res = escapeUnderline(res);\n\tif (strikethrough) res = escapeStrikethrough(res);\n\tif (spoiler) res = escapeSpoiler(res);\n\tif (heading) res = escapeHeading(res);\n\tif (bulletedList) res = escapeBulletedList(res);\n\tif (numberedList) res = escapeNumberedList(res);\n\tif (maskedLink) res = escapeMaskedLink(res);\n\treturn res;\n}\n\n/**\n * Escapes code block markdown in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeCodeBlock(text: string): string {\n\treturn text.replaceAll('```', '\\\\`\\\\`\\\\`');\n}\n\n/**\n * Escapes inline code markdown in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeInlineCode(text: string): string {\n\treturn text.replaceAll(/(?<=^|[^`])``?(?=[^`]|$)/g, (match) => (match.length === 2 ? '\\\\`\\\\`' : '\\\\`'));\n}\n\n/**\n * Escapes italic markdown in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeItalic(text: string): string {\n\tlet idx = 0;\n\tconst newText = text.replaceAll(/(?<=^|[^*])\\*([^*]|\\*\\*|$)/g, (_, match) => {\n\t\tif (match === '**') return ++idx % 2 ? `\\\\*${match}` : `${match}\\\\*`;\n\t\treturn `\\\\*${match}`;\n\t});\n\tidx = 0;\n\treturn newText.replaceAll(/(?<=^|[^_])(?)([^_]|__|$)/g, (_, match) => {\n\t\tif (match === '__') return ++idx % 2 ? `\\\\_${match}` : `${match}\\\\_`;\n\t\treturn `\\\\_${match}`;\n\t});\n}\n\n/**\n * Escapes bold markdown in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeBold(text: string): string {\n\tlet idx = 0;\n\treturn text.replaceAll(/\\*\\*(\\*)?/g, (_, match) => {\n\t\tif (match) return ++idx % 2 ? `${match}\\\\*\\\\*` : `\\\\*\\\\*${match}`;\n\t\treturn '\\\\*\\\\*';\n\t});\n}\n\n/**\n * Escapes underline markdown in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeUnderline(text: string): string {\n\tlet idx = 0;\n\treturn text.replaceAll(/(?)/g, (_, match) => {\n\t\tif (match) return ++idx % 2 ? `${match}\\\\_\\\\_` : `\\\\_\\\\_${match}`;\n\t\treturn '\\\\_\\\\_';\n\t});\n}\n\n/**\n * Escapes strikethrough markdown in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeStrikethrough(text: string): string {\n\treturn text.replaceAll('~~', '\\\\~\\\\~');\n}\n\n/**\n * Escapes spoiler markdown in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeSpoiler(text: string): string {\n\treturn text.replaceAll('||', '\\\\|\\\\|');\n}\n\n/**\n * Escapes escape characters in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeEscape(text: string): string {\n\treturn text.replaceAll('\\\\', '\\\\\\\\');\n}\n\n/**\n * Escapes heading characters in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeHeading(text: string): string {\n\treturn text.replaceAll(/^( {0,2})([*-] )?( *)(#{1,3} )/gm, '$1$2$3\\\\$4');\n}\n\n/**\n * Escapes bulleted list characters in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeBulletedList(text: string): string {\n\treturn text.replaceAll(/^( *)([*-])( +)/gm, '$1\\\\$2$3');\n}\n\n/**\n * Escapes numbered list characters in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeNumberedList(text: string): string {\n\treturn text.replaceAll(/^( *\\d+)\\./gm, '$1\\\\.');\n}\n\n/**\n * Escapes masked link characters in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeMaskedLink(text: string): string {\n\treturn text.replaceAll(/\\[.+]\\(.+\\)/gm, '\\\\$&');\n}\n","import type { URL } from 'node:url';\nimport type { Snowflake } from 'discord-api-types/globals';\n\n/**\n * Wraps the content inside a code block with no language.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function codeBlock(content: C): `\\`\\`\\`\\n${C}\\n\\`\\`\\``;\n\n/**\n * Wraps the content inside a code block with the specified language.\n *\n * @typeParam L - This is inferred by the supplied language\n * @typeParam C - This is inferred by the supplied content\n * @param language - The language for the code block\n * @param content - The content to wrap\n */\nexport function codeBlock(language: L, content: C): `\\`\\`\\`${L}\\n${C}\\n\\`\\`\\``;\n\nexport function codeBlock(language: string, content?: string): string {\n\treturn content === undefined ? `\\`\\`\\`\\n${language}\\n\\`\\`\\`` : `\\`\\`\\`${language}\\n${content}\\n\\`\\`\\``;\n}\n\n/**\n * Wraps the content inside \\`backticks\\` which formats it as inline code.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function inlineCode(content: C): `\\`${C}\\`` {\n\treturn `\\`${content}\\``;\n}\n\n/**\n * Formats the content into italic text.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function italic(content: C): `_${C}_` {\n\treturn `_${content}_`;\n}\n\n/**\n * Formats the content into bold text.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function bold(content: C): `**${C}**` {\n\treturn `**${content}**`;\n}\n\n/**\n * Formats the content into underscored text.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function underscore(content: C): `__${C}__` {\n\treturn `__${content}__`;\n}\n\n/**\n * Formats the content into strike-through text.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function strikethrough(content: C): `~~${C}~~` {\n\treturn `~~${content}~~`;\n}\n\n/**\n * Formats the content into a quote.\n *\n * @remarks This needs to be at the start of the line for Discord to format it.\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function quote(content: C): `> ${C}` {\n\treturn `> ${content}`;\n}\n\n/**\n * Formats the content into a block quote.\n *\n * @remarks This needs to be at the start of the line for Discord to format it.\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function blockQuote(content: C): `>>> ${C}` {\n\treturn `>>> ${content}`;\n}\n\n/**\n * Wraps the URL into `<>` which stops it from embedding.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param url - The URL to wrap\n */\nexport function hideLinkEmbed(url: C): `<${C}>`;\n\n/**\n * Wraps the URL into `<>` which stops it from embedding.\n *\n * @param url - The URL to wrap\n */\nexport function hideLinkEmbed(url: URL): `<${string}>`;\n\nexport function hideLinkEmbed(url: URL | string) {\n\treturn `<${url}>`;\n}\n\n/**\n * Formats the content and the URL into a masked URL.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to display\n * @param url - The URL the content links to\n */\nexport function hyperlink(content: C, url: URL): `[${C}](${string})`;\n\n/**\n * Formats the content and the URL into a masked URL.\n *\n * @typeParam C - This is inferred by the supplied content\n * @typeParam U - This is inferred by the supplied URL\n * @param content - The content to display\n * @param url - The URL the content links to\n */\nexport function hyperlink(content: C, url: U): `[${C}](${U})`;\n\n/**\n * Formats the content and the URL into a masked URL with a custom tooltip.\n *\n * @typeParam C - This is inferred by the supplied content\n * @typeParam T - This is inferred by the supplied title\n * @param content - The content to display\n * @param url - The URL the content links to\n * @param title - The title shown when hovering on the masked link\n */\nexport function hyperlink(\n\tcontent: C,\n\turl: URL,\n\ttitle: T,\n): `[${C}](${string} \"${T}\")`;\n\n/**\n * Formats the content and the URL into a masked URL with a custom tooltip.\n *\n * @typeParam C - This is inferred by the supplied content\n * @typeParam U - This is inferred by the supplied URL\n * @typeParam T - This is inferred by the supplied title\n * @param content - The content to display\n * @param url - The URL the content links to\n * @param title - The title shown when hovering on the masked link\n */\nexport function hyperlink(\n\tcontent: C,\n\turl: U,\n\ttitle: T,\n): `[${C}](${U} \"${T}\")`;\n\nexport function hyperlink(content: string, url: URL | string, title?: string) {\n\treturn title ? `[${content}](${url} \"${title}\")` : `[${content}](${url})`;\n}\n\n/**\n * Formats the content into a spoiler.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function spoiler(content: C): `||${C}||` {\n\treturn `||${content}||`;\n}\n\n/**\n * Formats a user id into a user mention.\n *\n * @typeParam C - This is inferred by the supplied user id\n * @param userId - The user id to format\n */\nexport function userMention(userId: C): `<@${C}>` {\n\treturn `<@${userId}>`;\n}\n\n/**\n * Formats a channel id into a channel mention.\n *\n * @typeParam C - This is inferred by the supplied channel id\n * @param channelId - The channel id to format\n */\nexport function channelMention(channelId: C): `<#${C}>` {\n\treturn `<#${channelId}>`;\n}\n\n/**\n * Formats a role id into a role mention.\n *\n * @typeParam C - This is inferred by the supplied role id\n * @param roleId - The role id to format\n */\nexport function roleMention(roleId: C): `<@&${C}>` {\n\treturn `<@&${roleId}>`;\n}\n\n/**\n * Formats an application command name, subcommand group name, subcommand name, and id into an application command mention.\n *\n * @typeParam N - This is inferred by the supplied command name\n * @typeParam G - This is inferred by the supplied subcommand group name\n * @typeParam S - This is inferred by the supplied subcommand name\n * @typeParam I - This is inferred by the supplied command id\n * @param commandName - The application command name to format\n * @param subcommandGroupName - The subcommand group name to format\n * @param subcommandName - The subcommand name to format\n * @param commandId - The application command id to format\n */\nexport function chatInputApplicationCommandMention<\n\tN extends string,\n\tG extends string,\n\tS extends string,\n\tI extends Snowflake,\n>(commandName: N, subcommandGroupName: G, subcommandName: S, commandId: I): ``;\n\n/**\n * Formats an application command name, subcommand name, and id into an application command mention.\n *\n * @typeParam N - This is inferred by the supplied command name\n * @typeParam S - This is inferred by the supplied subcommand name\n * @typeParam I - This is inferred by the supplied command id\n * @param commandName - The application command name to format\n * @param subcommandName - The subcommand name to format\n * @param commandId - The application command id to format\n */\nexport function chatInputApplicationCommandMention(\n\tcommandName: N,\n\tsubcommandName: S,\n\tcommandId: I,\n): ``;\n\n/**\n * Formats an application command name and id into an application command mention.\n *\n * @typeParam N - This is inferred by the supplied command name\n * @typeParam I - This is inferred by the supplied command id\n * @param commandName - The application command name to format\n * @param commandId - The application command id to format\n */\nexport function chatInputApplicationCommandMention(\n\tcommandName: N,\n\tcommandId: I,\n): ``;\n\nexport function chatInputApplicationCommandMention<\n\tN extends string,\n\tG extends Snowflake | string,\n\tS extends Snowflake | string,\n\tI extends Snowflake,\n>(\n\tcommandName: N,\n\tsubcommandGroupName: G,\n\tsubcommandName?: S,\n\tcommandId?: I,\n): `` | `` | `` {\n\tif (commandId !== undefined) {\n\t\treturn ``;\n\t}\n\n\tif (subcommandName !== undefined) {\n\t\treturn ``;\n\t}\n\n\treturn ``;\n}\n\n/**\n * Formats a non-animated emoji id into a fully qualified emoji identifier.\n *\n * @typeParam C - This is inferred by the supplied emoji id\n * @param emojiId - The emoji id to format\n */\nexport function formatEmoji(emojiId: C, animated?: false): `<:_:${C}>`;\n\n/**\n * Formats an animated emoji id into a fully qualified emoji identifier.\n *\n * @typeParam C - This is inferred by the supplied emoji id\n * @param emojiId - The emoji id to format\n * @param animated - Whether the emoji is animated\n */\nexport function formatEmoji(emojiId: C, animated?: true): ``;\n\n/**\n * Formats an emoji id into a fully qualified emoji identifier.\n *\n * @typeParam C - This is inferred by the supplied emoji id\n * @param emojiId - The emoji id to format\n * @param animated - Whether the emoji is animated\n */\nexport function formatEmoji(emojiId: C, animated?: boolean): `<:_:${C}>` | ``;\n\nexport function formatEmoji(emojiId: C, animated = false): `<:_:${C}>` | `` {\n\treturn `<${animated ? 'a' : ''}:_:${emojiId}>`;\n}\n\n/**\n * Formats a channel link for a direct message channel.\n *\n * @typeParam C - This is inferred by the supplied channel id\n * @param channelId - The channel's id\n */\nexport function channelLink(channelId: C): `https://discord.com/channels/@me/${C}`;\n\n/**\n * Formats a channel link for a guild channel.\n *\n * @typeParam C - This is inferred by the supplied channel id\n * @typeParam G - This is inferred by the supplied guild id\n * @param channelId - The channel's id\n * @param guildId - The guild's id\n */\nexport function channelLink(\n\tchannelId: C,\n\tguildId: G,\n): `https://discord.com/channels/${G}/${C}`;\n\nexport function channelLink(\n\tchannelId: C,\n\tguildId?: G,\n): `https://discord.com/channels/@me/${C}` | `https://discord.com/channels/${G}/${C}` {\n\treturn `https://discord.com/channels/${guildId ?? '@me'}/${channelId}`;\n}\n\n/**\n * Formats a message link for a direct message channel.\n *\n * @typeParam C - This is inferred by the supplied channel id\n * @typeParam M - This is inferred by the supplied message id\n * @param channelId - The channel's id\n * @param messageId - The message's id\n */\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n): `https://discord.com/channels/@me/${C}/${M}`;\n\n/**\n * Formats a message link for a guild channel.\n *\n * @typeParam C - This is inferred by the supplied channel id\n * @typeParam M - This is inferred by the supplied message id\n * @typeParam G - This is inferred by the supplied guild id\n * @param channelId - The channel's id\n * @param messageId - The message's id\n * @param guildId - The guild's id\n */\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n\tguildId: G,\n): `https://discord.com/channels/${G}/${C}/${M}`;\n\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n\tguildId?: G,\n): `https://discord.com/channels/@me/${C}/${M}` | `https://discord.com/channels/${G}/${C}/${M}` {\n\treturn `${guildId === undefined ? channelLink(channelId) : channelLink(channelId, guildId)}/${messageId}`;\n}\n\n/**\n * Formats a date into a short date-time string.\n *\n * @param date - The date to format. Defaults to the current time\n */\nexport function time(date?: Date): ``;\n\n/**\n * Formats a date given a format style.\n *\n * @typeParam S - This is inferred by the supplied {@link TimestampStylesString}\n * @param date - The date to format\n * @param style - The style to use\n */\nexport function time(date: Date, style: S): ``;\n\n/**\n * Formats the given timestamp into a short date-time string.\n *\n * @typeParam C - This is inferred by the supplied timestamp\n * @param seconds - A Unix timestamp in seconds\n */\nexport function time(seconds: C): ``;\n\n/**\n * Formats the given timestamp into a short date-time string.\n *\n * @typeParam C - This is inferred by the supplied timestamp\n * @typeParam S - This is inferred by the supplied {@link TimestampStylesString}\n * @param seconds - A Unix timestamp in seconds\n * @param style - The style to use\n */\nexport function time(seconds: C, style: S): ``;\n\nexport function time(timeOrSeconds?: Date | number, style?: TimestampStylesString): string {\n\tif (typeof timeOrSeconds !== 'number') {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\ttimeOrSeconds = Math.floor((timeOrSeconds?.getTime() ?? Date.now()) / 1_000);\n\t}\n\n\treturn typeof style === 'string' ? `` : ``;\n}\n\n/**\n * The {@link https://discord.com/developers/docs/reference#message-formatting-timestamp-styles | message formatting timestamp styles}\n * supported by Discord.\n */\nexport const TimestampStyles = {\n\t/**\n\t * Short time format, consisting of hours and minutes.\n\t *\n\t * @example `16:20`\n\t */\n\tShortTime: 't',\n\n\t/**\n\t * Long time format, consisting of hours, minutes, and seconds.\n\t *\n\t * @example `16:20:30`\n\t */\n\tLongTime: 'T',\n\n\t/**\n\t * Short date format, consisting of day, month, and year.\n\t *\n\t * @example `20/04/2021`\n\t */\n\tShortDate: 'd',\n\n\t/**\n\t * Long date format, consisting of day, month, and year.\n\t *\n\t * @example `20 April 2021`\n\t */\n\tLongDate: 'D',\n\n\t/**\n\t * Short date-time format, consisting of short date and short time formats.\n\t *\n\t * @example `20 April 2021 16:20`\n\t */\n\tShortDateTime: 'f',\n\n\t/**\n\t * Long date-time format, consisting of long date and short time formats.\n\t *\n\t * @example `Tuesday, 20 April 2021 16:20`\n\t */\n\tLongDateTime: 'F',\n\n\t/**\n\t * Relative time format, consisting of a relative duration format.\n\t *\n\t * @example `2 months ago`\n\t */\n\tRelativeTime: 'R',\n} as const satisfies Record;\n\n/**\n * The possible {@link TimestampStyles} values.\n */\nexport type TimestampStylesString = (typeof TimestampStyles)[keyof typeof TimestampStyles];\n\n// prettier-ignore\n/**\n * All the available faces from Discord's native slash commands.\n */\nexport enum Faces {\n\t/**\n\t * `Β―\\_(ツ)_/Β―`\n\t */\n\t// eslint-disable-next-line no-useless-escape\n\tShrug = 'Β―\\_(ツ)_/Β―',\n\n\t/**\n\t * `(β•―Β°β–‘Β°)β•―οΈ΅ ┻━┻`\n\t */\n\tTableflip = '(β•―Β°β–‘Β°)β•―οΈ΅ ┻━┻',\n\n\t/**\n\t * `β”¬β”€β”¬γƒŽ( ΒΊ _ ΒΊγƒŽ)`\n\t */\n\tUnflip = 'β”¬β”€β”¬γƒŽ( ΒΊ _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,SAAS,KAAK,eAA+B,OAAuC;AAC1F,MAAI,OAAO,kBAAkB,UAAU;AAEtC,oBAAgB,KAAK,OAAO,eAAe,QAAQ,KAAK,KAAK,IAAI,KAAK,GAAK;AAAA,EAC5E;AAEA,SAAO,OAAO,UAAU,WAAW,MAAM,iBAAiB,WAAW,MAAM;AAC5E;AAPgB;AAaT,IAAM,kBAAkB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAM9B,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOX,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOV,WAAW;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOX,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOV,eAAe;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOf,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOd,cAAc;AACf;AAWO,IAAK,QAAL,kBAAKC,WAAL;AAKN,EAAAA,OAAA,WAAQ;AAKR,EAAAA,OAAA,eAAY;AAKZ,EAAAA,OAAA,YAAS;AAfE,SAAAA;AAAA,GAAA;","names":["codeBlock","inlineCode","bold","italic","strikethrough","spoiler","Faces"]} \ No newline at end of file diff --git a/node_modules/@discordjs/formatters/dist/index.mjs b/node_modules/@discordjs/formatters/dist/index.mjs new file mode 100644 index 0000000..82a6f65 --- /dev/null +++ b/node_modules/@discordjs/formatters/dist/index.mjs @@ -0,0 +1,335 @@ +var __defProp = Object.defineProperty; +var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); + +// src/escapers.ts +function escapeMarkdown(text, options = {}) { + const { + codeBlock: codeBlock2 = true, + inlineCode: inlineCode2 = true, + bold: bold2 = true, + italic: italic2 = true, + underline = true, + strikethrough: strikethrough2 = true, + spoiler: spoiler2 = true, + codeBlockContent = true, + inlineCodeContent = true, + escape = true, + heading = false, + bulletedList = false, + numberedList = false, + maskedLink = false + } = options; + if (!codeBlockContent) { + return text.split("```").map((subString, index, array) => { + if (index % 2 && index !== array.length - 1) + return subString; + return escapeMarkdown(subString, { + inlineCode: inlineCode2, + bold: bold2, + italic: italic2, + underline, + strikethrough: strikethrough2, + spoiler: spoiler2, + inlineCodeContent, + escape, + heading, + bulletedList, + numberedList, + maskedLink + }); + }).join(codeBlock2 ? "\\`\\`\\`" : "```"); + } + if (!inlineCodeContent) { + return text.split(/(?<=^|[^`])`(?=[^`]|$)/g).map((subString, index, array) => { + if (index % 2 && index !== array.length - 1) + return subString; + return escapeMarkdown(subString, { + codeBlock: codeBlock2, + bold: bold2, + italic: italic2, + underline, + strikethrough: strikethrough2, + spoiler: spoiler2, + escape, + heading, + bulletedList, + numberedList, + maskedLink + }); + }).join(inlineCode2 ? "\\`" : "`"); + } + let res = text; + if (escape) + res = escapeEscape(res); + if (inlineCode2) + res = escapeInlineCode(res); + if (codeBlock2) + res = escapeCodeBlock(res); + if (italic2) + res = escapeItalic(res); + if (bold2) + res = escapeBold(res); + if (underline) + res = escapeUnderline(res); + if (strikethrough2) + res = escapeStrikethrough(res); + if (spoiler2) + 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; +} +__name(escapeMarkdown, "escapeMarkdown"); +function escapeCodeBlock(text) { + return text.replaceAll("```", "\\`\\`\\`"); +} +__name(escapeCodeBlock, "escapeCodeBlock"); +function escapeInlineCode(text) { + return text.replaceAll(/(?<=^|[^`])``?(?=[^`]|$)/g, (match) => match.length === 2 ? "\\`\\`" : "\\`"); +} +__name(escapeInlineCode, "escapeInlineCode"); +function escapeItalic(text) { + let idx = 0; + const newText = text.replaceAll(/(?<=^|[^*])\*([^*]|\*\*|$)/g, (_, match) => { + if (match === "**") + return ++idx % 2 ? `\\*${match}` : `${match}\\*`; + return `\\*${match}`; + }); + idx = 0; + return newText.replaceAll(/(?<=^|[^_])(?)([^_]|__|$)/g, (_, match) => { + if (match === "__") + return ++idx % 2 ? `\\_${match}` : `${match}\\_`; + return `\\_${match}`; + }); +} +__name(escapeItalic, "escapeItalic"); +function escapeBold(text) { + let idx = 0; + return text.replaceAll(/\*\*(\*)?/g, (_, match) => { + if (match) + return ++idx % 2 ? `${match}\\*\\*` : `\\*\\*${match}`; + return "\\*\\*"; + }); +} +__name(escapeBold, "escapeBold"); +function escapeUnderline(text) { + let idx = 0; + return text.replaceAll(/(?)/g, (_, match) => { + if (match) + return ++idx % 2 ? `${match}\\_\\_` : `\\_\\_${match}`; + return "\\_\\_"; + }); +} +__name(escapeUnderline, "escapeUnderline"); +function escapeStrikethrough(text) { + return text.replaceAll("~~", "\\~\\~"); +} +__name(escapeStrikethrough, "escapeStrikethrough"); +function escapeSpoiler(text) { + return text.replaceAll("||", "\\|\\|"); +} +__name(escapeSpoiler, "escapeSpoiler"); +function escapeEscape(text) { + return text.replaceAll("\\", "\\\\"); +} +__name(escapeEscape, "escapeEscape"); +function escapeHeading(text) { + return text.replaceAll(/^( {0,2})([*-] )?( *)(#{1,3} )/gm, "$1$2$3\\$4"); +} +__name(escapeHeading, "escapeHeading"); +function escapeBulletedList(text) { + return text.replaceAll(/^( *)([*-])( +)/gm, "$1\\$2$3"); +} +__name(escapeBulletedList, "escapeBulletedList"); +function escapeNumberedList(text) { + return text.replaceAll(/^( *\d+)\./gm, "$1\\."); +} +__name(escapeNumberedList, "escapeNumberedList"); +function escapeMaskedLink(text) { + return text.replaceAll(/\[.+]\(.+\)/gm, "\\$&"); +} +__name(escapeMaskedLink, "escapeMaskedLink"); + +// src/formatters.ts +function codeBlock(language, content) { + return content === void 0 ? `\`\`\` +${language} +\`\`\`` : `\`\`\`${language} +${content} +\`\`\``; +} +__name(codeBlock, "codeBlock"); +function inlineCode(content) { + return `\`${content}\``; +} +__name(inlineCode, "inlineCode"); +function italic(content) { + return `_${content}_`; +} +__name(italic, "italic"); +function bold(content) { + return `**${content}**`; +} +__name(bold, "bold"); +function underscore(content) { + return `__${content}__`; +} +__name(underscore, "underscore"); +function strikethrough(content) { + return `~~${content}~~`; +} +__name(strikethrough, "strikethrough"); +function quote(content) { + return `> ${content}`; +} +__name(quote, "quote"); +function blockQuote(content) { + return `>>> ${content}`; +} +__name(blockQuote, "blockQuote"); +function hideLinkEmbed(url) { + return `<${url}>`; +} +__name(hideLinkEmbed, "hideLinkEmbed"); +function hyperlink(content, url, title) { + return title ? `[${content}](${url} "${title}")` : `[${content}](${url})`; +} +__name(hyperlink, "hyperlink"); +function spoiler(content) { + return `||${content}||`; +} +__name(spoiler, "spoiler"); +function userMention(userId) { + return `<@${userId}>`; +} +__name(userMention, "userMention"); +function channelMention(channelId) { + return `<#${channelId}>`; +} +__name(channelMention, "channelMention"); +function roleMention(roleId) { + return `<@&${roleId}>`; +} +__name(roleMention, "roleMention"); +function chatInputApplicationCommandMention(commandName, subcommandGroupName, subcommandName, commandId) { + if (commandId !== void 0) { + return ``; + } + if (subcommandName !== void 0) { + return ``; + } + return ``; +} +__name(chatInputApplicationCommandMention, "chatInputApplicationCommandMention"); +function formatEmoji(emojiId, animated = false) { + return `<${animated ? "a" : ""}:_:${emojiId}>`; +} +__name(formatEmoji, "formatEmoji"); +function channelLink(channelId, guildId) { + return `https://discord.com/channels/${guildId ?? "@me"}/${channelId}`; +} +__name(channelLink, "channelLink"); +function messageLink(channelId, messageId, guildId) { + return `${guildId === void 0 ? channelLink(channelId) : channelLink(channelId, guildId)}/${messageId}`; +} +__name(messageLink, "messageLink"); +function time(timeOrSeconds, style) { + if (typeof timeOrSeconds !== "number") { + timeOrSeconds = Math.floor((timeOrSeconds?.getTime() ?? Date.now()) / 1e3); + } + return typeof style === "string" ? `` : ``; +} +__name(time, "time"); +var TimestampStyles = { + /** + * Short time format, consisting of hours and minutes. + * + * @example `16:20` + */ + ShortTime: "t", + /** + * Long time format, consisting of hours, minutes, and seconds. + * + * @example `16:20:30` + */ + LongTime: "T", + /** + * Short date format, consisting of day, month, and year. + * + * @example `20/04/2021` + */ + ShortDate: "d", + /** + * Long date format, consisting of day, month, and year. + * + * @example `20 April 2021` + */ + LongDate: "D", + /** + * Short date-time format, consisting of short date and short time formats. + * + * @example `20 April 2021 16:20` + */ + ShortDateTime: "f", + /** + * Long date-time format, consisting of long date and short time formats. + * + * @example `Tuesday, 20 April 2021 16:20` + */ + LongDateTime: "F", + /** + * Relative time format, consisting of a relative duration format. + * + * @example `2 months ago` + */ + RelativeTime: "R" +}; +var Faces = /* @__PURE__ */ ((Faces2) => { + Faces2["Shrug"] = "\xAF_(\u30C4)_/\xAF"; + Faces2["Tableflip"] = "(\u256F\xB0\u25A1\xB0)\u256F\uFE35 \u253B\u2501\u253B"; + Faces2["Unflip"] = "\u252C\u2500\u252C\u30CE( \xBA _ \xBA\u30CE)"; + return Faces2; +})(Faces || {}); +export { + Faces, + TimestampStyles, + blockQuote, + bold, + channelLink, + channelMention, + chatInputApplicationCommandMention, + codeBlock, + escapeBold, + escapeBulletedList, + escapeCodeBlock, + escapeEscape, + escapeHeading, + escapeInlineCode, + escapeItalic, + escapeMarkdown, + escapeMaskedLink, + escapeNumberedList, + escapeSpoiler, + escapeStrikethrough, + escapeUnderline, + formatEmoji, + hideLinkEmbed, + hyperlink, + inlineCode, + italic, + messageLink, + quote, + roleMention, + spoiler, + strikethrough, + time, + underscore, + userMention +}; +//# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@discordjs/formatters/dist/index.mjs.map b/node_modules/@discordjs/formatters/dist/index.mjs.map new file mode 100644 index 0000000..ed19934 --- /dev/null +++ b/node_modules/@discordjs/formatters/dist/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"sources":["../src/escapers.ts","../src/formatters.ts"],"sourcesContent":["/* eslint-disable prefer-named-capture-group */\n\n/**\n * The options that affect what will be escaped.\n */\nexport interface EscapeMarkdownOptions {\n\t/**\n\t * Whether to escape bold text.\n\t *\n\t * @defaultValue `true`\n\t */\n\tbold?: boolean;\n\n\t/**\n\t * Whether to escape bulleted lists.\n\t *\n\t * @defaultValue `false`\n\t */\n\tbulletedList?: boolean;\n\n\t/**\n\t * Whether to escape code blocks.\n\t *\n\t * @defaultValue `true`\n\t */\n\tcodeBlock?: boolean;\n\n\t/**\n\t * Whether to escape text inside code blocks.\n\t *\n\t * @defaultValue `true`\n\t */\n\tcodeBlockContent?: boolean;\n\n\t/**\n\t * Whether to escape `\\`.\n\t *\n\t * @defaultValue `true`\n\t */\n\tescape?: boolean;\n\n\t/**\n\t * Whether to escape headings.\n\t *\n\t * @defaultValue `false`\n\t */\n\theading?: boolean;\n\n\t/**\n\t * Whether to escape inline code.\n\t *\n\t * @defaultValue `true`\n\t */\n\tinlineCode?: boolean;\n\n\t/**\n\t * Whether to escape text inside inline code.\n\t *\n\t * @defaultValue `true`\n\t */\n\tinlineCodeContent?: boolean;\n\t/**\n\t * Whether to escape italics.\n\t *\n\t * @defaultValue `true`\n\t */\n\titalic?: boolean;\n\n\t/**\n\t * Whether to escape masked links.\n\t *\n\t * @defaultValue `false`\n\t */\n\tmaskedLink?: boolean;\n\n\t/**\n\t * Whether to escape numbered lists.\n\t *\n\t * @defaultValue `false`\n\t */\n\tnumberedList?: boolean;\n\n\t/**\n\t * Whether to escape spoilers.\n\t *\n\t * @defaultValue `true`\n\t */\n\tspoiler?: boolean;\n\n\t/**\n\t * Whether to escape strikethroughs.\n\t *\n\t * @defaultValue `true`\n\t */\n\tstrikethrough?: boolean;\n\n\t/**\n\t * Whether to escape underlines.\n\t *\n\t * @defaultValue `true`\n\t */\n\tunderline?: boolean;\n}\n\n/**\n * Escapes any Discord-flavored markdown in a string.\n *\n * @param text - Content to escape\n * @param options - Options for escaping the markdown\n */\nexport function escapeMarkdown(text: string, options: EscapeMarkdownOptions = {}): string {\n\tconst {\n\t\tcodeBlock = true,\n\t\tinlineCode = true,\n\t\tbold = true,\n\t\titalic = true,\n\t\tunderline = true,\n\t\tstrikethrough = true,\n\t\tspoiler = true,\n\t\tcodeBlockContent = true,\n\t\tinlineCodeContent = true,\n\t\tescape = true,\n\t\theading = false,\n\t\tbulletedList = false,\n\t\tnumberedList = false,\n\t\tmaskedLink = false,\n\t} = options;\n\n\tif (!codeBlockContent) {\n\t\treturn text\n\t\t\t.split('```')\n\t\t\t.map((subString, index, array) => {\n\t\t\t\tif (index % 2 && index !== array.length - 1) return subString;\n\t\t\t\treturn escapeMarkdown(subString, {\n\t\t\t\t\tinlineCode,\n\t\t\t\t\tbold,\n\t\t\t\t\titalic,\n\t\t\t\t\tunderline,\n\t\t\t\t\tstrikethrough,\n\t\t\t\t\tspoiler,\n\t\t\t\t\tinlineCodeContent,\n\t\t\t\t\tescape,\n\t\t\t\t\theading,\n\t\t\t\t\tbulletedList,\n\t\t\t\t\tnumberedList,\n\t\t\t\t\tmaskedLink,\n\t\t\t\t});\n\t\t\t})\n\t\t\t.join(codeBlock ? '\\\\`\\\\`\\\\`' : '```');\n\t}\n\n\tif (!inlineCodeContent) {\n\t\treturn text\n\t\t\t.split(/(?<=^|[^`])`(?=[^`]|$)/g)\n\t\t\t.map((subString, index, array) => {\n\t\t\t\tif (index % 2 && index !== array.length - 1) return subString;\n\t\t\t\treturn escapeMarkdown(subString, {\n\t\t\t\t\tcodeBlock,\n\t\t\t\t\tbold,\n\t\t\t\t\titalic,\n\t\t\t\t\tunderline,\n\t\t\t\t\tstrikethrough,\n\t\t\t\t\tspoiler,\n\t\t\t\t\tescape,\n\t\t\t\t\theading,\n\t\t\t\t\tbulletedList,\n\t\t\t\t\tnumberedList,\n\t\t\t\t\tmaskedLink,\n\t\t\t\t});\n\t\t\t})\n\t\t\t.join(inlineCode ? '\\\\`' : '`');\n\t}\n\n\tlet res = text;\n\tif (escape) res = escapeEscape(res);\n\tif (inlineCode) res = escapeInlineCode(res);\n\tif (codeBlock) res = escapeCodeBlock(res);\n\tif (italic) res = escapeItalic(res);\n\tif (bold) res = escapeBold(res);\n\tif (underline) res = escapeUnderline(res);\n\tif (strikethrough) res = escapeStrikethrough(res);\n\tif (spoiler) res = escapeSpoiler(res);\n\tif (heading) res = escapeHeading(res);\n\tif (bulletedList) res = escapeBulletedList(res);\n\tif (numberedList) res = escapeNumberedList(res);\n\tif (maskedLink) res = escapeMaskedLink(res);\n\treturn res;\n}\n\n/**\n * Escapes code block markdown in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeCodeBlock(text: string): string {\n\treturn text.replaceAll('```', '\\\\`\\\\`\\\\`');\n}\n\n/**\n * Escapes inline code markdown in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeInlineCode(text: string): string {\n\treturn text.replaceAll(/(?<=^|[^`])``?(?=[^`]|$)/g, (match) => (match.length === 2 ? '\\\\`\\\\`' : '\\\\`'));\n}\n\n/**\n * Escapes italic markdown in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeItalic(text: string): string {\n\tlet idx = 0;\n\tconst newText = text.replaceAll(/(?<=^|[^*])\\*([^*]|\\*\\*|$)/g, (_, match) => {\n\t\tif (match === '**') return ++idx % 2 ? `\\\\*${match}` : `${match}\\\\*`;\n\t\treturn `\\\\*${match}`;\n\t});\n\tidx = 0;\n\treturn newText.replaceAll(/(?<=^|[^_])(?)([^_]|__|$)/g, (_, match) => {\n\t\tif (match === '__') return ++idx % 2 ? `\\\\_${match}` : `${match}\\\\_`;\n\t\treturn `\\\\_${match}`;\n\t});\n}\n\n/**\n * Escapes bold markdown in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeBold(text: string): string {\n\tlet idx = 0;\n\treturn text.replaceAll(/\\*\\*(\\*)?/g, (_, match) => {\n\t\tif (match) return ++idx % 2 ? `${match}\\\\*\\\\*` : `\\\\*\\\\*${match}`;\n\t\treturn '\\\\*\\\\*';\n\t});\n}\n\n/**\n * Escapes underline markdown in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeUnderline(text: string): string {\n\tlet idx = 0;\n\treturn text.replaceAll(/(?)/g, (_, match) => {\n\t\tif (match) return ++idx % 2 ? `${match}\\\\_\\\\_` : `\\\\_\\\\_${match}`;\n\t\treturn '\\\\_\\\\_';\n\t});\n}\n\n/**\n * Escapes strikethrough markdown in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeStrikethrough(text: string): string {\n\treturn text.replaceAll('~~', '\\\\~\\\\~');\n}\n\n/**\n * Escapes spoiler markdown in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeSpoiler(text: string): string {\n\treturn text.replaceAll('||', '\\\\|\\\\|');\n}\n\n/**\n * Escapes escape characters in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeEscape(text: string): string {\n\treturn text.replaceAll('\\\\', '\\\\\\\\');\n}\n\n/**\n * Escapes heading characters in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeHeading(text: string): string {\n\treturn text.replaceAll(/^( {0,2})([*-] )?( *)(#{1,3} )/gm, '$1$2$3\\\\$4');\n}\n\n/**\n * Escapes bulleted list characters in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeBulletedList(text: string): string {\n\treturn text.replaceAll(/^( *)([*-])( +)/gm, '$1\\\\$2$3');\n}\n\n/**\n * Escapes numbered list characters in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeNumberedList(text: string): string {\n\treturn text.replaceAll(/^( *\\d+)\\./gm, '$1\\\\.');\n}\n\n/**\n * Escapes masked link characters in a string.\n *\n * @param text - Content to escape\n */\nexport function escapeMaskedLink(text: string): string {\n\treturn text.replaceAll(/\\[.+]\\(.+\\)/gm, '\\\\$&');\n}\n","import type { URL } from 'node:url';\nimport type { Snowflake } from 'discord-api-types/globals';\n\n/**\n * Wraps the content inside a code block with no language.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function codeBlock(content: C): `\\`\\`\\`\\n${C}\\n\\`\\`\\``;\n\n/**\n * Wraps the content inside a code block with the specified language.\n *\n * @typeParam L - This is inferred by the supplied language\n * @typeParam C - This is inferred by the supplied content\n * @param language - The language for the code block\n * @param content - The content to wrap\n */\nexport function codeBlock(language: L, content: C): `\\`\\`\\`${L}\\n${C}\\n\\`\\`\\``;\n\nexport function codeBlock(language: string, content?: string): string {\n\treturn content === undefined ? `\\`\\`\\`\\n${language}\\n\\`\\`\\`` : `\\`\\`\\`${language}\\n${content}\\n\\`\\`\\``;\n}\n\n/**\n * Wraps the content inside \\`backticks\\` which formats it as inline code.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function inlineCode(content: C): `\\`${C}\\`` {\n\treturn `\\`${content}\\``;\n}\n\n/**\n * Formats the content into italic text.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function italic(content: C): `_${C}_` {\n\treturn `_${content}_`;\n}\n\n/**\n * Formats the content into bold text.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function bold(content: C): `**${C}**` {\n\treturn `**${content}**`;\n}\n\n/**\n * Formats the content into underscored text.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function underscore(content: C): `__${C}__` {\n\treturn `__${content}__`;\n}\n\n/**\n * Formats the content into strike-through text.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function strikethrough(content: C): `~~${C}~~` {\n\treturn `~~${content}~~`;\n}\n\n/**\n * Formats the content into a quote.\n *\n * @remarks This needs to be at the start of the line for Discord to format it.\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function quote(content: C): `> ${C}` {\n\treturn `> ${content}`;\n}\n\n/**\n * Formats the content into a block quote.\n *\n * @remarks This needs to be at the start of the line for Discord to format it.\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function blockQuote(content: C): `>>> ${C}` {\n\treturn `>>> ${content}`;\n}\n\n/**\n * Wraps the URL into `<>` which stops it from embedding.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param url - The URL to wrap\n */\nexport function hideLinkEmbed(url: C): `<${C}>`;\n\n/**\n * Wraps the URL into `<>` which stops it from embedding.\n *\n * @param url - The URL to wrap\n */\nexport function hideLinkEmbed(url: URL): `<${string}>`;\n\nexport function hideLinkEmbed(url: URL | string) {\n\treturn `<${url}>`;\n}\n\n/**\n * Formats the content and the URL into a masked URL.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to display\n * @param url - The URL the content links to\n */\nexport function hyperlink(content: C, url: URL): `[${C}](${string})`;\n\n/**\n * Formats the content and the URL into a masked URL.\n *\n * @typeParam C - This is inferred by the supplied content\n * @typeParam U - This is inferred by the supplied URL\n * @param content - The content to display\n * @param url - The URL the content links to\n */\nexport function hyperlink(content: C, url: U): `[${C}](${U})`;\n\n/**\n * Formats the content and the URL into a masked URL with a custom tooltip.\n *\n * @typeParam C - This is inferred by the supplied content\n * @typeParam T - This is inferred by the supplied title\n * @param content - The content to display\n * @param url - The URL the content links to\n * @param title - The title shown when hovering on the masked link\n */\nexport function hyperlink(\n\tcontent: C,\n\turl: URL,\n\ttitle: T,\n): `[${C}](${string} \"${T}\")`;\n\n/**\n * Formats the content and the URL into a masked URL with a custom tooltip.\n *\n * @typeParam C - This is inferred by the supplied content\n * @typeParam U - This is inferred by the supplied URL\n * @typeParam T - This is inferred by the supplied title\n * @param content - The content to display\n * @param url - The URL the content links to\n * @param title - The title shown when hovering on the masked link\n */\nexport function hyperlink(\n\tcontent: C,\n\turl: U,\n\ttitle: T,\n): `[${C}](${U} \"${T}\")`;\n\nexport function hyperlink(content: string, url: URL | string, title?: string) {\n\treturn title ? `[${content}](${url} \"${title}\")` : `[${content}](${url})`;\n}\n\n/**\n * Formats the content into a spoiler.\n *\n * @typeParam C - This is inferred by the supplied content\n * @param content - The content to wrap\n */\nexport function spoiler(content: C): `||${C}||` {\n\treturn `||${content}||`;\n}\n\n/**\n * Formats a user id into a user mention.\n *\n * @typeParam C - This is inferred by the supplied user id\n * @param userId - The user id to format\n */\nexport function userMention(userId: C): `<@${C}>` {\n\treturn `<@${userId}>`;\n}\n\n/**\n * Formats a channel id into a channel mention.\n *\n * @typeParam C - This is inferred by the supplied channel id\n * @param channelId - The channel id to format\n */\nexport function channelMention(channelId: C): `<#${C}>` {\n\treturn `<#${channelId}>`;\n}\n\n/**\n * Formats a role id into a role mention.\n *\n * @typeParam C - This is inferred by the supplied role id\n * @param roleId - The role id to format\n */\nexport function roleMention(roleId: C): `<@&${C}>` {\n\treturn `<@&${roleId}>`;\n}\n\n/**\n * Formats an application command name, subcommand group name, subcommand name, and id into an application command mention.\n *\n * @typeParam N - This is inferred by the supplied command name\n * @typeParam G - This is inferred by the supplied subcommand group name\n * @typeParam S - This is inferred by the supplied subcommand name\n * @typeParam I - This is inferred by the supplied command id\n * @param commandName - The application command name to format\n * @param subcommandGroupName - The subcommand group name to format\n * @param subcommandName - The subcommand name to format\n * @param commandId - The application command id to format\n */\nexport function chatInputApplicationCommandMention<\n\tN extends string,\n\tG extends string,\n\tS extends string,\n\tI extends Snowflake,\n>(commandName: N, subcommandGroupName: G, subcommandName: S, commandId: I): ``;\n\n/**\n * Formats an application command name, subcommand name, and id into an application command mention.\n *\n * @typeParam N - This is inferred by the supplied command name\n * @typeParam S - This is inferred by the supplied subcommand name\n * @typeParam I - This is inferred by the supplied command id\n * @param commandName - The application command name to format\n * @param subcommandName - The subcommand name to format\n * @param commandId - The application command id to format\n */\nexport function chatInputApplicationCommandMention(\n\tcommandName: N,\n\tsubcommandName: S,\n\tcommandId: I,\n): ``;\n\n/**\n * Formats an application command name and id into an application command mention.\n *\n * @typeParam N - This is inferred by the supplied command name\n * @typeParam I - This is inferred by the supplied command id\n * @param commandName - The application command name to format\n * @param commandId - The application command id to format\n */\nexport function chatInputApplicationCommandMention(\n\tcommandName: N,\n\tcommandId: I,\n): ``;\n\nexport function chatInputApplicationCommandMention<\n\tN extends string,\n\tG extends Snowflake | string,\n\tS extends Snowflake | string,\n\tI extends Snowflake,\n>(\n\tcommandName: N,\n\tsubcommandGroupName: G,\n\tsubcommandName?: S,\n\tcommandId?: I,\n): `` | `` | `` {\n\tif (commandId !== undefined) {\n\t\treturn ``;\n\t}\n\n\tif (subcommandName !== undefined) {\n\t\treturn ``;\n\t}\n\n\treturn ``;\n}\n\n/**\n * Formats a non-animated emoji id into a fully qualified emoji identifier.\n *\n * @typeParam C - This is inferred by the supplied emoji id\n * @param emojiId - The emoji id to format\n */\nexport function formatEmoji(emojiId: C, animated?: false): `<:_:${C}>`;\n\n/**\n * Formats an animated emoji id into a fully qualified emoji identifier.\n *\n * @typeParam C - This is inferred by the supplied emoji id\n * @param emojiId - The emoji id to format\n * @param animated - Whether the emoji is animated\n */\nexport function formatEmoji(emojiId: C, animated?: true): ``;\n\n/**\n * Formats an emoji id into a fully qualified emoji identifier.\n *\n * @typeParam C - This is inferred by the supplied emoji id\n * @param emojiId - The emoji id to format\n * @param animated - Whether the emoji is animated\n */\nexport function formatEmoji(emojiId: C, animated?: boolean): `<:_:${C}>` | ``;\n\nexport function formatEmoji(emojiId: C, animated = false): `<:_:${C}>` | `` {\n\treturn `<${animated ? 'a' : ''}:_:${emojiId}>`;\n}\n\n/**\n * Formats a channel link for a direct message channel.\n *\n * @typeParam C - This is inferred by the supplied channel id\n * @param channelId - The channel's id\n */\nexport function channelLink(channelId: C): `https://discord.com/channels/@me/${C}`;\n\n/**\n * Formats a channel link for a guild channel.\n *\n * @typeParam C - This is inferred by the supplied channel id\n * @typeParam G - This is inferred by the supplied guild id\n * @param channelId - The channel's id\n * @param guildId - The guild's id\n */\nexport function channelLink(\n\tchannelId: C,\n\tguildId: G,\n): `https://discord.com/channels/${G}/${C}`;\n\nexport function channelLink(\n\tchannelId: C,\n\tguildId?: G,\n): `https://discord.com/channels/@me/${C}` | `https://discord.com/channels/${G}/${C}` {\n\treturn `https://discord.com/channels/${guildId ?? '@me'}/${channelId}`;\n}\n\n/**\n * Formats a message link for a direct message channel.\n *\n * @typeParam C - This is inferred by the supplied channel id\n * @typeParam M - This is inferred by the supplied message id\n * @param channelId - The channel's id\n * @param messageId - The message's id\n */\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n): `https://discord.com/channels/@me/${C}/${M}`;\n\n/**\n * Formats a message link for a guild channel.\n *\n * @typeParam C - This is inferred by the supplied channel id\n * @typeParam M - This is inferred by the supplied message id\n * @typeParam G - This is inferred by the supplied guild id\n * @param channelId - The channel's id\n * @param messageId - The message's id\n * @param guildId - The guild's id\n */\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n\tguildId: G,\n): `https://discord.com/channels/${G}/${C}/${M}`;\n\nexport function messageLink(\n\tchannelId: C,\n\tmessageId: M,\n\tguildId?: G,\n): `https://discord.com/channels/@me/${C}/${M}` | `https://discord.com/channels/${G}/${C}/${M}` {\n\treturn `${guildId === undefined ? channelLink(channelId) : channelLink(channelId, guildId)}/${messageId}`;\n}\n\n/**\n * Formats a date into a short date-time string.\n *\n * @param date - The date to format. Defaults to the current time\n */\nexport function time(date?: Date): ``;\n\n/**\n * Formats a date given a format style.\n *\n * @typeParam S - This is inferred by the supplied {@link TimestampStylesString}\n * @param date - The date to format\n * @param style - The style to use\n */\nexport function time(date: Date, style: S): ``;\n\n/**\n * Formats the given timestamp into a short date-time string.\n *\n * @typeParam C - This is inferred by the supplied timestamp\n * @param seconds - A Unix timestamp in seconds\n */\nexport function time(seconds: C): ``;\n\n/**\n * Formats the given timestamp into a short date-time string.\n *\n * @typeParam C - This is inferred by the supplied timestamp\n * @typeParam S - This is inferred by the supplied {@link TimestampStylesString}\n * @param seconds - A Unix timestamp in seconds\n * @param style - The style to use\n */\nexport function time(seconds: C, style: S): ``;\n\nexport function time(timeOrSeconds?: Date | number, style?: TimestampStylesString): string {\n\tif (typeof timeOrSeconds !== 'number') {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\ttimeOrSeconds = Math.floor((timeOrSeconds?.getTime() ?? Date.now()) / 1_000);\n\t}\n\n\treturn typeof style === 'string' ? `` : ``;\n}\n\n/**\n * The {@link https://discord.com/developers/docs/reference#message-formatting-timestamp-styles | message formatting timestamp styles}\n * supported by Discord.\n */\nexport const TimestampStyles = {\n\t/**\n\t * Short time format, consisting of hours and minutes.\n\t *\n\t * @example `16:20`\n\t */\n\tShortTime: 't',\n\n\t/**\n\t * Long time format, consisting of hours, minutes, and seconds.\n\t *\n\t * @example `16:20:30`\n\t */\n\tLongTime: 'T',\n\n\t/**\n\t * Short date format, consisting of day, month, and year.\n\t *\n\t * @example `20/04/2021`\n\t */\n\tShortDate: 'd',\n\n\t/**\n\t * Long date format, consisting of day, month, and year.\n\t *\n\t * @example `20 April 2021`\n\t */\n\tLongDate: 'D',\n\n\t/**\n\t * Short date-time format, consisting of short date and short time formats.\n\t *\n\t * @example `20 April 2021 16:20`\n\t */\n\tShortDateTime: 'f',\n\n\t/**\n\t * Long date-time format, consisting of long date and short time formats.\n\t *\n\t * @example `Tuesday, 20 April 2021 16:20`\n\t */\n\tLongDateTime: 'F',\n\n\t/**\n\t * Relative time format, consisting of a relative duration format.\n\t *\n\t * @example `2 months ago`\n\t */\n\tRelativeTime: 'R',\n} as const satisfies Record;\n\n/**\n * The possible {@link TimestampStyles} values.\n */\nexport type TimestampStylesString = (typeof TimestampStyles)[keyof typeof TimestampStyles];\n\n// prettier-ignore\n/**\n * All the available faces from Discord's native slash commands.\n */\nexport enum Faces {\n\t/**\n\t * `Β―\\_(ツ)_/Β―`\n\t */\n\t// eslint-disable-next-line no-useless-escape\n\tShrug = 'Β―\\_(ツ)_/Β―',\n\n\t/**\n\t * `(β•―Β°β–‘Β°)β•―οΈ΅ ┻━┻`\n\t */\n\tTableflip = '(β•―Β°β–‘Β°)β•―οΈ΅ ┻━┻',\n\n\t/**\n\t * `β”¬β”€β”¬γƒŽ( ΒΊ _ ΒΊγƒŽ)`\n\t */\n\tUnflip = 'β”¬β”€β”¬γƒŽ( ΒΊ _ ΒΊγƒŽ)',\n}\n"],"mappings":";;;;AA8GO,SAAS,eAAe,MAAc,UAAiC,CAAC,GAAW;AACzF,QAAM;AAAA,IACL,WAAAA,aAAY;AAAA,IACZ,YAAAC,cAAa;AAAA,IACb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AAA;AAAA;AAAA,EAOX,UAAU;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOV,eAAe;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOf,cAAc;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOd,cAAc;AACf;AAWO,IAAK,QAAL,kBAAKC,WAAL;AAKN,EAAAA,OAAA,WAAQ;AAKR,EAAAA,OAAA,eAAY;AAKZ,EAAAA,OAAA,YAAS;AAfE,SAAAA;AAAA,GAAA;","names":["codeBlock","inlineCode","bold","italic","strikethrough","spoiler","Faces"]} \ No newline at end of file diff --git a/node_modules/@discordjs/formatters/package.json b/node_modules/@discordjs/formatters/package.json new file mode 100644 index 0000000..8eef008 --- /dev/null +++ b/node_modules/@discordjs/formatters/package.json @@ -0,0 +1,71 @@ +{ + "name": "@discordjs/formatters", + "version": "0.3.1", + "description": "A set of functions to format strings for Discord.", + "scripts": { + "test": "vitest run", + "build": "tsup", + "build:docs": "tsc -p tsconfig.docs.json", + "lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty", + "format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty", + "docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json", + "prepack": "yarn build && yarn lint", + "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/formatters/*'", + "release": "cliff-jumper" + }, + "main": "./dist/index.js", + "module": "./dist/index.mjs", + "typings": "./dist/index.d.ts", + "exports": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + }, + "directories": { + "lib": "src", + "test": "__tests__" + }, + "files": [ + "dist" + ], + "contributors": [ + "Crawl ", + "SpaceEEC ", + "Vlad Frangu ", + "Aura RomΓ‘n " + ], + "license": "Apache-2.0", + "keywords": [], + "repository": { + "type": "git", + "url": "https://github.com/discordjs/discord.js.git", + "directory": "packages/formatters" + }, + "bugs": { + "url": "https://github.com/discordjs/discord.js/issues" + }, + "homepage": "https://discord.js.org", + "dependencies": { + "discord-api-types": "^0.37.41" + }, + "devDependencies": { + "@favware/cliff-jumper": "^2.0.0", + "@microsoft/api-extractor": "^7.34.6", + "@types/node": "16.18.25", + "@vitest/coverage-c8": "^0.30.1", + "cross-env": "^7.0.3", + "eslint": "^8.39.0", + "eslint-config-neon": "^0.1.42", + "eslint-formatter-pretty": "^5.0.0", + "prettier": "^2.8.8", + "tsup": "^6.7.0", + "typescript": "^5.0.4", + "vitest": "^0.29.8" + }, + "engines": { + "node": ">=16.9.0" + }, + "publishConfig": { + "access": "public" + } +} \ No newline at end of file diff --git a/node_modules/@discordjs/rest/CHANGELOG.md b/node_modules/@discordjs/rest/CHANGELOG.md index 2a7f5c8..deabd9b 100644 --- a/node_modules/@discordjs/rest/CHANGELOG.md +++ b/node_modules/@discordjs/rest/CHANGELOG.md @@ -2,6 +2,50 @@ All notable changes to this project will be documented in this file. +# [@discordjs/rest@1.7.1](https://github.com/discordjs/discord.js/compare/@discordjs/rest@1.7.0...@discordjs/rest@1.7.1) - (2023-05-01) + +## Bug Fixes + +- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2)) + +## Documentation + +- Reference package names properly (#9426) ([d6bca9b](https://github.com/discordjs/discord.js/commit/d6bca9bb4d976dc069a5039250db7d5b3e9142ef)) +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) + +# [@discordjs/rest@1.7.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@1.6.0...@discordjs/rest@1.7.0) - (2023-04-01) + +## Bug Fixes + +- **handlers:** Create burst handler for interaction callbacks (#8996) ([db8df10](https://github.com/discordjs/discord.js/commit/db8df104c5e70a12f35b54e5f3f7c897068dde6f)) +- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b)) +- **rest:** Remove `const enum`s in favour of regular enums (#9243) ([229ad07](https://github.com/discordjs/discord.js/commit/229ad077ff52d8706d68ed4d31983619a32eba45)) + +## Features + +- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b)) + +# [@discordjs/rest@1.6.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@1.5.0...@discordjs/rest@1.6.0) - (2023-03-12) + +## Bug Fixes + +- **snowflake:** Snowflakes length (#9144) ([955e8fe](https://github.com/discordjs/discord.js/commit/955e8fe312c42ad4937cc1994d1d81e517c413c8)) +- **RequestManager:** Inference of image/apng (#9014) ([ecb4281](https://github.com/discordjs/discord.js/commit/ecb4281d1e2d9a0a427605f75352cbf74ffb2d7c)) + +## Documentation + +- Fix typos (#9127) ([1ba1f23](https://github.com/discordjs/discord.js/commit/1ba1f238f04221ec890fc921678909b5b7d92c26)) +- Fix version export (#9049) ([8b70f49](https://github.com/discordjs/discord.js/commit/8b70f497a1207e30edebdecd12b926c981c13d28)) + +## Features + +- **Sticker:** Add support for gif stickers (#9038) ([6a9875d](https://github.com/discordjs/discord.js/commit/6a9875da054a875a4711394547d47439bbe66fb6)) +- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38)) + +## Styling + +- Run prettier (#9041) ([2798ba1](https://github.com/discordjs/discord.js/commit/2798ba1eb3d734f0cf2eeccd2e16cfba6804873b)) + # [@discordjs/rest@1.5.0](https://github.com/discordjs/discord.js/compare/@discordjs/rest@1.4.0...@discordjs/rest@1.5.0) - (2022-12-16) ## Features diff --git a/node_modules/@discordjs/rest/README.md b/node_modules/@discordjs/rest/README.md index d36725a..b5fba00 100644 --- a/node_modules/@discordjs/rest/README.md +++ b/node_modules/@discordjs/rest/README.md @@ -16,11 +16,15 @@

+## About + +`@discordjs/rest` is a module that allows you to easily make REST requests to the Discord API. + ## Installation **Node.js 16.9.0 or newer is required.** -```sh-session +```sh npm install @discordjs/rest yarn add @discordjs/rest pnpm add @discordjs/rest @@ -30,7 +34,7 @@ pnpm add @discordjs/rest Install all required dependencies: -```sh-session +```sh npm install @discordjs/rest discord-api-types yarn add @discordjs/rest discord-api-types pnpm add @discordjs/rest discord-api-types @@ -80,7 +84,7 @@ try { - [Website][website] ([source][website-source]) - [Documentation][documentation] - [Guide][guide] ([source][guide-source]) - See also the [Update Guide][guide-update], including updated and removed items in the library. + Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library. - [discord.js Discord server][discord] - [Discord API Discord server][discord-api] - [GitHub][source] @@ -95,12 +99,11 @@ See [the contribution guide][contributing] if you'd like to submit a PR. ## Help -If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle -nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. +If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. -[website]: https://discord.js.org/ +[website]: https://discord.js.org [website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website -[documentation]: https://discord.js.org/#/docs/rest +[documentation]: https://discord.js.org/docs/packages/rest/stable [guide]: https://discordjs.guide/ [guide-source]: https://github.com/discordjs/guide [guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html diff --git a/node_modules/@discordjs/rest/dist/index.d.ts b/node_modules/@discordjs/rest/dist/index.d.ts index 3536eda..5077622 100644 --- a/node_modules/@discordjs/rest/dist/index.d.ts +++ b/node_modules/@discordjs/rest/dist/index.d.ts @@ -4,7 +4,11 @@ import { EventEmitter } from 'node:events'; import { URLSearchParams } from 'node:url'; import { Collection } from '@discordjs/collection'; -declare const DefaultUserAgent = "DiscordBot (https://discord.js.org, [VI]{{inject}}[/VI])"; +declare const DefaultUserAgent: `DiscordBot (https://discord.js.org, ${string})`; +/** + * The default string to append onto the user agent. + */ +declare const DefaultUserAgentAppendix: string; declare const DefaultRestOptions: { readonly agent: Agent; readonly api: "https://discord.com/api"; @@ -17,7 +21,7 @@ declare const DefaultRestOptions: { readonly rejectOnRateLimit: null; readonly retries: 3; readonly timeout: 15000; - readonly userAgentAppendix: `Node.js ${string}`; + readonly userAgentAppendix: string; readonly version: "10"; readonly hashSweepInterval: 14400000; readonly hashLifetime: 86400000; @@ -26,7 +30,7 @@ declare const DefaultRestOptions: { /** * The events that the REST manager emits */ -declare const enum RESTEvents { +declare enum RESTEvents { Debug = "restDebug", HandlerSweep = "handlerSweep", HashSweep = "hashSweep", @@ -35,11 +39,15 @@ declare const enum RESTEvents { Response = "response" } declare const ALLOWED_EXTENSIONS: readonly ["webp", "png", "jpg", "jpeg", "gif"]; -declare const ALLOWED_STICKER_EXTENSIONS: readonly ["png", "json"]; +declare const ALLOWED_STICKER_EXTENSIONS: readonly ["png", "json", "gif"]; declare const ALLOWED_SIZES: readonly [16, 32, 64, 128, 256, 512, 1024, 2048, 4096]; -type ImageExtension = typeof ALLOWED_EXTENSIONS[number]; -type StickerExtension = typeof ALLOWED_STICKER_EXTENSIONS[number]; -type ImageSize = typeof ALLOWED_SIZES[number]; +type ImageExtension = (typeof ALLOWED_EXTENSIONS)[number]; +type StickerExtension = (typeof ALLOWED_STICKER_EXTENSIONS)[number]; +type ImageSize = (typeof ALLOWED_SIZES)[number]; +declare const OverwrittenMimeTypes: { + readonly 'image/apng': "image/png"; +}; +declare const BurstHandlerMajorIdKey = "burst"; /** * The options used for image URLs @@ -198,6 +206,8 @@ declare class CDN { * * @param stickerId - The sticker id * @param extension - The extension of the sticker + * @privateRemarks + * Stickers cannot have a `.webp` extension, so we default to a `.png` */ sticker(stickerId: string, extension?: StickerExtension): string; /** @@ -355,7 +365,7 @@ interface RESTOptions { /** * Extra information to add to the user agent * - * @defaultValue `Node.js ${process.version}` + * @defaultValue DefaultUserAgentAppendix */ userAgentAppendix: string; /** @@ -627,7 +637,7 @@ interface RequestHeaders { /** * Possible API methods to be used when doing requests */ -declare const enum RequestMethod { +declare enum RequestMethod { Delete = "DELETE", Get = "GET", Patch = "PATCH", @@ -862,4 +872,4 @@ declare function parseResponse(res: Dispatcher.ResponseData): Promise; */ declare const version: string; -export { ALLOWED_EXTENSIONS, ALLOWED_SIZES, ALLOWED_STICKER_EXTENSIONS, APIRequest, BaseImageURLOptions, CDN, DefaultRestOptions, DefaultUserAgent, DiscordAPIError, DiscordErrorData, HTTPError, HandlerRequestData, HashData, ImageExtension, ImageSize, ImageURLOptions, InternalRequest, InvalidRequestWarningData, MakeURLOptions, OAuthErrorData, REST, RESTEvents, RESTOptions, RateLimitData, RateLimitError, RateLimitQueueFilter, RawFile, RequestBody, RequestData, RequestHeaders, RequestManager, RequestMethod, RequestOptions, RestEvents, RouteData, RouteLike, StickerExtension, makeURLSearchParams, parseResponse, version }; +export { ALLOWED_EXTENSIONS, ALLOWED_SIZES, ALLOWED_STICKER_EXTENSIONS, APIRequest, BaseImageURLOptions, BurstHandlerMajorIdKey, CDN, DefaultRestOptions, DefaultUserAgent, DefaultUserAgentAppendix, DiscordAPIError, DiscordErrorData, HTTPError, HandlerRequestData, HashData, ImageExtension, ImageSize, ImageURLOptions, InternalRequest, InvalidRequestWarningData, MakeURLOptions, OAuthErrorData, OverwrittenMimeTypes, REST, RESTEvents, RESTOptions, RateLimitData, RateLimitError, RateLimitQueueFilter, RawFile, RequestBody, RequestData, RequestHeaders, RequestManager, RequestMethod, RequestOptions, RestEvents, RouteData, RouteLike, StickerExtension, makeURLSearchParams, parseResponse, version }; diff --git a/node_modules/@discordjs/rest/dist/index.js b/node_modules/@discordjs/rest/dist/index.js index 513e9dc..f4e24b2 100644 --- a/node_modules/@discordjs/rest/dist/index.js +++ b/node_modules/@discordjs/rest/dist/index.js @@ -19,6 +19,10 @@ var __copyProps = (to, from, except, desc) => { return to; }; var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod )); @@ -30,11 +34,14 @@ __export(src_exports, { ALLOWED_EXTENSIONS: () => ALLOWED_EXTENSIONS, ALLOWED_SIZES: () => ALLOWED_SIZES, ALLOWED_STICKER_EXTENSIONS: () => ALLOWED_STICKER_EXTENSIONS, + BurstHandlerMajorIdKey: () => BurstHandlerMajorIdKey, CDN: () => CDN, DefaultRestOptions: () => DefaultRestOptions, DefaultUserAgent: () => DefaultUserAgent, + DefaultUserAgentAppendix: () => DefaultUserAgentAppendix, DiscordAPIError: () => DiscordAPIError, HTTPError: () => HTTPError, + OverwrittenMimeTypes: () => OverwrittenMimeTypes, REST: () => REST, RESTEvents: () => RESTEvents, RateLimitError: () => RateLimitError, @@ -53,7 +60,8 @@ var import_node_url = require("url"); var import_node_process = __toESM(require("process")); var import_v10 = require("discord-api-types/v10"); var import_undici = require("undici"); -var DefaultUserAgent = `DiscordBot (https://discord.js.org, 1.5.0)`; +var DefaultUserAgent = `DiscordBot (https://discord.js.org, 1.7.1)`; +var DefaultUserAgentAppendix = import_node_process.default.release?.name === "node" ? `Node.js/${import_node_process.default.version}` : ""; var DefaultRestOptions = { get agent() { return new import_undici.Agent({ @@ -72,11 +80,14 @@ var DefaultRestOptions = { rejectOnRateLimit: null, retries: 3, timeout: 15e3, - userAgentAppendix: `Node.js ${import_node_process.default.version}`, + userAgentAppendix: DefaultUserAgentAppendix, version: import_v10.APIVersion, hashSweepInterval: 144e5, + // 4 Hours hashLifetime: 864e5, + // 24 Hours handlerSweepInterval: 36e5 + // 1 Hour }; var RESTEvents = /* @__PURE__ */ ((RESTEvents2) => { RESTEvents2["Debug"] = "restDebug"; @@ -88,71 +99,204 @@ var RESTEvents = /* @__PURE__ */ ((RESTEvents2) => { return RESTEvents2; })(RESTEvents || {}); var ALLOWED_EXTENSIONS = ["webp", "png", "jpg", "jpeg", "gif"]; -var ALLOWED_STICKER_EXTENSIONS = ["png", "json"]; +var ALLOWED_STICKER_EXTENSIONS = ["png", "json", "gif"]; var ALLOWED_SIZES = [16, 32, 64, 128, 256, 512, 1024, 2048, 4096]; +var OverwrittenMimeTypes = { + // https://github.com/discordjs/discord.js/issues/8557 + "image/apng": "image/png" +}; +var BurstHandlerMajorIdKey = "burst"; // src/lib/CDN.ts var CDN = class { constructor(base = DefaultRestOptions.cdn) { this.base = base; } + /** + * Generates an app asset URL for a client's asset. + * + * @param clientId - The client id that has the asset + * @param assetHash - The hash provided by Discord for this asset + * @param options - Optional options for the asset + */ appAsset(clientId, assetHash, options) { return this.makeURL(`/app-assets/${clientId}/${assetHash}`, options); } + /** + * Generates an app icon URL for a client's icon. + * + * @param clientId - The client id that has the icon + * @param iconHash - The hash provided by Discord for this icon + * @param options - Optional options for the icon + */ appIcon(clientId, iconHash, options) { return this.makeURL(`/app-icons/${clientId}/${iconHash}`, options); } + /** + * Generates an avatar URL, e.g. for a user or a webhook. + * + * @param id - The id that has the icon + * @param avatarHash - The hash provided by Discord for this avatar + * @param options - Optional options for the avatar + */ avatar(id, avatarHash, options) { return this.dynamicMakeURL(`/avatars/${id}/${avatarHash}`, avatarHash, options); } + /** + * Generates a banner URL, e.g. for a user or a guild. + * + * @param id - The id that has the banner splash + * @param bannerHash - The hash provided by Discord for this banner + * @param options - Optional options for the banner + */ banner(id, bannerHash, options) { return this.dynamicMakeURL(`/banners/${id}/${bannerHash}`, bannerHash, options); } + /** + * Generates an icon URL for a channel, e.g. a group DM. + * + * @param channelId - The channel id that has the icon + * @param iconHash - The hash provided by Discord for this channel + * @param options - Optional options for the icon + */ channelIcon(channelId, iconHash, options) { return this.makeURL(`/channel-icons/${channelId}/${iconHash}`, options); } + /** + * Generates the default avatar URL for a discriminator. + * + * @param discriminator - The discriminator modulo 5 + */ defaultAvatar(discriminator) { return this.makeURL(`/embed/avatars/${discriminator}`, { extension: "png" }); } + /** + * Generates a discovery splash URL for a guild's discovery splash. + * + * @param guildId - The guild id that has the discovery splash + * @param splashHash - The hash provided by Discord for this splash + * @param options - Optional options for the splash + */ discoverySplash(guildId, splashHash, options) { return this.makeURL(`/discovery-splashes/${guildId}/${splashHash}`, options); } + /** + * Generates an emoji's URL for an emoji. + * + * @param emojiId - The emoji id + * @param extension - The extension of the emoji + */ emoji(emojiId, extension) { return this.makeURL(`/emojis/${emojiId}`, { extension }); } + /** + * Generates a guild member avatar URL. + * + * @param guildId - The id of the guild + * @param userId - The id of the user + * @param avatarHash - The hash provided by Discord for this avatar + * @param options - Optional options for the avatar + */ guildMemberAvatar(guildId, userId, avatarHash, options) { return this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/avatars/${avatarHash}`, avatarHash, options); } + /** + * Generates a guild member banner URL. + * + * @param guildId - The id of the guild + * @param userId - The id of the user + * @param bannerHash - The hash provided by Discord for this banner + * @param options - Optional options for the banner + */ guildMemberBanner(guildId, userId, bannerHash, options) { return this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/banner`, bannerHash, options); } + /** + * Generates an icon URL, e.g. for a guild. + * + * @param id - The id that has the icon splash + * @param iconHash - The hash provided by Discord for this icon + * @param options - Optional options for the icon + */ icon(id, iconHash, options) { return this.dynamicMakeURL(`/icons/${id}/${iconHash}`, iconHash, options); } + /** + * Generates a URL for the icon of a role + * + * @param roleId - The id of the role that has the icon + * @param roleIconHash - The hash provided by Discord for this role icon + * @param options - Optional options for the role icon + */ roleIcon(roleId, roleIconHash, options) { return this.makeURL(`/role-icons/${roleId}/${roleIconHash}`, options); } + /** + * Generates a guild invite splash URL for a guild's invite splash. + * + * @param guildId - The guild id that has the invite splash + * @param splashHash - The hash provided by Discord for this splash + * @param options - Optional options for the splash + */ splash(guildId, splashHash, options) { return this.makeURL(`/splashes/${guildId}/${splashHash}`, options); } - sticker(stickerId, extension) { - return this.makeURL(`/stickers/${stickerId}`, { - allowedExtensions: ALLOWED_STICKER_EXTENSIONS, - extension: extension ?? "png" - }); - } + /** + * Generates a sticker URL. + * + * @param stickerId - The sticker id + * @param extension - The extension of the sticker + * @privateRemarks + * Stickers cannot have a `.webp` extension, so we default to a `.png` + */ + sticker(stickerId, extension = "png") { + return this.makeURL(`/stickers/${stickerId}`, { allowedExtensions: ALLOWED_STICKER_EXTENSIONS, extension }); + } + /** + * Generates a sticker pack banner URL. + * + * @param bannerId - The banner id + * @param options - Optional options for the banner + */ stickerPackBanner(bannerId, options) { return this.makeURL(`/app-assets/710982414301790216/store/${bannerId}`, options); } + /** + * Generates a team icon URL for a team's icon. + * + * @param teamId - The team id that has the icon + * @param iconHash - The hash provided by Discord for this icon + * @param options - Optional options for the icon + */ teamIcon(teamId, iconHash, options) { return this.makeURL(`/team-icons/${teamId}/${iconHash}`, options); } + /** + * Generates a cover image for a guild scheduled event. + * + * @param scheduledEventId - The scheduled event id + * @param coverHash - The hash provided by discord for this cover image + * @param options - Optional options for the cover image + */ guildScheduledEventCover(scheduledEventId, coverHash, options) { return this.makeURL(`/guild-events/${scheduledEventId}/${coverHash}`, options); } + /** + * Constructs the URL for the resource, checking whether or not `hash` starts with `a_` if `dynamic` is set to `true`. + * + * @param route - The base cdn route + * @param hash - The hash provided by Discord for this icon + * @param options - Optional options for the link + */ dynamicMakeURL(route, hash, { forceStatic = false, ...options } = {}) { return this.makeURL(route, !forceStatic && hash.startsWith("a_") ? { ...options, extension: "gif" } : options); } + /** + * Constructs the URL for the resource + * + * @param route - The base cdn route + * @param options - The extension/size options for the link + */ makeURL(route, { allowedExtensions = ALLOWED_EXTENSIONS, extension = "webp", size } = {}) { extension = String(extension).toLowerCase(); if (!allowedExtensions.includes(extension)) { @@ -182,6 +326,14 @@ function isErrorResponse(error) { } __name(isErrorResponse, "isErrorResponse"); var DiscordAPIError = class extends Error { + /** + * @param rawError - The error reported by Discord + * @param code - The error code reported by Discord + * @param status - The status code of the response + * @param method - The method of the request that erred + * @param url - The url of the request that erred + * @param bodyData - The unparsed data for the request that errored + */ constructor(rawError, code, status, method, url, bodyData) { super(DiscordAPIError.getMessage(rawError)); this.rawError = rawError; @@ -192,6 +344,9 @@ var DiscordAPIError = class extends Error { this.requestBody = { files: bodyData.files, json: bodyData.body }; } requestBody; + /** + * The name of the error + */ get name() { return `${DiscordAPIError.name}[${this.code}]`; } @@ -229,6 +384,12 @@ __name(DiscordAPIError, "DiscordAPIError"); // src/lib/errors/HTTPError.ts var import_node_http = require("http"); var HTTPError = class extends Error { + /** + * @param status - The status code of the response + * @param method - The method of the request that erred + * @param url - The url of the request that erred + * @param bodyData - The unparsed data for the request that errored + */ constructor(status, method, url, bodyData) { super(import_node_http.STATUS_CODES[status]); this.status = status; @@ -262,6 +423,9 @@ var RateLimitError = class extends Error { this.majorParameter = majorParameter; this.global = global; } + /** + * The name of the error + */ get name() { return `${RateLimitError.name}[${this.route}]`; } @@ -277,11 +441,8 @@ var import_util = require("@discordjs/util"); var import_snowflake = require("@sapphire/snowflake"); var import_undici4 = require("undici"); -// src/lib/handlers/SequentialHandler.ts -var import_node_timers = require("timers"); +// src/lib/handlers/BurstHandler.ts var import_promises = require("timers/promises"); -var import_async_queue = require("@sapphire/async-queue"); -var import_undici3 = require("undici"); // src/lib/utils/utils.ts var import_node_buffer = require("buffer"); @@ -392,56 +553,293 @@ function shouldRetry(error) { return "code" in error && error.code === "ECONNRESET" || error.message.includes("ECONNRESET"); } __name(shouldRetry, "shouldRetry"); +async function onRateLimit(manager, rateLimitData) { + const { options } = manager; + if (!options.rejectOnRateLimit) + return; + const shouldThrow = typeof options.rejectOnRateLimit === "function" ? await options.rejectOnRateLimit(rateLimitData) : options.rejectOnRateLimit.some((route) => rateLimitData.route.startsWith(route.toLowerCase())); + if (shouldThrow) { + throw new RateLimitError(rateLimitData); + } +} +__name(onRateLimit, "onRateLimit"); -// src/lib/handlers/SequentialHandler.ts +// src/lib/handlers/Shared.ts +var import_node_timers = require("timers"); +var import_undici3 = require("undici"); var invalidCount = 0; var invalidCountResetTime = null; +function incrementInvalidCount(manager) { + if (!invalidCountResetTime || invalidCountResetTime < Date.now()) { + invalidCountResetTime = Date.now() + 1e3 * 60 * 10; + invalidCount = 0; + } + invalidCount++; + const emitInvalid = manager.options.invalidRequestWarningInterval > 0 && invalidCount % manager.options.invalidRequestWarningInterval === 0; + if (emitInvalid) { + manager.emit("invalidRequestWarning" /* InvalidRequestWarning */, { + count: invalidCount, + remainingTime: invalidCountResetTime - Date.now() + }); + } +} +__name(incrementInvalidCount, "incrementInvalidCount"); +async function makeNetworkRequest(manager, routeId, url, options, requestData, retries) { + const controller = new AbortController(); + const timeout = (0, import_node_timers.setTimeout)(() => controller.abort(), manager.options.timeout).unref(); + if (requestData.signal) { + const signal = requestData.signal; + if (signal.aborted) + controller.abort(); + else + signal.addEventListener("abort", () => controller.abort()); + } + let res; + try { + res = await (0, import_undici3.request)(url, { ...options, signal: controller.signal }); + } catch (error) { + if (!(error instanceof Error)) + throw error; + if (shouldRetry(error) && retries !== manager.options.retries) { + return null; + } + throw error; + } finally { + (0, import_node_timers.clearTimeout)(timeout); + } + if (manager.listenerCount("response" /* Response */)) { + manager.emit( + "response" /* Response */, + { + method: options.method ?? "get", + path: routeId.original, + route: routeId.bucketRoute, + options, + data: requestData, + retries + }, + { ...res } + ); + } + return res; +} +__name(makeNetworkRequest, "makeNetworkRequest"); +async function handleErrors(manager, res, method, url, requestData, retries) { + const status = res.statusCode; + if (status >= 500 && status < 600) { + if (retries !== manager.options.retries) { + return null; + } + throw new HTTPError(status, method, url, requestData); + } else { + if (status >= 400 && status < 500) { + if (status === 401 && requestData.auth) { + manager.setToken(null); + } + const data = await parseResponse(res); + throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData); + } + return res; + } +} +__name(handleErrors, "handleErrors"); + +// src/lib/handlers/BurstHandler.ts +var BurstHandler = class { + /** + * @param manager - The request manager + * @param hash - The hash that this RequestHandler handles + * @param majorParameter - The major parameter for this handler + */ + constructor(manager, hash, majorParameter) { + this.manager = manager; + this.hash = hash; + this.majorParameter = majorParameter; + this.id = `${hash}:${majorParameter}`; + } + /** + * {@inheritdoc IHandler.id} + */ + id; + /** + * {@inheritDoc IHandler.inactive} + */ + inactive = false; + /** + * Emits a debug message + * + * @param message - The message to debug + */ + debug(message) { + this.manager.emit("restDebug" /* Debug */, `[REST ${this.id}] ${message}`); + } + /** + * {@inheritDoc IHandler.queueRequest} + */ + async queueRequest(routeId, url, options, requestData) { + return this.runRequest(routeId, url, options, requestData); + } + /** + * The method that actually makes the request to the API, and updates info about the bucket accordingly + * + * @param routeId - The generalized API route with literal ids for major parameters + * @param url - The fully resolved URL to make the request to + * @param options - The fetch options needed to make the request + * @param requestData - Extra data from the user's request needed for errors and additional processing + * @param retries - The number of retries this request has already attempted (recursion) + */ + async runRequest(routeId, url, options, requestData, retries = 0) { + const method = options.method ?? "get"; + const res = await makeNetworkRequest(this.manager, routeId, url, options, requestData, retries); + if (res === null) { + return this.runRequest(routeId, url, options, requestData, ++retries); + } + const status = res.statusCode; + let retryAfter = 0; + const retry = parseHeader(res.headers["retry-after"]); + if (retry) + retryAfter = Number(retry) * 1e3 + this.manager.options.offset; + if (status === 401 || status === 403 || status === 429) { + incrementInvalidCount(this.manager); + } + if (status >= 200 && status < 300) { + return res; + } else if (status === 429) { + const isGlobal = res.headers["x-ratelimit-global"] !== void 0; + await onRateLimit(this.manager, { + timeToReset: retryAfter, + limit: Number.POSITIVE_INFINITY, + method, + hash: this.hash, + url, + route: routeId.bucketRoute, + majorParameter: this.majorParameter, + global: isGlobal + }); + this.debug( + [ + "Encountered unexpected 429 rate limit", + ` Global : ${isGlobal}`, + ` Method : ${method}`, + ` URL : ${url}`, + ` Bucket : ${routeId.bucketRoute}`, + ` Major parameter: ${routeId.majorParameter}`, + ` Hash : ${this.hash}`, + ` Limit : ${Number.POSITIVE_INFINITY}`, + ` Retry After : ${retryAfter}ms`, + ` Sublimit : None` + ].join("\n") + ); + await (0, import_promises.setTimeout)(retryAfter); + return this.runRequest(routeId, url, options, requestData, retries); + } else { + const handled = await handleErrors(this.manager, res, method, url, requestData, retries); + if (handled === null) { + return this.runRequest(routeId, url, options, requestData, ++retries); + } + return handled; + } + } +}; +__name(BurstHandler, "BurstHandler"); + +// src/lib/handlers/SequentialHandler.ts +var import_promises2 = require("timers/promises"); +var import_async_queue = require("@sapphire/async-queue"); var SequentialHandler = class { + /** + * @param manager - The request manager + * @param hash - The hash that this RequestHandler handles + * @param majorParameter - The major parameter for this handler + */ constructor(manager, hash, majorParameter) { this.manager = manager; this.hash = hash; this.majorParameter = majorParameter; this.id = `${hash}:${majorParameter}`; } + /** + * {@inheritDoc IHandler.id} + */ id; + /** + * The time this rate limit bucket will reset + */ reset = -1; + /** + * The remaining requests that can be made before we are rate limited + */ remaining = 1; + /** + * The total number of requests that can be made before we are rate limited + */ limit = Number.POSITIVE_INFINITY; + /** + * The interface used to sequence async requests sequentially + */ #asyncQueue = new import_async_queue.AsyncQueue(); + /** + * The interface used to sequence sublimited async requests sequentially + */ #sublimitedQueue = null; + /** + * A promise wrapper for when the sublimited queue is finished being processed or null when not being processed + */ #sublimitPromise = null; + /** + * Whether the sublimit queue needs to be shifted in the finally block + */ #shiftSublimit = false; + /** + * {@inheritDoc IHandler.inactive} + */ get inactive() { return this.#asyncQueue.remaining === 0 && (this.#sublimitedQueue === null || this.#sublimitedQueue.remaining === 0) && !this.limited; } + /** + * If the rate limit bucket is currently limited by the global limit + */ get globalLimited() { return this.manager.globalRemaining <= 0 && Date.now() < this.manager.globalReset; } + /** + * If the rate limit bucket is currently limited by its limit + */ get localLimited() { return this.remaining <= 0 && Date.now() < this.reset; } + /** + * If the rate limit bucket is currently limited + */ get limited() { return this.globalLimited || this.localLimited; } + /** + * The time until queued requests can continue + */ get timeToReset() { return this.reset + this.manager.options.offset - Date.now(); } + /** + * Emits a debug message + * + * @param message - The message to debug + */ debug(message) { this.manager.emit("restDebug" /* Debug */, `[REST ${this.id}] ${message}`); } + /** + * Delay all requests for the specified amount of time, handling global rate limits + * + * @param time - The amount of time to delay all requests for + */ async globalDelayFor(time) { - await (0, import_promises.setTimeout)(time); + await (0, import_promises2.setTimeout)(time); this.manager.globalDelay = null; } - async onRateLimit(rateLimitData) { - const { options } = this.manager; - if (!options.rejectOnRateLimit) - return; - const shouldThrow = typeof options.rejectOnRateLimit === "function" ? await options.rejectOnRateLimit(rateLimitData) : options.rejectOnRateLimit.some((route) => rateLimitData.route.startsWith(route.toLowerCase())); - if (shouldThrow) { - throw new RateLimitError(rateLimitData); - } - } + /** + * {@inheritDoc IHandler.queueRequest} + */ async queueRequest(routeId, url, options, requestData) { let queue = this.#asyncQueue; let queueType = 0 /* Standard */; @@ -474,26 +872,35 @@ var SequentialHandler = class { } } } + /** + * The method that actually makes the request to the api, and updates info about the bucket accordingly + * + * @param routeId - The generalized api route with literal ids for major parameters + * @param url - The fully resolved url to make the request to + * @param options - The fetch options needed to make the request + * @param requestData - Extra data from the user's request needed for errors and additional processing + * @param retries - The number of retries this request has already attempted (recursion) + */ async runRequest(routeId, url, options, requestData, retries = 0) { while (this.limited) { const isGlobal = this.globalLimited; let limit2; - let timeout2; + let timeout; let delay; if (isGlobal) { limit2 = this.manager.options.globalRequestsPerSecond; - timeout2 = this.manager.globalReset + this.manager.options.offset - Date.now(); + timeout = this.manager.globalReset + this.manager.options.offset - Date.now(); if (!this.manager.globalDelay) { - this.manager.globalDelay = this.globalDelayFor(timeout2); + this.manager.globalDelay = this.globalDelayFor(timeout); } delay = this.manager.globalDelay; } else { limit2 = this.limit; - timeout2 = this.timeToReset; - delay = (0, import_promises.setTimeout)(timeout2); + timeout = this.timeToReset; + delay = (0, import_promises2.setTimeout)(timeout); } const rateLimitData = { - timeToReset: timeout2, + timeToReset: timeout, limit: limit2, method: options.method ?? "get", hash: this.hash, @@ -503,11 +910,11 @@ var SequentialHandler = class { global: isGlobal }; this.manager.emit("rateLimited" /* RateLimited */, rateLimitData); - await this.onRateLimit(rateLimitData); + await onRateLimit(this.manager, rateLimitData); if (isGlobal) { - this.debug(`Global rate limit hit, blocking all requests for ${timeout2}ms`); + this.debug(`Global rate limit hit, blocking all requests for ${timeout}ms`); } else { - this.debug(`Waiting ${timeout2}ms for rate limit to pass`); + this.debug(`Waiting ${timeout}ms for rate limit to pass`); } await delay; } @@ -517,41 +924,9 @@ var SequentialHandler = class { } this.manager.globalRemaining--; const method = options.method ?? "get"; - const controller = new AbortController(); - const timeout = (0, import_node_timers.setTimeout)(() => controller.abort(), this.manager.options.timeout).unref(); - if (requestData.signal) { - const signal = requestData.signal; - if (signal.aborted) - controller.abort(); - else - signal.addEventListener("abort", () => controller.abort()); - } - let res; - try { - res = await (0, import_undici3.request)(url, { ...options, signal: controller.signal }); - } catch (error) { - if (!(error instanceof Error)) - throw error; - if (shouldRetry(error) && retries !== this.manager.options.retries) { - return await this.runRequest(routeId, url, options, requestData, ++retries); - } - throw error; - } finally { - (0, import_node_timers.clearTimeout)(timeout); - } - if (this.manager.listenerCount("response" /* Response */)) { - this.manager.emit( - "response" /* Response */, - { - method, - path: routeId.original, - route: routeId.bucketRoute, - options, - data: requestData, - retries - }, - { ...res } - ); + const res = await makeNetworkRequest(this.manager, routeId, url, options, requestData, retries); + if (res === null) { + return this.runRequest(routeId, url, options, requestData, ++retries); } const status = res.statusCode; let retryAfter = 0; @@ -584,34 +959,23 @@ var SequentialHandler = class { } } if (status === 401 || status === 403 || status === 429) { - if (!invalidCountResetTime || invalidCountResetTime < Date.now()) { - invalidCountResetTime = Date.now() + 1e3 * 60 * 10; - invalidCount = 0; - } - invalidCount++; - const emitInvalid = this.manager.options.invalidRequestWarningInterval > 0 && invalidCount % this.manager.options.invalidRequestWarningInterval === 0; - if (emitInvalid) { - this.manager.emit("invalidRequestWarning" /* InvalidRequestWarning */, { - count: invalidCount, - remainingTime: invalidCountResetTime - Date.now() - }); - } + incrementInvalidCount(this.manager); } if (status >= 200 && status < 300) { return res; } else if (status === 429) { const isGlobal = this.globalLimited; let limit2; - let timeout2; + let timeout; if (isGlobal) { limit2 = this.manager.options.globalRequestsPerSecond; - timeout2 = this.manager.globalReset + this.manager.options.offset - Date.now(); + timeout = this.manager.globalReset + this.manager.options.offset - Date.now(); } else { limit2 = this.limit; - timeout2 = this.timeToReset; + timeout = this.timeToReset; } - await this.onRateLimit({ - timeToReset: timeout2, + await onRateLimit(this.manager, { + timeToReset: timeout, limit: limit2, method, hash: this.hash, @@ -643,7 +1007,7 @@ var SequentialHandler = class { } this.#sublimitPromise?.resolve(); this.#sublimitPromise = null; - await (0, import_promises.setTimeout)(sublimitTimeout); + await (0, import_promises2.setTimeout)(sublimitTimeout); let resolve; const promise = new Promise((res2) => resolve = res2); this.#sublimitPromise = { promise, resolve }; @@ -653,20 +1017,12 @@ var SequentialHandler = class { } } return this.runRequest(routeId, url, options, requestData, retries); - } else if (status >= 500 && status < 600) { - if (retries !== this.manager.options.retries) { - return this.runRequest(routeId, url, options, requestData, ++retries); - } - throw new HTTPError(status, method, url, requestData); } else { - if (status >= 400 && status < 500) { - if (status === 401 && requestData.auth) { - this.manager.setToken(null); - } - const data = await parseResponse(res); - throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData); + const handled = await handleErrors(this.manager, res, method, url, requestData, retries); + if (handled === null) { + return this.runRequest(routeId, url, options, requestData, ++retries); } - return res; + return handled; } } }; @@ -683,11 +1039,30 @@ var RequestMethod = /* @__PURE__ */ ((RequestMethod2) => { return RequestMethod2; })(RequestMethod || {}); var RequestManager = class extends import_node_events.EventEmitter { + /** + * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} for all requests + * performed by this manager. + */ agent = null; + /** + * The number of requests remaining in the global bucket + */ globalRemaining; + /** + * The promise used to wait out the global rate limit + */ globalDelay = null; + /** + * The timestamp at which the global bucket resets + */ globalReset = -1; + /** + * API bucket hashes that are cached from provided routes + */ hashes = new import_collection.Collection(); + /** + * Request handlers created from the bucket hash and the major parameters + */ handlers = new import_collection.Collection(); #token = null; hashTimer; @@ -741,14 +1116,30 @@ var RequestManager = class extends import_node_events.EventEmitter { }, this.options.handlerSweepInterval).unref(); } } + /** + * Sets the default agent to use for requests performed by this manager + * + * @param agent - The agent to use + */ setAgent(agent) { this.agent = agent; return this; } + /** + * Sets the authorization token that should be used for requests + * + * @param token - The authorization token to use + */ setToken(token) { this.#token = token; return this; } + /** + * Queues a request to be sent + * + * @param request - All the information needed to make a request + * @returns The response from the api request + */ async queueRequest(request2) { const routeId = RequestManager.generateRouteData(request2.fullRoute, request2.method); const hash = this.hashes.get(`${request2.method}:${routeId.bucketRoute}`) ?? { @@ -764,11 +1155,23 @@ var RequestManager = class extends import_node_events.EventEmitter { signal: request2.signal }); } + /** + * Creates a new rate limit handler from a hash, based on the hash and the major parameter + * + * @param hash - The hash for the route + * @param majorParameter - The major parameter for this handler + * @internal + */ createHandler(hash, majorParameter) { - const queue = new SequentialHandler(this, hash, majorParameter); + const queue = majorParameter === BurstHandlerMajorIdKey ? new BurstHandler(this, hash, majorParameter) : new SequentialHandler(this, hash, majorParameter); this.handlers.set(queue.id, queue); return queue; } + /** + * Formats the request data to a usable format for fetch + * + * @param request - The request data + */ async resolveRequest(request2) { const { options } = this; let query = ""; @@ -800,7 +1203,13 @@ var RequestManager = class extends import_node_events.EventEmitter { const fileKey = file.key ?? `files[${index}]`; if (import_node_buffer2.Buffer.isBuffer(file.data)) { const { fileTypeFromBuffer } = await getFileType(); - const contentType = file.contentType ?? (await fileTypeFromBuffer(file.data))?.mime; + let contentType = file.contentType; + if (!contentType) { + const parsedType = (await fileTypeFromBuffer(file.data))?.mime; + if (parsedType) { + contentType = OverwrittenMimeTypes[parsedType] ?? parsedType; + } + } formData.append(fileKey, new import_node_buffer2.Blob([file.data], { type: contentType }), file.name); } else { formData.append(fileKey, new import_node_buffer2.Blob([`${file.data}`], { type: file.contentType }), file.name); @@ -835,19 +1244,39 @@ var RequestManager = class extends import_node_events.EventEmitter { fetchOptions.dispatcher = request2.dispatcher ?? this.agent ?? void 0; return { url, fetchOptions }; } + /** + * Stops the hash sweeping interval + */ clearHashSweeper() { (0, import_node_timers2.clearInterval)(this.hashTimer); } + /** + * Stops the request handler sweeping interval + */ clearHandlerSweeper() { (0, import_node_timers2.clearInterval)(this.handlerTimer); } + /** + * Generates route data for an endpoint:method + * + * @param endpoint - The raw endpoint to generalize + * @param method - The HTTP method this endpoint is called without + * @internal + */ static generateRouteData(endpoint, method) { - const majorIdMatch = /^\/(?:channels|guilds|webhooks)\/(\d{16,19})/.exec(endpoint); + if (endpoint.startsWith("/interactions/") && endpoint.endsWith("/callback")) { + return { + majorParameter: BurstHandlerMajorIdKey, + bucketRoute: "/interactions/:id/:token/callback", + original: endpoint + }; + } + const majorIdMatch = /^\/(?:channels|guilds|webhooks)\/(\d{17,19})/.exec(endpoint); const majorId = majorIdMatch?.[1] ?? "global"; - const baseRoute = endpoint.replaceAll(/\d{16,19}/g, ":id").replace(/\/reactions\/(.*)/, "/reactions/:reaction"); + const baseRoute = endpoint.replaceAll(/\d{17,19}/g, ":id").replace(/\/reactions\/(.*)/, "/reactions/:reaction"); let exceptions = ""; if (method === "DELETE" /* Delete */ && baseRoute === "/channels/:id/messages/:id") { - const id = /\d{16,19}$/.exec(endpoint)[0]; + const id = /\d{17,19}$/.exec(endpoint)[0]; const timestamp = import_snowflake.DiscordSnowflake.timestampFrom(id); if (Date.now() - timestamp > 1e3 * 60 * 60 * 24 * 14) { exceptions += "/Delete Old Message"; @@ -880,36 +1309,89 @@ var REST = class extends import_node_events2.EventEmitter { this.requestManager.off(name, listener); }); } + /** + * Gets the agent set for this instance + */ getAgent() { return this.requestManager.agent; } + /** + * Sets the default agent to use for requests performed by this instance + * + * @param agent - Sets the agent to use + */ setAgent(agent) { this.requestManager.setAgent(agent); return this; } + /** + * Sets the authorization token that should be used for requests + * + * @param token - The authorization token to use + */ setToken(token) { this.requestManager.setToken(token); return this; } + /** + * Runs a get request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async get(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "GET" /* Get */ }); } + /** + * Runs a delete request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async delete(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "DELETE" /* Delete */ }); } + /** + * Runs a post request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async post(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "POST" /* Post */ }); } + /** + * Runs a put request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async put(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "PUT" /* Put */ }); } + /** + * Runs a patch request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async patch(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "PATCH" /* Patch */ }); } + /** + * Runs a request from the api + * + * @param options - Request options + */ async request(options) { const response = await this.raw(options); return parseResponse(response); } + /** + * Runs a request from the API, yielding the raw Response object + * + * @param options - Request options + */ async raw(options) { return this.requestManager.queueRequest(options); } @@ -917,17 +1399,20 @@ var REST = class extends import_node_events2.EventEmitter { __name(REST, "REST"); // src/index.ts -var version = "1.5.0"; +var version = "1.7.1"; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { ALLOWED_EXTENSIONS, ALLOWED_SIZES, ALLOWED_STICKER_EXTENSIONS, + BurstHandlerMajorIdKey, CDN, DefaultRestOptions, DefaultUserAgent, + DefaultUserAgentAppendix, DiscordAPIError, HTTPError, + OverwrittenMimeTypes, REST, RESTEvents, RateLimitError, diff --git a/node_modules/@discordjs/rest/dist/index.js.map b/node_modules/@discordjs/rest/dist/index.js.map index b21a0eb..f01c8dd 100644 --- a/node_modules/@discordjs/rest/dist/index.js.map +++ b/node_modules/@discordjs/rest/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.ts","../src/lib/CDN.ts","../src/lib/utils/constants.ts","../src/lib/errors/DiscordAPIError.ts","../src/lib/errors/HTTPError.ts","../src/lib/errors/RateLimitError.ts","../src/lib/RequestManager.ts","../src/lib/handlers/SequentialHandler.ts","../src/lib/utils/utils.ts","../src/lib/REST.ts"],"sourcesContent":["export * from './lib/CDN.js';\nexport * from './lib/errors/DiscordAPIError.js';\nexport * from './lib/errors/HTTPError.js';\nexport * from './lib/errors/RateLimitError.js';\nexport * from './lib/RequestManager.js';\nexport * from './lib/REST.js';\nexport * from './lib/utils/constants.js';\nexport { makeURLSearchParams, parseResponse } from './lib/utils/utils.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/rest/#readme | @discordjs/rest} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const version: string = '1.5.0';\n","/* eslint-disable jsdoc/check-param-names */\nimport { URL } from 'node:url';\nimport {\n\tALLOWED_EXTENSIONS,\n\tALLOWED_SIZES,\n\tALLOWED_STICKER_EXTENSIONS,\n\tDefaultRestOptions,\n\ttype ImageExtension,\n\ttype ImageSize,\n\ttype StickerExtension,\n} from './utils/constants.js';\n\n/**\n * The options used for image URLs\n */\nexport interface BaseImageURLOptions {\n\t/**\n\t * The extension to use for the image URL\n\t *\n\t * @defaultValue `'webp'`\n\t */\n\textension?: ImageExtension;\n\t/**\n\t * The size specified in the image URL\n\t */\n\tsize?: ImageSize;\n}\n\n/**\n * The options used for image URLs with animated content\n */\nexport interface ImageURLOptions extends BaseImageURLOptions {\n\t/**\n\t * Whether or not to prefer the static version of an image asset.\n\t */\n\tforceStatic?: boolean;\n}\n\n/**\n * The options to use when making a CDN URL\n */\nexport interface MakeURLOptions {\n\t/**\n\t * The allowed extensions that can be used\n\t */\n\tallowedExtensions?: readonly string[];\n\t/**\n\t * The extension to use for the image URL\n\t *\n\t * @defaultValue `'webp'`\n\t */\n\textension?: string | undefined;\n\t/**\n\t * The size specified in the image URL\n\t */\n\tsize?: ImageSize;\n}\n\n/**\n * The CDN link builder\n */\nexport class CDN {\n\tpublic constructor(private readonly base: string = DefaultRestOptions.cdn) {}\n\n\t/**\n\t * Generates an app asset URL for a client's asset.\n\t *\n\t * @param clientId - The client id that has the asset\n\t * @param assetHash - The hash provided by Discord for this asset\n\t * @param options - Optional options for the asset\n\t */\n\tpublic appAsset(clientId: string, assetHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-assets/${clientId}/${assetHash}`, options);\n\t}\n\n\t/**\n\t * Generates an app icon URL for a client's icon.\n\t *\n\t * @param clientId - The client id that has the icon\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic appIcon(clientId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-icons/${clientId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates an avatar URL, e.g. for a user or a webhook.\n\t *\n\t * @param id - The id that has the icon\n\t * @param avatarHash - The hash provided by Discord for this avatar\n\t * @param options - Optional options for the avatar\n\t */\n\tpublic avatar(id: string, avatarHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/avatars/${id}/${avatarHash}`, avatarHash, options);\n\t}\n\n\t/**\n\t * Generates a banner URL, e.g. for a user or a guild.\n\t *\n\t * @param id - The id that has the banner splash\n\t * @param bannerHash - The hash provided by Discord for this banner\n\t * @param options - Optional options for the banner\n\t */\n\tpublic banner(id: string, bannerHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/banners/${id}/${bannerHash}`, bannerHash, options);\n\t}\n\n\t/**\n\t * Generates an icon URL for a channel, e.g. a group DM.\n\t *\n\t * @param channelId - The channel id that has the icon\n\t * @param iconHash - The hash provided by Discord for this channel\n\t * @param options - Optional options for the icon\n\t */\n\tpublic channelIcon(channelId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/channel-icons/${channelId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates the default avatar URL for a discriminator.\n\t *\n\t * @param discriminator - The discriminator modulo 5\n\t */\n\tpublic defaultAvatar(discriminator: number): string {\n\t\treturn this.makeURL(`/embed/avatars/${discriminator}`, { extension: 'png' });\n\t}\n\n\t/**\n\t * Generates a discovery splash URL for a guild's discovery splash.\n\t *\n\t * @param guildId - The guild id that has the discovery splash\n\t * @param splashHash - The hash provided by Discord for this splash\n\t * @param options - Optional options for the splash\n\t */\n\tpublic discoverySplash(guildId: string, splashHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/discovery-splashes/${guildId}/${splashHash}`, options);\n\t}\n\n\t/**\n\t * Generates an emoji's URL for an emoji.\n\t *\n\t * @param emojiId - The emoji id\n\t * @param extension - The extension of the emoji\n\t */\n\tpublic emoji(emojiId: string, extension?: ImageExtension): string {\n\t\treturn this.makeURL(`/emojis/${emojiId}`, { extension });\n\t}\n\n\t/**\n\t * Generates a guild member avatar URL.\n\t *\n\t * @param guildId - The id of the guild\n\t * @param userId - The id of the user\n\t * @param avatarHash - The hash provided by Discord for this avatar\n\t * @param options - Optional options for the avatar\n\t */\n\tpublic guildMemberAvatar(\n\t\tguildId: string,\n\t\tuserId: string,\n\t\tavatarHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/avatars/${avatarHash}`, avatarHash, options);\n\t}\n\n\t/**\n\t * Generates a guild member banner URL.\n\t *\n\t * @param guildId - The id of the guild\n\t * @param userId - The id of the user\n\t * @param bannerHash - The hash provided by Discord for this banner\n\t * @param options - Optional options for the banner\n\t */\n\tpublic guildMemberBanner(\n\t\tguildId: string,\n\t\tuserId: string,\n\t\tbannerHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/banner`, bannerHash, options);\n\t}\n\n\t/**\n\t * Generates an icon URL, e.g. for a guild.\n\t *\n\t * @param id - The id that has the icon splash\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic icon(id: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/icons/${id}/${iconHash}`, iconHash, options);\n\t}\n\n\t/**\n\t * Generates a URL for the icon of a role\n\t *\n\t * @param roleId - The id of the role that has the icon\n\t * @param roleIconHash - The hash provided by Discord for this role icon\n\t * @param options - Optional options for the role icon\n\t */\n\tpublic roleIcon(roleId: string, roleIconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/role-icons/${roleId}/${roleIconHash}`, options);\n\t}\n\n\t/**\n\t * Generates a guild invite splash URL for a guild's invite splash.\n\t *\n\t * @param guildId - The guild id that has the invite splash\n\t * @param splashHash - The hash provided by Discord for this splash\n\t * @param options - Optional options for the splash\n\t */\n\tpublic splash(guildId: string, splashHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/splashes/${guildId}/${splashHash}`, options);\n\t}\n\n\t/**\n\t * Generates a sticker URL.\n\t *\n\t * @param stickerId - The sticker id\n\t * @param extension - The extension of the sticker\n\t */\n\tpublic sticker(stickerId: string, extension?: StickerExtension): string {\n\t\treturn this.makeURL(`/stickers/${stickerId}`, {\n\t\t\tallowedExtensions: ALLOWED_STICKER_EXTENSIONS,\n\t\t\textension: extension ?? 'png', // Stickers cannot have a `.webp` extension, so we default to a `.png`\n\t\t});\n\t}\n\n\t/**\n\t * Generates a sticker pack banner URL.\n\t *\n\t * @param bannerId - The banner id\n\t * @param options - Optional options for the banner\n\t */\n\tpublic stickerPackBanner(bannerId: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-assets/710982414301790216/store/${bannerId}`, options);\n\t}\n\n\t/**\n\t * Generates a team icon URL for a team's icon.\n\t *\n\t * @param teamId - The team id that has the icon\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic teamIcon(teamId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/team-icons/${teamId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates a cover image for a guild scheduled event.\n\t *\n\t * @param scheduledEventId - The scheduled event id\n\t * @param coverHash - The hash provided by discord for this cover image\n\t * @param options - Optional options for the cover image\n\t */\n\tpublic guildScheduledEventCover(\n\t\tscheduledEventId: string,\n\t\tcoverHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.makeURL(`/guild-events/${scheduledEventId}/${coverHash}`, options);\n\t}\n\n\t/**\n\t * Constructs the URL for the resource, checking whether or not `hash` starts with `a_` if `dynamic` is set to `true`.\n\t *\n\t * @param route - The base cdn route\n\t * @param hash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the link\n\t */\n\tprivate dynamicMakeURL(\n\t\troute: string,\n\t\thash: string,\n\t\t{ forceStatic = false, ...options }: Readonly = {},\n\t): string {\n\t\treturn this.makeURL(route, !forceStatic && hash.startsWith('a_') ? { ...options, extension: 'gif' } : options);\n\t}\n\n\t/**\n\t * Constructs the URL for the resource\n\t *\n\t * @param route - The base cdn route\n\t * @param options - The extension/size options for the link\n\t */\n\tprivate makeURL(\n\t\troute: string,\n\t\t{ allowedExtensions = ALLOWED_EXTENSIONS, extension = 'webp', size }: Readonly = {},\n\t): string {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\textension = String(extension).toLowerCase();\n\n\t\tif (!allowedExtensions.includes(extension)) {\n\t\t\tthrow new RangeError(`Invalid extension provided: ${extension}\\nMust be one of: ${allowedExtensions.join(', ')}`);\n\t\t}\n\n\t\tif (size && !ALLOWED_SIZES.includes(size)) {\n\t\t\tthrow new RangeError(`Invalid size provided: ${size}\\nMust be one of: ${ALLOWED_SIZES.join(', ')}`);\n\t\t}\n\n\t\tconst url = new URL(`${this.base}${route}.${extension}`);\n\n\t\tif (size) {\n\t\t\turl.searchParams.set('size', String(size));\n\t\t}\n\n\t\treturn url.toString();\n\t}\n}\n","import process from 'node:process';\nimport { APIVersion } from 'discord-api-types/v10';\nimport { Agent } from 'undici';\nimport type { RESTOptions } from '../REST.js';\n\nexport const DefaultUserAgent = `DiscordBot (https://discord.js.org, 1.5.0)`;\n\nexport const DefaultRestOptions = {\n\tget agent() {\n\t\treturn new Agent({\n\t\t\tconnect: {\n\t\t\t\ttimeout: 30_000,\n\t\t\t},\n\t\t});\n\t},\n\tapi: 'https://discord.com/api',\n\tauthPrefix: 'Bot',\n\tcdn: 'https://cdn.discordapp.com',\n\theaders: {},\n\tinvalidRequestWarningInterval: 0,\n\tglobalRequestsPerSecond: 50,\n\toffset: 50,\n\trejectOnRateLimit: null,\n\tretries: 3,\n\ttimeout: 15_000,\n\tuserAgentAppendix: `Node.js ${process.version}`,\n\tversion: APIVersion,\n\thashSweepInterval: 14_400_000, // 4 Hours\n\thashLifetime: 86_400_000, // 24 Hours\n\thandlerSweepInterval: 3_600_000, // 1 Hour\n} as const satisfies Required;\n\n/**\n * The events that the REST manager emits\n */\nexport const enum RESTEvents {\n\tDebug = 'restDebug',\n\tHandlerSweep = 'handlerSweep',\n\tHashSweep = 'hashSweep',\n\tInvalidRequestWarning = 'invalidRequestWarning',\n\tRateLimited = 'rateLimited',\n\tResponse = 'response',\n}\n\nexport const ALLOWED_EXTENSIONS = ['webp', 'png', 'jpg', 'jpeg', 'gif'] as const satisfies readonly string[];\nexport const ALLOWED_STICKER_EXTENSIONS = ['png', 'json'] as const satisfies readonly string[];\nexport const ALLOWED_SIZES = [16, 32, 64, 128, 256, 512, 1_024, 2_048, 4_096] as const satisfies readonly number[];\n\nexport type ImageExtension = typeof ALLOWED_EXTENSIONS[number];\nexport type StickerExtension = typeof ALLOWED_STICKER_EXTENSIONS[number];\nexport type ImageSize = typeof ALLOWED_SIZES[number];\n","import type { InternalRequest, RawFile } from '../RequestManager.js';\n\ninterface DiscordErrorFieldInformation {\n\tcode: string;\n\tmessage: string;\n}\n\ninterface DiscordErrorGroupWrapper {\n\t_errors: DiscordError[];\n}\n\ntype DiscordError = DiscordErrorFieldInformation | DiscordErrorGroupWrapper | string | { [k: string]: DiscordError };\n\nexport interface DiscordErrorData {\n\tcode: number;\n\terrors?: DiscordError;\n\tmessage: string;\n}\n\nexport interface OAuthErrorData {\n\terror: string;\n\terror_description?: string;\n}\n\nexport interface RequestBody {\n\tfiles: RawFile[] | undefined;\n\tjson: unknown | undefined;\n}\n\nfunction isErrorGroupWrapper(error: DiscordError): error is DiscordErrorGroupWrapper {\n\treturn Reflect.has(error as Record, '_errors');\n}\n\nfunction isErrorResponse(error: DiscordError): error is DiscordErrorFieldInformation {\n\treturn typeof Reflect.get(error as Record, 'message') === 'string';\n}\n\n/**\n * Represents an API error returned by Discord\n */\nexport class DiscordAPIError extends Error {\n\tpublic requestBody: RequestBody;\n\n\t/**\n\t * @param rawError - The error reported by Discord\n\t * @param code - The error code reported by Discord\n\t * @param status - The status code of the response\n\t * @param method - The method of the request that erred\n\t * @param url - The url of the request that erred\n\t * @param bodyData - The unparsed data for the request that errored\n\t */\n\tpublic constructor(\n\t\tpublic rawError: DiscordErrorData | OAuthErrorData,\n\t\tpublic code: number | string,\n\t\tpublic status: number,\n\t\tpublic method: string,\n\t\tpublic url: string,\n\t\tbodyData: Pick,\n\t) {\n\t\tsuper(DiscordAPIError.getMessage(rawError));\n\n\t\tthis.requestBody = { files: bodyData.files, json: bodyData.body };\n\t}\n\n\t/**\n\t * The name of the error\n\t */\n\tpublic override get name(): string {\n\t\treturn `${DiscordAPIError.name}[${this.code}]`;\n\t}\n\n\tprivate static getMessage(error: DiscordErrorData | OAuthErrorData) {\n\t\tlet flattened = '';\n\t\tif ('code' in error) {\n\t\t\tif (error.errors) {\n\t\t\t\tflattened = [...this.flattenDiscordError(error.errors)].join('\\n');\n\t\t\t}\n\n\t\t\treturn error.message && flattened\n\t\t\t\t? `${error.message}\\n${flattened}`\n\t\t\t\t: error.message || flattened || 'Unknown Error';\n\t\t}\n\n\t\treturn error.error_description ?? 'No Description';\n\t}\n\n\tprivate static *flattenDiscordError(obj: DiscordError, key = ''): IterableIterator {\n\t\tif (isErrorResponse(obj)) {\n\t\t\treturn yield `${key.length ? `${key}[${obj.code}]` : `${obj.code}`}: ${obj.message}`.trim();\n\t\t}\n\n\t\tfor (const [otherKey, val] of Object.entries(obj)) {\n\t\t\tconst nextKey = otherKey.startsWith('_')\n\t\t\t\t? key\n\t\t\t\t: key\n\t\t\t\t? Number.isNaN(Number(otherKey))\n\t\t\t\t\t? `${key}.${otherKey}`\n\t\t\t\t\t: `${key}[${otherKey}]`\n\t\t\t\t: otherKey;\n\n\t\t\tif (typeof val === 'string') {\n\t\t\t\tyield val;\n\t\t\t} else if (isErrorGroupWrapper(val)) {\n\t\t\t\tfor (const error of val._errors) {\n\t\t\t\t\tyield* this.flattenDiscordError(error, nextKey);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tyield* this.flattenDiscordError(val, nextKey);\n\t\t\t}\n\t\t}\n\t}\n}\n","import { STATUS_CODES } from 'node:http';\nimport type { InternalRequest } from '../RequestManager.js';\nimport type { RequestBody } from './DiscordAPIError.js';\n\n/**\n * Represents a HTTP error\n */\nexport class HTTPError extends Error {\n\tpublic requestBody: RequestBody;\n\n\tpublic override name = HTTPError.name;\n\n\t/**\n\t * @param status - The status code of the response\n\t * @param method - The method of the request that erred\n\t * @param url - The url of the request that erred\n\t * @param bodyData - The unparsed data for the request that errored\n\t */\n\tpublic constructor(\n\t\tpublic status: number,\n\t\tpublic method: string,\n\t\tpublic url: string,\n\t\tbodyData: Pick,\n\t) {\n\t\tsuper(STATUS_CODES[status]);\n\n\t\tthis.requestBody = { files: bodyData.files, json: bodyData.body };\n\t}\n}\n","import type { RateLimitData } from '../REST';\n\nexport class RateLimitError extends Error implements RateLimitData {\n\tpublic timeToReset: number;\n\n\tpublic limit: number;\n\n\tpublic method: string;\n\n\tpublic hash: string;\n\n\tpublic url: string;\n\n\tpublic route: string;\n\n\tpublic majorParameter: string;\n\n\tpublic global: boolean;\n\n\tpublic constructor({ timeToReset, limit, method, hash, url, route, majorParameter, global }: RateLimitData) {\n\t\tsuper();\n\t\tthis.timeToReset = timeToReset;\n\t\tthis.limit = limit;\n\t\tthis.method = method;\n\t\tthis.hash = hash;\n\t\tthis.url = url;\n\t\tthis.route = route;\n\t\tthis.majorParameter = majorParameter;\n\t\tthis.global = global;\n\t}\n\n\t/**\n\t * The name of the error\n\t */\n\tpublic override get name(): string {\n\t\treturn `${RateLimitError.name}[${this.route}]`;\n\t}\n}\n","import { Blob, Buffer } from 'node:buffer';\nimport { EventEmitter } from 'node:events';\nimport { setInterval, clearInterval } from 'node:timers';\nimport type { URLSearchParams } from 'node:url';\nimport { Collection } from '@discordjs/collection';\nimport { lazy } from '@discordjs/util';\nimport { DiscordSnowflake } from '@sapphire/snowflake';\nimport { FormData, type RequestInit, type BodyInit, type Dispatcher, type Agent } from 'undici';\nimport type { RESTOptions, RestEvents, RequestOptions } from './REST.js';\nimport type { IHandler } from './handlers/IHandler.js';\nimport { SequentialHandler } from './handlers/SequentialHandler.js';\nimport { DefaultRestOptions, DefaultUserAgent, RESTEvents } from './utils/constants.js';\nimport { resolveBody } from './utils/utils.js';\n\n// Make this a lazy dynamic import as file-type is a pure ESM package\nconst getFileType = lazy(async () => import('file-type'));\n\n/**\n * Represents a file to be added to the request\n */\nexport interface RawFile {\n\t/**\n\t * Content-Type of the file\n\t */\n\tcontentType?: string;\n\t/**\n\t * The actual data for the file\n\t */\n\tdata: Buffer | boolean | number | string;\n\t/**\n\t * An explicit key to use for key of the formdata field for this file.\n\t * When not provided, the index of the file in the files array is used in the form `files[${index}]`.\n\t * If you wish to alter the placeholder snowflake, you must provide this property in the same form (`files[${placeholder}]`)\n\t */\n\tkey?: string;\n\t/**\n\t * The name of the file\n\t */\n\tname: string;\n}\n\n/**\n * Represents possible data to be given to an endpoint\n */\nexport interface RequestData {\n\t/**\n\t * Whether to append JSON data to form data instead of `payload_json` when sending files\n\t */\n\tappendToFormData?: boolean;\n\t/**\n\t * If this request needs the `Authorization` header\n\t *\n\t * @defaultValue `true`\n\t */\n\tauth?: boolean;\n\t/**\n\t * The authorization prefix to use for this request, useful if you use this with bearer tokens\n\t *\n\t * @defaultValue `'Bot'`\n\t */\n\tauthPrefix?: 'Bearer' | 'Bot';\n\t/**\n\t * The body to send to this request.\n\t * If providing as BodyInit, set `passThroughBody: true`\n\t */\n\tbody?: BodyInit | unknown;\n\t/**\n\t * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} to use for the request.\n\t */\n\tdispatcher?: Agent;\n\t/**\n\t * Files to be attached to this request\n\t */\n\tfiles?: RawFile[] | undefined;\n\t/**\n\t * Additional headers to add to this request\n\t */\n\theaders?: Record;\n\t/**\n\t * Whether to pass-through the body property directly to `fetch()`.\n\t * This only applies when files is NOT present\n\t */\n\tpassThroughBody?: boolean;\n\t/**\n\t * Query string parameters to append to the called endpoint\n\t */\n\tquery?: URLSearchParams;\n\t/**\n\t * Reason to show in the audit logs\n\t */\n\treason?: string | undefined;\n\t/**\n\t * The signal to abort the queue entry or the REST call, where applicable\n\t */\n\tsignal?: AbortSignal | undefined;\n\t/**\n\t * If this request should be versioned\n\t *\n\t * @defaultValue `true`\n\t */\n\tversioned?: boolean;\n}\n\n/**\n * Possible headers for an API call\n */\nexport interface RequestHeaders {\n\tAuthorization?: string;\n\t'User-Agent': string;\n\t'X-Audit-Log-Reason'?: string;\n}\n\n/**\n * Possible API methods to be used when doing requests\n */\nexport const enum RequestMethod {\n\tDelete = 'DELETE',\n\tGet = 'GET',\n\tPatch = 'PATCH',\n\tPost = 'POST',\n\tPut = 'PUT',\n}\n\nexport type RouteLike = `/${string}`;\n\n/**\n * Internal request options\n *\n * @internal\n */\nexport interface InternalRequest extends RequestData {\n\tfullRoute: RouteLike;\n\tmethod: RequestMethod;\n}\n\nexport type HandlerRequestData = Pick;\n\n/**\n * Parsed route data for an endpoint\n *\n * @internal\n */\nexport interface RouteData {\n\tbucketRoute: string;\n\tmajorParameter: string;\n\toriginal: RouteLike;\n}\n\n/**\n * Represents a hash and its associated fields\n *\n * @internal\n */\nexport interface HashData {\n\tlastAccess: number;\n\tvalue: string;\n}\n\nexport interface RequestManager {\n\temit: ((event: K, ...args: RestEvents[K]) => boolean) &\n\t\t((event: Exclude, ...args: any[]) => boolean);\n\n\toff: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\ton: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tonce: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tremoveAllListeners: ((event?: K) => this) &\n\t\t((event?: Exclude) => this);\n}\n\n/**\n * Represents the class that manages handlers for endpoints\n */\nexport class RequestManager extends EventEmitter {\n\t/**\n\t * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} for all requests\n\t * performed by this manager.\n\t */\n\tpublic agent: Dispatcher | null = null;\n\n\t/**\n\t * The number of requests remaining in the global bucket\n\t */\n\tpublic globalRemaining: number;\n\n\t/**\n\t * The promise used to wait out the global rate limit\n\t */\n\tpublic globalDelay: Promise | null = null;\n\n\t/**\n\t * The timestamp at which the global bucket resets\n\t */\n\tpublic globalReset = -1;\n\n\t/**\n\t * API bucket hashes that are cached from provided routes\n\t */\n\tpublic readonly hashes = new Collection();\n\n\t/**\n\t * Request handlers created from the bucket hash and the major parameters\n\t */\n\tpublic readonly handlers = new Collection();\n\n\t#token: string | null = null;\n\n\tprivate hashTimer!: NodeJS.Timer;\n\n\tprivate handlerTimer!: NodeJS.Timer;\n\n\tpublic readonly options: RESTOptions;\n\n\tpublic constructor(options: Partial) {\n\t\tsuper();\n\t\tthis.options = { ...DefaultRestOptions, ...options };\n\t\tthis.options.offset = Math.max(0, this.options.offset);\n\t\tthis.globalRemaining = this.options.globalRequestsPerSecond;\n\t\tthis.agent = options.agent ?? null;\n\n\t\t// Start sweepers\n\t\tthis.setupSweepers();\n\t}\n\n\tprivate setupSweepers() {\n\t\t// eslint-disable-next-line unicorn/consistent-function-scoping\n\t\tconst validateMaxInterval = (interval: number) => {\n\t\t\tif (interval > 14_400_000) {\n\t\t\t\tthrow new Error('Cannot set an interval greater than 4 hours');\n\t\t\t}\n\t\t};\n\n\t\tif (this.options.hashSweepInterval !== 0 && this.options.hashSweepInterval !== Number.POSITIVE_INFINITY) {\n\t\t\tvalidateMaxInterval(this.options.hashSweepInterval);\n\t\t\tthis.hashTimer = setInterval(() => {\n\t\t\t\tconst sweptHashes = new Collection();\n\t\t\t\tconst currentDate = Date.now();\n\n\t\t\t\t// Begin sweeping hash based on lifetimes\n\t\t\t\tthis.hashes.sweep((val, key) => {\n\t\t\t\t\t// `-1` indicates a global hash\n\t\t\t\t\tif (val.lastAccess === -1) return false;\n\n\t\t\t\t\t// Check if lifetime has been exceeded\n\t\t\t\t\tconst shouldSweep = Math.floor(currentDate - val.lastAccess) > this.options.hashLifetime;\n\n\t\t\t\t\t// Add hash to collection of swept hashes\n\t\t\t\t\tif (shouldSweep) {\n\t\t\t\t\t\t// Add to swept hashes\n\t\t\t\t\t\tsweptHashes.set(key, val);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Emit debug information\n\t\t\t\t\tthis.emit(RESTEvents.Debug, `Hash ${val.value} for ${key} swept due to lifetime being exceeded`);\n\n\t\t\t\t\treturn shouldSweep;\n\t\t\t\t});\n\n\t\t\t\t// Fire event\n\t\t\t\tthis.emit(RESTEvents.HashSweep, sweptHashes);\n\t\t\t}, this.options.hashSweepInterval).unref();\n\t\t}\n\n\t\tif (this.options.handlerSweepInterval !== 0 && this.options.handlerSweepInterval !== Number.POSITIVE_INFINITY) {\n\t\t\tvalidateMaxInterval(this.options.handlerSweepInterval);\n\t\t\tthis.handlerTimer = setInterval(() => {\n\t\t\t\tconst sweptHandlers = new Collection();\n\n\t\t\t\t// Begin sweeping handlers based on activity\n\t\t\t\tthis.handlers.sweep((val, key) => {\n\t\t\t\t\tconst { inactive } = val;\n\n\t\t\t\t\t// Collect inactive handlers\n\t\t\t\t\tif (inactive) {\n\t\t\t\t\t\tsweptHandlers.set(key, val);\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.emit(RESTEvents.Debug, `Handler ${val.id} for ${key} swept due to being inactive`);\n\t\t\t\t\treturn inactive;\n\t\t\t\t});\n\n\t\t\t\t// Fire event\n\t\t\t\tthis.emit(RESTEvents.HandlerSweep, sweptHandlers);\n\t\t\t}, this.options.handlerSweepInterval).unref();\n\t\t}\n\t}\n\n\t/**\n\t * Sets the default agent to use for requests performed by this manager\n\t *\n\t * @param agent - The agent to use\n\t */\n\tpublic setAgent(agent: Dispatcher) {\n\t\tthis.agent = agent;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the authorization token that should be used for requests\n\t *\n\t * @param token - The authorization token to use\n\t */\n\tpublic setToken(token: string) {\n\t\tthis.#token = token;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Queues a request to be sent\n\t *\n\t * @param request - All the information needed to make a request\n\t * @returns The response from the api request\n\t */\n\tpublic async queueRequest(request: InternalRequest): Promise {\n\t\t// Generalize the endpoint to its route data\n\t\tconst routeId = RequestManager.generateRouteData(request.fullRoute, request.method);\n\t\t// Get the bucket hash for the generic route, or point to a global route otherwise\n\t\tconst hash = this.hashes.get(`${request.method}:${routeId.bucketRoute}`) ?? {\n\t\t\tvalue: `Global(${request.method}:${routeId.bucketRoute})`,\n\t\t\tlastAccess: -1,\n\t\t};\n\n\t\t// Get the request handler for the obtained hash, with its major parameter\n\t\tconst handler =\n\t\t\tthis.handlers.get(`${hash.value}:${routeId.majorParameter}`) ??\n\t\t\tthis.createHandler(hash.value, routeId.majorParameter);\n\n\t\t// Resolve the request into usable fetch options\n\t\tconst { url, fetchOptions } = await this.resolveRequest(request);\n\n\t\t// Queue the request\n\t\treturn handler.queueRequest(routeId, url, fetchOptions, {\n\t\t\tbody: request.body,\n\t\t\tfiles: request.files,\n\t\t\tauth: request.auth !== false,\n\t\t\tsignal: request.signal,\n\t\t});\n\t}\n\n\t/**\n\t * Creates a new rate limit handler from a hash, based on the hash and the major parameter\n\t *\n\t * @param hash - The hash for the route\n\t * @param majorParameter - The major parameter for this handler\n\t * @internal\n\t */\n\tprivate createHandler(hash: string, majorParameter: string) {\n\t\t// Create the async request queue to handle requests\n\t\tconst queue = new SequentialHandler(this, hash, majorParameter);\n\t\t// Save the queue based on its id\n\t\tthis.handlers.set(queue.id, queue);\n\n\t\treturn queue;\n\t}\n\n\t/**\n\t * Formats the request data to a usable format for fetch\n\t *\n\t * @param request - The request data\n\t */\n\tprivate async resolveRequest(request: InternalRequest): Promise<{ fetchOptions: RequestOptions; url: string }> {\n\t\tconst { options } = this;\n\n\t\tlet query = '';\n\n\t\t// If a query option is passed, use it\n\t\tif (request.query) {\n\t\t\tconst resolvedQuery = request.query.toString();\n\t\t\tif (resolvedQuery !== '') {\n\t\t\t\tquery = `?${resolvedQuery}`;\n\t\t\t}\n\t\t}\n\n\t\t// Create the required headers\n\t\tconst headers: RequestHeaders = {\n\t\t\t...this.options.headers,\n\t\t\t'User-Agent': `${DefaultUserAgent} ${options.userAgentAppendix}`.trim(),\n\t\t};\n\n\t\t// If this request requires authorization (allowing non-\"authorized\" requests for webhooks)\n\t\tif (request.auth !== false) {\n\t\t\t// If we haven't received a token, throw an error\n\t\t\tif (!this.#token) {\n\t\t\t\tthrow new Error('Expected token to be set for this request, but none was present');\n\t\t\t}\n\n\t\t\theaders.Authorization = `${request.authPrefix ?? this.options.authPrefix} ${this.#token}`;\n\t\t}\n\n\t\t// If a reason was set, set it's appropriate header\n\t\tif (request.reason?.length) {\n\t\t\theaders['X-Audit-Log-Reason'] = encodeURIComponent(request.reason);\n\t\t}\n\n\t\t// Format the full request URL (api base, optional version, endpoint, optional querystring)\n\t\tconst url = `${options.api}${request.versioned === false ? '' : `/v${options.version}`}${\n\t\t\trequest.fullRoute\n\t\t}${query}`;\n\n\t\tlet finalBody: RequestInit['body'];\n\t\tlet additionalHeaders: Record = {};\n\n\t\tif (request.files?.length) {\n\t\t\tconst formData = new FormData();\n\n\t\t\t// Attach all files to the request\n\t\t\tfor (const [index, file] of request.files.entries()) {\n\t\t\t\tconst fileKey = file.key ?? `files[${index}]`;\n\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/FormData/append#parameters\n\t\t\t\t// FormData.append only accepts a string or Blob.\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob#parameters\n\t\t\t\t// The Blob constructor accepts TypedArray/ArrayBuffer, strings, and Blobs.\n\t\t\t\tif (Buffer.isBuffer(file.data)) {\n\t\t\t\t\t// Try to infer the content type from the buffer if one isn't passed\n\t\t\t\t\tconst { fileTypeFromBuffer } = await getFileType();\n\t\t\t\t\tconst contentType = file.contentType ?? (await fileTypeFromBuffer(file.data))?.mime;\n\t\t\t\t\tformData.append(fileKey, new Blob([file.data], { type: contentType }), file.name);\n\t\t\t\t} else {\n\t\t\t\t\tformData.append(fileKey, new Blob([`${file.data}`], { type: file.contentType }), file.name);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If a JSON body was added as well, attach it to the form data, using payload_json unless otherwise specified\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t\tif (request.body != null) {\n\t\t\t\tif (request.appendToFormData) {\n\t\t\t\t\tfor (const [key, value] of Object.entries(request.body as Record)) {\n\t\t\t\t\t\tformData.append(key, value);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tformData.append('payload_json', JSON.stringify(request.body));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Set the final body to the form data\n\t\t\tfinalBody = formData;\n\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t} else if (request.body != null) {\n\t\t\tif (request.passThroughBody) {\n\t\t\t\tfinalBody = request.body as BodyInit;\n\t\t\t} else {\n\t\t\t\t// Stringify the JSON data\n\t\t\t\tfinalBody = JSON.stringify(request.body);\n\t\t\t\t// Set the additional headers to specify the content-type\n\t\t\t\tadditionalHeaders = { 'Content-Type': 'application/json' };\n\t\t\t}\n\t\t}\n\n\t\tfinalBody = await resolveBody(finalBody);\n\n\t\tconst fetchOptions: RequestOptions = {\n\t\t\theaders: { ...request.headers, ...additionalHeaders, ...headers } as Record,\n\t\t\tmethod: request.method.toUpperCase() as Dispatcher.HttpMethod,\n\t\t};\n\n\t\tif (finalBody !== undefined) {\n\t\t\tfetchOptions.body = finalBody as Exclude;\n\t\t}\n\n\t\t// Prioritize setting an agent per request, use the agent for this instance otherwise.\n\t\tfetchOptions.dispatcher = request.dispatcher ?? this.agent ?? undefined!;\n\n\t\treturn { url, fetchOptions };\n\t}\n\n\t/**\n\t * Stops the hash sweeping interval\n\t */\n\tpublic clearHashSweeper() {\n\t\tclearInterval(this.hashTimer);\n\t}\n\n\t/**\n\t * Stops the request handler sweeping interval\n\t */\n\tpublic clearHandlerSweeper() {\n\t\tclearInterval(this.handlerTimer);\n\t}\n\n\t/**\n\t * Generates route data for an endpoint:method\n\t *\n\t * @param endpoint - The raw endpoint to generalize\n\t * @param method - The HTTP method this endpoint is called without\n\t * @internal\n\t */\n\tprivate static generateRouteData(endpoint: RouteLike, method: RequestMethod): RouteData {\n\t\tconst majorIdMatch = /^\\/(?:channels|guilds|webhooks)\\/(\\d{16,19})/.exec(endpoint);\n\n\t\t// Get the major id for this route - global otherwise\n\t\tconst majorId = majorIdMatch?.[1] ?? 'global';\n\n\t\tconst baseRoute = endpoint\n\t\t\t// Strip out all ids\n\t\t\t.replaceAll(/\\d{16,19}/g, ':id')\n\t\t\t// Strip out reaction as they fall under the same bucket\n\t\t\t.replace(/\\/reactions\\/(.*)/, '/reactions/:reaction');\n\n\t\tlet exceptions = '';\n\n\t\t// Hard-Code Old Message Deletion Exception (2 week+ old messages are a different bucket)\n\t\t// https://github.com/discord/discord-api-docs/issues/1295\n\t\tif (method === RequestMethod.Delete && baseRoute === '/channels/:id/messages/:id') {\n\t\t\tconst id = /\\d{16,19}$/.exec(endpoint)![0]!;\n\t\t\tconst timestamp = DiscordSnowflake.timestampFrom(id);\n\t\t\tif (Date.now() - timestamp > 1_000 * 60 * 60 * 24 * 14) {\n\t\t\t\texceptions += '/Delete Old Message';\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tmajorParameter: majorId,\n\t\t\tbucketRoute: baseRoute + exceptions,\n\t\t\toriginal: endpoint,\n\t\t};\n\t}\n}\n","import { setTimeout, clearTimeout } from 'node:timers';\nimport { setTimeout as sleep } from 'node:timers/promises';\nimport { AsyncQueue } from '@sapphire/async-queue';\nimport { request, type Dispatcher } from 'undici';\nimport type { RateLimitData, RequestOptions } from '../REST';\nimport type { HandlerRequestData, RequestManager, RouteData } from '../RequestManager';\nimport { DiscordAPIError, type DiscordErrorData, type OAuthErrorData } from '../errors/DiscordAPIError.js';\nimport { HTTPError } from '../errors/HTTPError.js';\nimport { RateLimitError } from '../errors/RateLimitError.js';\nimport { RESTEvents } from '../utils/constants.js';\nimport { hasSublimit, parseHeader, parseResponse, shouldRetry } from '../utils/utils.js';\nimport type { IHandler } from './IHandler.js';\n\n/**\n * Invalid request limiting is done on a per-IP basis, not a per-token basis.\n * The best we can do is track invalid counts process-wide (on the theory that\n * users could have multiple bots run from one process) rather than per-bot.\n * Therefore, store these at file scope here rather than in the client's\n * RESTManager object.\n */\nlet invalidCount = 0;\nlet invalidCountResetTime: number | null = null;\n\nconst enum QueueType {\n\tStandard,\n\tSublimit,\n}\n\n/**\n * The structure used to handle requests for a given bucket\n */\nexport class SequentialHandler implements IHandler {\n\t/**\n\t * {@inheritDoc IHandler.id}\n\t */\n\tpublic readonly id: string;\n\n\t/**\n\t * The time this rate limit bucket will reset\n\t */\n\tprivate reset = -1;\n\n\t/**\n\t * The remaining requests that can be made before we are rate limited\n\t */\n\tprivate remaining = 1;\n\n\t/**\n\t * The total number of requests that can be made before we are rate limited\n\t */\n\tprivate limit = Number.POSITIVE_INFINITY;\n\n\t/**\n\t * The interface used to sequence async requests sequentially\n\t */\n\t#asyncQueue = new AsyncQueue();\n\n\t/**\n\t * The interface used to sequence sublimited async requests sequentially\n\t */\n\t#sublimitedQueue: AsyncQueue | null = null;\n\n\t/**\n\t * A promise wrapper for when the sublimited queue is finished being processed or null when not being processed\n\t */\n\t#sublimitPromise: { promise: Promise; resolve(): void } | null = null;\n\n\t/**\n\t * Whether the sublimit queue needs to be shifted in the finally block\n\t */\n\t#shiftSublimit = false;\n\n\t/**\n\t * @param manager - The request manager\n\t * @param hash - The hash that this RequestHandler handles\n\t * @param majorParameter - The major parameter for this handler\n\t */\n\tpublic constructor(\n\t\tprivate readonly manager: RequestManager,\n\t\tprivate readonly hash: string,\n\t\tprivate readonly majorParameter: string,\n\t) {\n\t\tthis.id = `${hash}:${majorParameter}`;\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.inactive}\n\t */\n\tpublic get inactive(): boolean {\n\t\treturn (\n\t\t\tthis.#asyncQueue.remaining === 0 &&\n\t\t\t(this.#sublimitedQueue === null || this.#sublimitedQueue.remaining === 0) &&\n\t\t\t!this.limited\n\t\t);\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited by the global limit\n\t */\n\tprivate get globalLimited(): boolean {\n\t\treturn this.manager.globalRemaining <= 0 && Date.now() < this.manager.globalReset;\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited by its limit\n\t */\n\tprivate get localLimited(): boolean {\n\t\treturn this.remaining <= 0 && Date.now() < this.reset;\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited\n\t */\n\tprivate get limited(): boolean {\n\t\treturn this.globalLimited || this.localLimited;\n\t}\n\n\t/**\n\t * The time until queued requests can continue\n\t */\n\tprivate get timeToReset(): number {\n\t\treturn this.reset + this.manager.options.offset - Date.now();\n\t}\n\n\t/**\n\t * Emits a debug message\n\t *\n\t * @param message - The message to debug\n\t */\n\tprivate debug(message: string) {\n\t\tthis.manager.emit(RESTEvents.Debug, `[REST ${this.id}] ${message}`);\n\t}\n\n\t/**\n\t * Delay all requests for the specified amount of time, handling global rate limits\n\t *\n\t * @param time - The amount of time to delay all requests for\n\t */\n\tprivate async globalDelayFor(time: number): Promise {\n\t\tawait sleep(time);\n\t\tthis.manager.globalDelay = null;\n\t}\n\n\t/*\n\t * Determines whether the request should be queued or whether a RateLimitError should be thrown\n\t */\n\tprivate async onRateLimit(rateLimitData: RateLimitData) {\n\t\tconst { options } = this.manager;\n\t\tif (!options.rejectOnRateLimit) return;\n\n\t\tconst shouldThrow =\n\t\t\ttypeof options.rejectOnRateLimit === 'function'\n\t\t\t\t? await options.rejectOnRateLimit(rateLimitData)\n\t\t\t\t: options.rejectOnRateLimit.some((route) => rateLimitData.route.startsWith(route.toLowerCase()));\n\t\tif (shouldThrow) {\n\t\t\tthrow new RateLimitError(rateLimitData);\n\t\t}\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.queueRequest}\n\t */\n\tpublic async queueRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t): Promise {\n\t\tlet queue = this.#asyncQueue;\n\t\tlet queueType = QueueType.Standard;\n\t\t// Separate sublimited requests when already sublimited\n\t\tif (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) {\n\t\t\tqueue = this.#sublimitedQueue!;\n\t\t\tqueueType = QueueType.Sublimit;\n\t\t}\n\n\t\t// Wait for any previous requests to be completed before this one is run\n\t\tawait queue.wait({ signal: requestData.signal });\n\t\t// This set handles retroactively sublimiting requests\n\t\tif (queueType === QueueType.Standard) {\n\t\t\tif (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) {\n\t\t\t\t/**\n\t\t\t\t * Remove the request from the standard queue, it should never be possible to get here while processing the\n\t\t\t\t * sublimit queue so there is no need to worry about shifting the wrong request\n\t\t\t\t */\n\t\t\t\tqueue = this.#sublimitedQueue!;\n\t\t\t\tconst wait = queue.wait();\n\t\t\t\tthis.#asyncQueue.shift();\n\t\t\t\tawait wait;\n\t\t\t} else if (this.#sublimitPromise) {\n\t\t\t\t// Stall requests while the sublimit queue gets processed\n\t\t\t\tawait this.#sublimitPromise.promise;\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t// Make the request, and return the results\n\t\t\treturn await this.runRequest(routeId, url, options, requestData);\n\t\t} finally {\n\t\t\t// Allow the next request to fire\n\t\t\tqueue.shift();\n\t\t\tif (this.#shiftSublimit) {\n\t\t\t\tthis.#shiftSublimit = false;\n\t\t\t\tthis.#sublimitedQueue?.shift();\n\t\t\t}\n\n\t\t\t// If this request is the last request in a sublimit\n\t\t\tif (this.#sublimitedQueue?.remaining === 0) {\n\t\t\t\tthis.#sublimitPromise?.resolve();\n\t\t\t\tthis.#sublimitedQueue = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * The method that actually makes the request to the api, and updates info about the bucket accordingly\n\t *\n\t * @param routeId - The generalized api route with literal ids for major parameters\n\t * @param url - The fully resolved url to make the request to\n\t * @param options - The fetch options needed to make the request\n\t * @param requestData - Extra data from the user's request needed for errors and additional processing\n\t * @param retries - The number of retries this request has already attempted (recursion)\n\t */\n\tprivate async runRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t\tretries = 0,\n\t): Promise {\n\t\t/*\n\t\t * After calculations have been done, pre-emptively stop further requests\n\t\t * Potentially loop until this task can run if e.g. the global rate limit is hit twice\n\t\t */\n\t\twhile (this.limited) {\n\t\t\tconst isGlobal = this.globalLimited;\n\t\t\tlet limit: number;\n\t\t\tlet timeout: number;\n\t\t\tlet delay: Promise;\n\n\t\t\tif (isGlobal) {\n\t\t\t\t// Set RateLimitData based on the global limit\n\t\t\t\tlimit = this.manager.options.globalRequestsPerSecond;\n\t\t\t\ttimeout = this.manager.globalReset + this.manager.options.offset - Date.now();\n\t\t\t\t// If this is the first task to reach the global timeout, set the global delay\n\t\t\t\tif (!this.manager.globalDelay) {\n\t\t\t\t\t// The global delay function clears the global delay state when it is resolved\n\t\t\t\t\tthis.manager.globalDelay = this.globalDelayFor(timeout);\n\t\t\t\t}\n\n\t\t\t\tdelay = this.manager.globalDelay;\n\t\t\t} else {\n\t\t\t\t// Set RateLimitData based on the route-specific limit\n\t\t\t\tlimit = this.limit;\n\t\t\t\ttimeout = this.timeToReset;\n\t\t\t\tdelay = sleep(timeout);\n\t\t\t}\n\n\t\t\tconst rateLimitData: RateLimitData = {\n\t\t\t\ttimeToReset: timeout,\n\t\t\t\tlimit,\n\t\t\t\tmethod: options.method ?? 'get',\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t};\n\t\t\t// Let library users know they have hit a rate limit\n\t\t\tthis.manager.emit(RESTEvents.RateLimited, rateLimitData);\n\t\t\t// Determine whether a RateLimitError should be thrown\n\t\t\tawait this.onRateLimit(rateLimitData);\n\t\t\t// When not erroring, emit debug for what is happening\n\t\t\tif (isGlobal) {\n\t\t\t\tthis.debug(`Global rate limit hit, blocking all requests for ${timeout}ms`);\n\t\t\t} else {\n\t\t\t\tthis.debug(`Waiting ${timeout}ms for rate limit to pass`);\n\t\t\t}\n\n\t\t\t// Wait the remaining time left before the rate limit resets\n\t\t\tawait delay;\n\t\t}\n\n\t\t// As the request goes out, update the global usage information\n\t\tif (!this.manager.globalReset || this.manager.globalReset < Date.now()) {\n\t\t\tthis.manager.globalReset = Date.now() + 1_000;\n\t\t\tthis.manager.globalRemaining = this.manager.options.globalRequestsPerSecond;\n\t\t}\n\n\t\tthis.manager.globalRemaining--;\n\n\t\tconst method = options.method ?? 'get';\n\n\t\tconst controller = new AbortController();\n\t\tconst timeout = setTimeout(() => controller.abort(), this.manager.options.timeout).unref();\n\t\tif (requestData.signal) {\n\t\t\t// The type polyfill is required because Node.js's types are incomplete.\n\t\t\tconst signal = requestData.signal as PolyFillAbortSignal;\n\t\t\t// If the user signal was aborted, abort the controller, else abort the local signal.\n\t\t\t// The reason why we don't re-use the user's signal, is because users may use the same signal for multiple\n\t\t\t// requests, and we do not want to cause unexpected side-effects.\n\t\t\tif (signal.aborted) controller.abort();\n\t\t\telse signal.addEventListener('abort', () => controller.abort());\n\t\t}\n\n\t\tlet res: Dispatcher.ResponseData;\n\t\ttry {\n\t\t\tres = await request(url, { ...options, signal: controller.signal });\n\t\t} catch (error: unknown) {\n\t\t\tif (!(error instanceof Error)) throw error;\n\t\t\t// Retry the specified number of times if needed\n\t\t\tif (shouldRetry(error) && retries !== this.manager.options.retries) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\treturn await this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t\t}\n\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tclearTimeout(timeout);\n\t\t}\n\n\t\tif (this.manager.listenerCount(RESTEvents.Response)) {\n\t\t\tthis.manager.emit(\n\t\t\t\tRESTEvents.Response,\n\t\t\t\t{\n\t\t\t\t\tmethod,\n\t\t\t\t\tpath: routeId.original,\n\t\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\t\toptions,\n\t\t\t\t\tdata: requestData,\n\t\t\t\t\tretries,\n\t\t\t\t},\n\t\t\t\t{ ...res },\n\t\t\t);\n\t\t}\n\n\t\tconst status = res.statusCode;\n\t\tlet retryAfter = 0;\n\n\t\tconst limit = parseHeader(res.headers['x-ratelimit-limit']);\n\t\tconst remaining = parseHeader(res.headers['x-ratelimit-remaining']);\n\t\tconst reset = parseHeader(res.headers['x-ratelimit-reset-after']);\n\t\tconst hash = parseHeader(res.headers['x-ratelimit-bucket']);\n\t\tconst retry = parseHeader(res.headers['retry-after']);\n\n\t\t// Update the total number of requests that can be made before the rate limit resets\n\t\tthis.limit = limit ? Number(limit) : Number.POSITIVE_INFINITY;\n\t\t// Update the number of remaining requests that can be made before the rate limit resets\n\t\tthis.remaining = remaining ? Number(remaining) : 1;\n\t\t// Update the time when this rate limit resets (reset-after is in seconds)\n\t\tthis.reset = reset ? Number(reset) * 1_000 + Date.now() + this.manager.options.offset : Date.now();\n\n\t\t// Amount of time in milliseconds until we should retry if rate limited (globally or otherwise)\n\t\tif (retry) retryAfter = Number(retry) * 1_000 + this.manager.options.offset;\n\n\t\t// Handle buckets via the hash header retroactively\n\t\tif (hash && hash !== this.hash) {\n\t\t\t// Let library users know when rate limit buckets have been updated\n\t\t\tthis.debug(['Received bucket hash update', ` Old Hash : ${this.hash}`, ` New Hash : ${hash}`].join('\\n'));\n\t\t\t// This queue will eventually be eliminated via attrition\n\t\t\tthis.manager.hashes.set(`${method}:${routeId.bucketRoute}`, { value: hash, lastAccess: Date.now() });\n\t\t} else if (hash) {\n\t\t\t// Handle the case where hash value doesn't change\n\t\t\t// Fetch the hash data from the manager\n\t\t\tconst hashData = this.manager.hashes.get(`${method}:${routeId.bucketRoute}`);\n\n\t\t\t// When fetched, update the last access of the hash\n\t\t\tif (hashData) {\n\t\t\t\thashData.lastAccess = Date.now();\n\t\t\t}\n\t\t}\n\n\t\t// Handle retryAfter, which means we have actually hit a rate limit\n\t\tlet sublimitTimeout: number | null = null;\n\t\tif (retryAfter > 0) {\n\t\t\tif (res.headers['x-ratelimit-global'] !== undefined) {\n\t\t\t\tthis.manager.globalRemaining = 0;\n\t\t\t\tthis.manager.globalReset = Date.now() + retryAfter;\n\t\t\t} else if (!this.localLimited) {\n\t\t\t\t/*\n\t\t\t\t * This is a sublimit (e.g. 2 channel name changes/10 minutes) since the headers don't indicate a\n\t\t\t\t * route-wide rate limit. Don't update remaining or reset to avoid rate limiting the whole\n\t\t\t\t * endpoint, just set a reset time on the request itself to avoid retrying too soon.\n\t\t\t\t */\n\t\t\t\tsublimitTimeout = retryAfter;\n\t\t\t}\n\t\t}\n\n\t\t// Count the invalid requests\n\t\tif (status === 401 || status === 403 || status === 429) {\n\t\t\tif (!invalidCountResetTime || invalidCountResetTime < Date.now()) {\n\t\t\t\tinvalidCountResetTime = Date.now() + 1_000 * 60 * 10;\n\t\t\t\tinvalidCount = 0;\n\t\t\t}\n\n\t\t\tinvalidCount++;\n\n\t\t\tconst emitInvalid =\n\t\t\t\tthis.manager.options.invalidRequestWarningInterval > 0 &&\n\t\t\t\tinvalidCount % this.manager.options.invalidRequestWarningInterval === 0;\n\t\t\tif (emitInvalid) {\n\t\t\t\t// Let library users know periodically about invalid requests\n\t\t\t\tthis.manager.emit(RESTEvents.InvalidRequestWarning, {\n\t\t\t\t\tcount: invalidCount,\n\t\t\t\t\tremainingTime: invalidCountResetTime - Date.now(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (status >= 200 && status < 300) {\n\t\t\treturn res;\n\t\t} else if (status === 429) {\n\t\t\t// A rate limit was hit - this may happen if the route isn't associated with an official bucket hash yet, or when first globally rate limited\n\t\t\tconst isGlobal = this.globalLimited;\n\t\t\tlet limit: number;\n\t\t\tlet timeout: number;\n\n\t\t\tif (isGlobal) {\n\t\t\t\t// Set RateLimitData based on the global limit\n\t\t\t\tlimit = this.manager.options.globalRequestsPerSecond;\n\t\t\t\ttimeout = this.manager.globalReset + this.manager.options.offset - Date.now();\n\t\t\t} else {\n\t\t\t\t// Set RateLimitData based on the route-specific limit\n\t\t\t\tlimit = this.limit;\n\t\t\t\ttimeout = this.timeToReset;\n\t\t\t}\n\n\t\t\tawait this.onRateLimit({\n\t\t\t\ttimeToReset: timeout,\n\t\t\t\tlimit,\n\t\t\t\tmethod,\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t});\n\t\t\tthis.debug(\n\t\t\t\t[\n\t\t\t\t\t'Encountered unexpected 429 rate limit',\n\t\t\t\t\t` Global : ${isGlobal.toString()}`,\n\t\t\t\t\t` Method : ${method}`,\n\t\t\t\t\t` URL : ${url}`,\n\t\t\t\t\t` Bucket : ${routeId.bucketRoute}`,\n\t\t\t\t\t` Major parameter: ${routeId.majorParameter}`,\n\t\t\t\t\t` Hash : ${this.hash}`,\n\t\t\t\t\t` Limit : ${limit}`,\n\t\t\t\t\t` Retry After : ${retryAfter}ms`,\n\t\t\t\t\t` Sublimit : ${sublimitTimeout ? `${sublimitTimeout}ms` : 'None'}`,\n\t\t\t\t].join('\\n'),\n\t\t\t);\n\t\t\t// If caused by a sublimit, wait it out here so other requests on the route can be handled\n\t\t\tif (sublimitTimeout) {\n\t\t\t\t// Normally the sublimit queue will not exist, however, if a sublimit is hit while in the sublimit queue, it will\n\t\t\t\tconst firstSublimit = !this.#sublimitedQueue;\n\t\t\t\tif (firstSublimit) {\n\t\t\t\t\tthis.#sublimitedQueue = new AsyncQueue();\n\t\t\t\t\tvoid this.#sublimitedQueue.wait();\n\t\t\t\t\tthis.#asyncQueue.shift();\n\t\t\t\t}\n\n\t\t\t\tthis.#sublimitPromise?.resolve();\n\t\t\t\tthis.#sublimitPromise = null;\n\t\t\t\tawait sleep(sublimitTimeout);\n\t\t\t\tlet resolve: () => void;\n\t\t\t\t// eslint-disable-next-line promise/param-names, no-promise-executor-return\n\t\t\t\tconst promise = new Promise((res) => (resolve = res));\n\t\t\t\tthis.#sublimitPromise = { promise, resolve: resolve! };\n\t\t\t\tif (firstSublimit) {\n\t\t\t\t\t// Re-queue this request so it can be shifted by the finally\n\t\t\t\t\tawait this.#asyncQueue.wait();\n\t\t\t\t\tthis.#shiftSublimit = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Since this is not a server side issue, the next request should pass, so we don't bump the retries counter\n\t\t\treturn this.runRequest(routeId, url, options, requestData, retries);\n\t\t} else if (status >= 500 && status < 600) {\n\t\t\t// Retry the specified number of times for possible server side issues\n\t\t\tif (retries !== this.manager.options.retries) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t\t}\n\n\t\t\t// We are out of retries, throw an error\n\t\t\tthrow new HTTPError(status, method, url, requestData);\n\t\t} else {\n\t\t\t// Handle possible malformed requests\n\t\t\tif (status >= 400 && status < 500) {\n\t\t\t\t// If we receive this status code, it means the token we had is no longer valid.\n\t\t\t\tif (status === 401 && requestData.auth) {\n\t\t\t\t\tthis.manager.setToken(null!);\n\t\t\t\t}\n\n\t\t\t\t// The request will not succeed for some reason, parse the error returned from the api\n\t\t\t\tconst data = (await parseResponse(res)) as DiscordErrorData | OAuthErrorData;\n\t\t\t\t// throw the API error\n\t\t\t\tthrow new DiscordAPIError(data, 'code' in data ? data.code : data.error, status, method, url, requestData);\n\t\t\t}\n\n\t\t\treturn res;\n\t\t}\n\t}\n}\n\ninterface PolyFillAbortSignal {\n\treadonly aborted: boolean;\n\taddEventListener(type: 'abort', listener: () => void): void;\n\tremoveEventListener(type: 'abort', listener: () => void): void;\n}\n","import { Blob, Buffer } from 'node:buffer';\nimport { URLSearchParams } from 'node:url';\nimport { types } from 'node:util';\nimport type { RESTPatchAPIChannelJSONBody } from 'discord-api-types/v10';\nimport { FormData, type Dispatcher, type RequestInit } from 'undici';\nimport type { RequestOptions } from '../REST.js';\nimport { RequestMethod } from '../RequestManager.js';\n\nexport function parseHeader(header: string[] | string | undefined): string | undefined {\n\tif (header === undefined || typeof header === 'string') {\n\t\treturn header;\n\t}\n\n\treturn header.join(';');\n}\n\nfunction serializeSearchParam(value: unknown): string | null {\n\tswitch (typeof value) {\n\t\tcase 'string':\n\t\t\treturn value;\n\t\tcase 'number':\n\t\tcase 'bigint':\n\t\tcase 'boolean':\n\t\t\treturn value.toString();\n\t\tcase 'object':\n\t\t\tif (value === null) return null;\n\t\t\tif (value instanceof Date) {\n\t\t\t\treturn Number.isNaN(value.getTime()) ? null : value.toISOString();\n\t\t\t}\n\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-base-to-string\n\t\t\tif (typeof value.toString === 'function' && value.toString !== Object.prototype.toString) return value.toString();\n\t\t\treturn null;\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/**\n * Creates and populates an URLSearchParams instance from an object, stripping\n * out null and undefined values, while also coercing non-strings to strings.\n *\n * @param options - The options to use\n * @returns A populated URLSearchParams instance\n */\nexport function makeURLSearchParams(options?: Readonly) {\n\tconst params = new URLSearchParams();\n\tif (!options) return params;\n\n\tfor (const [key, value] of Object.entries(options)) {\n\t\tconst serialized = serializeSearchParam(value);\n\t\tif (serialized !== null) params.append(key, serialized);\n\t}\n\n\treturn params;\n}\n\n/**\n * Converts the response to usable data\n *\n * @param res - The fetch response\n */\nexport async function parseResponse(res: Dispatcher.ResponseData): Promise {\n\tconst header = parseHeader(res.headers['content-type']);\n\tif (header?.startsWith('application/json')) {\n\t\treturn res.body.json();\n\t}\n\n\treturn res.body.arrayBuffer();\n}\n\n/**\n * Check whether a request falls under a sublimit\n *\n * @param bucketRoute - The buckets route identifier\n * @param body - The options provided as JSON data\n * @param method - The HTTP method that will be used to make the request\n * @returns Whether the request falls under a sublimit\n */\nexport function hasSublimit(bucketRoute: string, body?: unknown, method?: string): boolean {\n\t// TODO: Update for new sublimits\n\t// Currently known sublimits:\n\t// Editing channel `name` or `topic`\n\tif (bucketRoute === '/channels/:id') {\n\t\tif (typeof body !== 'object' || body === null) return false;\n\t\t// This should never be a POST body, but just in case\n\t\tif (method !== RequestMethod.Patch) return false;\n\t\tconst castedBody = body as RESTPatchAPIChannelJSONBody;\n\t\treturn ['name', 'topic'].some((key) => Reflect.has(castedBody, key));\n\t}\n\n\t// If we are checking if a request has a sublimit on a route not checked above, sublimit all requests to avoid a flood of 429s\n\treturn true;\n}\n\nexport async function resolveBody(body: RequestInit['body']): Promise {\n\t// eslint-disable-next-line no-eq-null, eqeqeq\n\tif (body == null) {\n\t\treturn null;\n\t} else if (typeof body === 'string') {\n\t\treturn body;\n\t} else if (types.isUint8Array(body)) {\n\t\treturn body;\n\t} else if (types.isArrayBuffer(body)) {\n\t\treturn new Uint8Array(body);\n\t} else if (body instanceof URLSearchParams) {\n\t\treturn body.toString();\n\t} else if (body instanceof DataView) {\n\t\treturn new Uint8Array(body.buffer);\n\t} else if (body instanceof Blob) {\n\t\treturn new Uint8Array(await body.arrayBuffer());\n\t} else if (body instanceof FormData) {\n\t\treturn body;\n\t} else if ((body as Iterable)[Symbol.iterator]) {\n\t\tconst chunks = [...(body as Iterable)];\n\t\tconst length = chunks.reduce((a, b) => a + b.length, 0);\n\n\t\tconst uint8 = new Uint8Array(length);\n\t\tlet lengthUsed = 0;\n\n\t\treturn chunks.reduce((a, b) => {\n\t\t\ta.set(b, lengthUsed);\n\t\t\tlengthUsed += b.length;\n\t\t\treturn a;\n\t\t}, uint8);\n\t} else if ((body as AsyncIterable)[Symbol.asyncIterator]) {\n\t\tconst chunks: Uint8Array[] = [];\n\n\t\tfor await (const chunk of body as AsyncIterable) {\n\t\t\tchunks.push(chunk);\n\t\t}\n\n\t\treturn Buffer.concat(chunks);\n\t}\n\n\tthrow new TypeError(`Unable to resolve body.`);\n}\n\n/**\n * Check whether an error indicates that a retry can be attempted\n *\n * @param error - The error thrown by the network request\n * @returns Whether the error indicates a retry should be attempted\n */\nexport function shouldRetry(error: Error | NodeJS.ErrnoException) {\n\t// Retry for possible timed out requests\n\tif (error.name === 'AbortError') return true;\n\t// Downlevel ECONNRESET to retry as it may be recoverable\n\treturn ('code' in error && error.code === 'ECONNRESET') || error.message.includes('ECONNRESET');\n}\n","import { EventEmitter } from 'node:events';\nimport type { Collection } from '@discordjs/collection';\nimport type { request, Dispatcher } from 'undici';\nimport { CDN } from './CDN.js';\nimport {\n\tRequestManager,\n\tRequestMethod,\n\ttype HashData,\n\ttype HandlerRequestData,\n\ttype InternalRequest,\n\ttype RequestData,\n\ttype RouteLike,\n} from './RequestManager.js';\nimport type { IHandler } from './handlers/IHandler.js';\nimport { DefaultRestOptions, RESTEvents } from './utils/constants.js';\nimport { parseResponse } from './utils/utils.js';\n\n/**\n * Options to be passed when creating the REST instance\n */\nexport interface RESTOptions {\n\t/**\n\t * The agent to set globally\n\t */\n\tagent: Dispatcher;\n\t/**\n\t * The base api path, without version\n\t *\n\t * @defaultValue `'https://discord.com/api'`\n\t */\n\tapi: string;\n\t/**\n\t * The authorization prefix to use for requests, useful if you want to use\n\t * bearer tokens\n\t *\n\t * @defaultValue `'Bot'`\n\t */\n\tauthPrefix: 'Bearer' | 'Bot';\n\t/**\n\t * The cdn path\n\t *\n\t * @defaultValue 'https://cdn.discordapp.com'\n\t */\n\tcdn: string;\n\t/**\n\t * How many requests to allow sending per second (Infinity for unlimited, 50 for the standard global limit used by Discord)\n\t *\n\t * @defaultValue `50`\n\t */\n\tglobalRequestsPerSecond: number;\n\t/**\n\t * The amount of time in milliseconds that passes between each hash sweep. (defaults to 1h)\n\t *\n\t * @defaultValue `3_600_000`\n\t */\n\thandlerSweepInterval: number;\n\t/**\n\t * The maximum amount of time a hash can exist in milliseconds without being hit with a request (defaults to 24h)\n\t *\n\t * @defaultValue `86_400_000`\n\t */\n\thashLifetime: number;\n\t/**\n\t * The amount of time in milliseconds that passes between each hash sweep. (defaults to 4h)\n\t *\n\t * @defaultValue `14_400_000`\n\t */\n\thashSweepInterval: number;\n\t/**\n\t * Additional headers to send for all API requests\n\t *\n\t * @defaultValue `{}`\n\t */\n\theaders: Record;\n\t/**\n\t * The number of invalid REST requests (those that return 401, 403, or 429) in a 10 minute window between emitted warnings (0 for no warnings).\n\t * That is, if set to 500, warnings will be emitted at invalid request number 500, 1000, 1500, and so on.\n\t *\n\t * @defaultValue `0`\n\t */\n\tinvalidRequestWarningInterval: number;\n\t/**\n\t * The extra offset to add to rate limits in milliseconds\n\t *\n\t * @defaultValue `50`\n\t */\n\toffset: number;\n\t/**\n\t * Determines how rate limiting and pre-emptive throttling should be handled.\n\t * When an array of strings, each element is treated as a prefix for the request route\n\t * (e.g. `/channels` to match any route starting with `/channels` such as `/channels/:id/messages`)\n\t * for which to throw {@link RateLimitError}s. All other request routes will be queued normally\n\t *\n\t * @defaultValue `null`\n\t */\n\trejectOnRateLimit: RateLimitQueueFilter | string[] | null;\n\t/**\n\t * The number of retries for errors with the 500 code, or errors\n\t * that timeout\n\t *\n\t * @defaultValue `3`\n\t */\n\tretries: number;\n\t/**\n\t * The time to wait in milliseconds before a request is aborted\n\t *\n\t * @defaultValue `15_000`\n\t */\n\ttimeout: number;\n\t/**\n\t * Extra information to add to the user agent\n\t *\n\t * @defaultValue `Node.js ${process.version}`\n\t */\n\tuserAgentAppendix: string;\n\t/**\n\t * The version of the API to use\n\t *\n\t * @defaultValue `'10'`\n\t */\n\tversion: string;\n}\n\n/**\n * Data emitted on `RESTEvents.RateLimited`\n */\nexport interface RateLimitData {\n\t/**\n\t * Whether the rate limit that was reached was the global limit\n\t */\n\tglobal: boolean;\n\t/**\n\t * The bucket hash for this request\n\t */\n\thash: string;\n\t/**\n\t * The amount of requests we can perform before locking requests\n\t */\n\tlimit: number;\n\t/**\n\t * The major parameter of the route\n\t *\n\t * For example, in `/channels/x`, this will be `x`.\n\t * If there is no major parameter (e.g: `/bot/gateway`) this will be `global`.\n\t */\n\tmajorParameter: string;\n\t/**\n\t * The HTTP method being performed\n\t */\n\tmethod: string;\n\t/**\n\t * The route being hit in this request\n\t */\n\troute: string;\n\t/**\n\t * The time, in milliseconds, until the request-lock is reset\n\t */\n\ttimeToReset: number;\n\t/**\n\t * The full URL for this request\n\t */\n\turl: string;\n}\n\n/**\n * A function that determines whether the rate limit hit should throw an Error\n */\nexport type RateLimitQueueFilter = (rateLimitData: RateLimitData) => Promise | boolean;\n\nexport interface APIRequest {\n\t/**\n\t * The data that was used to form the body of this request\n\t */\n\tdata: HandlerRequestData;\n\t/**\n\t * The HTTP method used in this request\n\t */\n\tmethod: string;\n\t/**\n\t * Additional HTTP options for this request\n\t */\n\toptions: RequestOptions;\n\t/**\n\t * The full path used to make the request\n\t */\n\tpath: RouteLike;\n\t/**\n\t * The number of times this request has been attempted\n\t */\n\tretries: number;\n\t/**\n\t * The API route identifying the ratelimit for this request\n\t */\n\troute: string;\n}\n\nexport interface InvalidRequestWarningData {\n\t/**\n\t * Number of invalid requests that have been made in the window\n\t */\n\tcount: number;\n\t/**\n\t * Time in milliseconds remaining before the count resets\n\t */\n\tremainingTime: number;\n}\n\nexport interface RestEvents {\n\thandlerSweep: [sweptHandlers: Collection];\n\thashSweep: [sweptHashes: Collection];\n\tinvalidRequestWarning: [invalidRequestInfo: InvalidRequestWarningData];\n\tnewListener: [name: string, listener: (...args: any) => void];\n\trateLimited: [rateLimitInfo: RateLimitData];\n\tremoveListener: [name: string, listener: (...args: any) => void];\n\tresponse: [request: APIRequest, response: Dispatcher.ResponseData];\n\trestDebug: [info: string];\n}\n\nexport interface REST {\n\temit: ((event: K, ...args: RestEvents[K]) => boolean) &\n\t\t((event: Exclude, ...args: any[]) => boolean);\n\n\toff: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\ton: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tonce: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tremoveAllListeners: ((event?: K) => this) &\n\t\t((event?: Exclude) => this);\n}\n\nexport type RequestOptions = Exclude[1], undefined>;\n\nexport class REST extends EventEmitter {\n\tpublic readonly cdn: CDN;\n\n\tpublic readonly requestManager: RequestManager;\n\n\tpublic constructor(options: Partial = {}) {\n\t\tsuper();\n\t\tthis.cdn = new CDN(options.cdn ?? DefaultRestOptions.cdn);\n\t\tthis.requestManager = new RequestManager(options)\n\t\t\t.on(RESTEvents.Debug, this.emit.bind(this, RESTEvents.Debug))\n\t\t\t.on(RESTEvents.RateLimited, this.emit.bind(this, RESTEvents.RateLimited))\n\t\t\t.on(RESTEvents.InvalidRequestWarning, this.emit.bind(this, RESTEvents.InvalidRequestWarning))\n\t\t\t.on(RESTEvents.HashSweep, this.emit.bind(this, RESTEvents.HashSweep));\n\n\t\tthis.on('newListener', (name, listener) => {\n\t\t\tif (name === RESTEvents.Response) this.requestManager.on(name, listener);\n\t\t});\n\t\tthis.on('removeListener', (name, listener) => {\n\t\t\tif (name === RESTEvents.Response) this.requestManager.off(name, listener);\n\t\t});\n\t}\n\n\t/**\n\t * Gets the agent set for this instance\n\t */\n\tpublic getAgent() {\n\t\treturn this.requestManager.agent;\n\t}\n\n\t/**\n\t * Sets the default agent to use for requests performed by this instance\n\t *\n\t * @param agent - Sets the agent to use\n\t */\n\tpublic setAgent(agent: Dispatcher) {\n\t\tthis.requestManager.setAgent(agent);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the authorization token that should be used for requests\n\t *\n\t * @param token - The authorization token to use\n\t */\n\tpublic setToken(token: string) {\n\t\tthis.requestManager.setToken(token);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a get request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async get(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Get });\n\t}\n\n\t/**\n\t * Runs a delete request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async delete(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Delete });\n\t}\n\n\t/**\n\t * Runs a post request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async post(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Post });\n\t}\n\n\t/**\n\t * Runs a put request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async put(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Put });\n\t}\n\n\t/**\n\t * Runs a patch request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async patch(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Patch });\n\t}\n\n\t/**\n\t * Runs a request from the api\n\t *\n\t * @param options - Request options\n\t */\n\tpublic async request(options: InternalRequest) {\n\t\tconst response = await this.raw(options);\n\t\treturn parseResponse(response);\n\t}\n\n\t/**\n\t * Runs a request from the API, yielding the raw Response object\n\t *\n\t * @param options - Request options\n\t */\n\tpublic async raw(options: InternalRequest) {\n\t\treturn this.requestManager.queueRequest(options);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,sBAAoB;;;ACDpB,0BAAoB;AACpB,iBAA2B;AAC3B,oBAAsB;AAGf,IAAM,mBAAmB;AAEzB,IAAM,qBAAqB;AAAA,EACjC,IAAI,QAAQ;AACX,WAAO,IAAI,oBAAM;AAAA,MAChB,SAAS;AAAA,QACR,SAAS;AAAA,MACV;AAAA,IACD,CAAC;AAAA,EACF;AAAA,EACA,KAAK;AAAA,EACL,YAAY;AAAA,EACZ,KAAK;AAAA,EACL,SAAS,CAAC;AAAA,EACV,+BAA+B;AAAA,EAC/B,yBAAyB;AAAA,EACzB,QAAQ;AAAA,EACR,mBAAmB;AAAA,EACnB,SAAS;AAAA,EACT,SAAS;AAAA,EACT,mBAAmB,WAAW,oBAAAA,QAAQ;AAAA,EACtC,SAAS;AAAA,EACT,mBAAmB;AAAA,EACnB,cAAc;AAAA,EACd,sBAAsB;AACvB;AAKO,IAAW,aAAX,kBAAWC,gBAAX;AACN,EAAAA,YAAA,WAAQ;AACR,EAAAA,YAAA,kBAAe;AACf,EAAAA,YAAA,eAAY;AACZ,EAAAA,YAAA,2BAAwB;AACxB,EAAAA,YAAA,iBAAc;AACd,EAAAA,YAAA,cAAW;AANM,SAAAA;AAAA,GAAA;AASX,IAAM,qBAAqB,CAAC,QAAQ,OAA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AAS,WAAW,wBAA0B,CAAC;AAAA,EACzE;AAAA,EAQA,MAAa,OAAO,WAAsB,UAAuB,CAAC,GAAG;AACpE,WAAO,KAAK,QAAQ,EAAE,GAAG,SAAS,WAAW,8BAA6B,CAAC;AAAA,EAC5E;AAAA,EAQA,MAAa,KAAK,WAAsB,UAAuB,CAAC,GAAG;AAClE,WAAO,KAAK,QAAQ,EAAE,GAAG,SAAS,WAAW,0BAA2B,CAAC;AAAA,EAC1E;AAAA,EAQA,MAAa,IAAI,WAAsB,UAAuB,CAAC,GAAG;AACjE,WAAO,KAAK,QAAQ,EAAE,GAAG,SAAS,WAAW,wBAA0B,CAAC;AAAA,EACzE;AAAA,EAQA,MAAa,MAAM,WAAsB,UAAuB,CAAC,GAAG;AACnE,WAAO,KAAK,QAAQ,EAAE,GAAG,SAAS,WAAW,4BAA4B,CAAC;AAAA,EAC3E;AAAA,EAOA,MAAa,QAAQ,SAA0B;AAC9C,UAAM,WAAW,MAAM,KAAK,IAAI,OAAO;AACvC,WAAO,cAAc,QAAQ;AAAA,EAC9B;AAAA,EAOA,MAAa,IAAI,SAA0B;AAC1C,WAAO,KAAK,eAAe,aAAa,OAAO;AAAA,EAChD;AACD;AArHa;;;AT9NN,IAAM,UAAkB;","names":["process","RESTEvents","import_node_buffer","import_node_timers","import_undici","import_undici","import_node_url","import_undici","sleep","limit","timeout","res","RequestMethod","request","import_node_events"]} \ No newline at end of file +{"version":3,"sources":["../src/index.ts","../src/lib/CDN.ts","../src/lib/utils/constants.ts","../src/lib/errors/DiscordAPIError.ts","../src/lib/errors/HTTPError.ts","../src/lib/errors/RateLimitError.ts","../src/lib/RequestManager.ts","../src/lib/handlers/BurstHandler.ts","../src/lib/utils/utils.ts","../src/lib/handlers/Shared.ts","../src/lib/handlers/SequentialHandler.ts","../src/lib/REST.ts"],"sourcesContent":["export * from './lib/CDN.js';\nexport * from './lib/errors/DiscordAPIError.js';\nexport * from './lib/errors/HTTPError.js';\nexport * from './lib/errors/RateLimitError.js';\nexport * from './lib/RequestManager.js';\nexport * from './lib/REST.js';\nexport * from './lib/utils/constants.js';\nexport { makeURLSearchParams, parseResponse } from './lib/utils/utils.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/rest/#readme | @discordjs/rest} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\nexport const version = '1.7.1' as string;\n","/* eslint-disable jsdoc/check-param-names */\nimport { URL } from 'node:url';\nimport {\n\tALLOWED_EXTENSIONS,\n\tALLOWED_SIZES,\n\tALLOWED_STICKER_EXTENSIONS,\n\tDefaultRestOptions,\n\ttype ImageExtension,\n\ttype ImageSize,\n\ttype StickerExtension,\n} from './utils/constants.js';\n\n/**\n * The options used for image URLs\n */\nexport interface BaseImageURLOptions {\n\t/**\n\t * The extension to use for the image URL\n\t *\n\t * @defaultValue `'webp'`\n\t */\n\textension?: ImageExtension;\n\t/**\n\t * The size specified in the image URL\n\t */\n\tsize?: ImageSize;\n}\n\n/**\n * The options used for image URLs with animated content\n */\nexport interface ImageURLOptions extends BaseImageURLOptions {\n\t/**\n\t * Whether or not to prefer the static version of an image asset.\n\t */\n\tforceStatic?: boolean;\n}\n\n/**\n * The options to use when making a CDN URL\n */\nexport interface MakeURLOptions {\n\t/**\n\t * The allowed extensions that can be used\n\t */\n\tallowedExtensions?: readonly string[];\n\t/**\n\t * The extension to use for the image URL\n\t *\n\t * @defaultValue `'webp'`\n\t */\n\textension?: string | undefined;\n\t/**\n\t * The size specified in the image URL\n\t */\n\tsize?: ImageSize;\n}\n\n/**\n * The CDN link builder\n */\nexport class CDN {\n\tpublic constructor(private readonly base: string = DefaultRestOptions.cdn) {}\n\n\t/**\n\t * Generates an app asset URL for a client's asset.\n\t *\n\t * @param clientId - The client id that has the asset\n\t * @param assetHash - The hash provided by Discord for this asset\n\t * @param options - Optional options for the asset\n\t */\n\tpublic appAsset(clientId: string, assetHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-assets/${clientId}/${assetHash}`, options);\n\t}\n\n\t/**\n\t * Generates an app icon URL for a client's icon.\n\t *\n\t * @param clientId - The client id that has the icon\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic appIcon(clientId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-icons/${clientId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates an avatar URL, e.g. for a user or a webhook.\n\t *\n\t * @param id - The id that has the icon\n\t * @param avatarHash - The hash provided by Discord for this avatar\n\t * @param options - Optional options for the avatar\n\t */\n\tpublic avatar(id: string, avatarHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/avatars/${id}/${avatarHash}`, avatarHash, options);\n\t}\n\n\t/**\n\t * Generates a banner URL, e.g. for a user or a guild.\n\t *\n\t * @param id - The id that has the banner splash\n\t * @param bannerHash - The hash provided by Discord for this banner\n\t * @param options - Optional options for the banner\n\t */\n\tpublic banner(id: string, bannerHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/banners/${id}/${bannerHash}`, bannerHash, options);\n\t}\n\n\t/**\n\t * Generates an icon URL for a channel, e.g. a group DM.\n\t *\n\t * @param channelId - The channel id that has the icon\n\t * @param iconHash - The hash provided by Discord for this channel\n\t * @param options - Optional options for the icon\n\t */\n\tpublic channelIcon(channelId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/channel-icons/${channelId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates the default avatar URL for a discriminator.\n\t *\n\t * @param discriminator - The discriminator modulo 5\n\t */\n\tpublic defaultAvatar(discriminator: number): string {\n\t\treturn this.makeURL(`/embed/avatars/${discriminator}`, { extension: 'png' });\n\t}\n\n\t/**\n\t * Generates a discovery splash URL for a guild's discovery splash.\n\t *\n\t * @param guildId - The guild id that has the discovery splash\n\t * @param splashHash - The hash provided by Discord for this splash\n\t * @param options - Optional options for the splash\n\t */\n\tpublic discoverySplash(guildId: string, splashHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/discovery-splashes/${guildId}/${splashHash}`, options);\n\t}\n\n\t/**\n\t * Generates an emoji's URL for an emoji.\n\t *\n\t * @param emojiId - The emoji id\n\t * @param extension - The extension of the emoji\n\t */\n\tpublic emoji(emojiId: string, extension?: ImageExtension): string {\n\t\treturn this.makeURL(`/emojis/${emojiId}`, { extension });\n\t}\n\n\t/**\n\t * Generates a guild member avatar URL.\n\t *\n\t * @param guildId - The id of the guild\n\t * @param userId - The id of the user\n\t * @param avatarHash - The hash provided by Discord for this avatar\n\t * @param options - Optional options for the avatar\n\t */\n\tpublic guildMemberAvatar(\n\t\tguildId: string,\n\t\tuserId: string,\n\t\tavatarHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/avatars/${avatarHash}`, avatarHash, options);\n\t}\n\n\t/**\n\t * Generates a guild member banner URL.\n\t *\n\t * @param guildId - The id of the guild\n\t * @param userId - The id of the user\n\t * @param bannerHash - The hash provided by Discord for this banner\n\t * @param options - Optional options for the banner\n\t */\n\tpublic guildMemberBanner(\n\t\tguildId: string,\n\t\tuserId: string,\n\t\tbannerHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/banner`, bannerHash, options);\n\t}\n\n\t/**\n\t * Generates an icon URL, e.g. for a guild.\n\t *\n\t * @param id - The id that has the icon splash\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic icon(id: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/icons/${id}/${iconHash}`, iconHash, options);\n\t}\n\n\t/**\n\t * Generates a URL for the icon of a role\n\t *\n\t * @param roleId - The id of the role that has the icon\n\t * @param roleIconHash - The hash provided by Discord for this role icon\n\t * @param options - Optional options for the role icon\n\t */\n\tpublic roleIcon(roleId: string, roleIconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/role-icons/${roleId}/${roleIconHash}`, options);\n\t}\n\n\t/**\n\t * Generates a guild invite splash URL for a guild's invite splash.\n\t *\n\t * @param guildId - The guild id that has the invite splash\n\t * @param splashHash - The hash provided by Discord for this splash\n\t * @param options - Optional options for the splash\n\t */\n\tpublic splash(guildId: string, splashHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/splashes/${guildId}/${splashHash}`, options);\n\t}\n\n\t/**\n\t * Generates a sticker URL.\n\t *\n\t * @param stickerId - The sticker id\n\t * @param extension - The extension of the sticker\n\t * @privateRemarks\n\t * Stickers cannot have a `.webp` extension, so we default to a `.png`\n\t */\n\tpublic sticker(stickerId: string, extension: StickerExtension = 'png'): string {\n\t\treturn this.makeURL(`/stickers/${stickerId}`, { allowedExtensions: ALLOWED_STICKER_EXTENSIONS, extension });\n\t}\n\n\t/**\n\t * Generates a sticker pack banner URL.\n\t *\n\t * @param bannerId - The banner id\n\t * @param options - Optional options for the banner\n\t */\n\tpublic stickerPackBanner(bannerId: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-assets/710982414301790216/store/${bannerId}`, options);\n\t}\n\n\t/**\n\t * Generates a team icon URL for a team's icon.\n\t *\n\t * @param teamId - The team id that has the icon\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic teamIcon(teamId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/team-icons/${teamId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates a cover image for a guild scheduled event.\n\t *\n\t * @param scheduledEventId - The scheduled event id\n\t * @param coverHash - The hash provided by discord for this cover image\n\t * @param options - Optional options for the cover image\n\t */\n\tpublic guildScheduledEventCover(\n\t\tscheduledEventId: string,\n\t\tcoverHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.makeURL(`/guild-events/${scheduledEventId}/${coverHash}`, options);\n\t}\n\n\t/**\n\t * Constructs the URL for the resource, checking whether or not `hash` starts with `a_` if `dynamic` is set to `true`.\n\t *\n\t * @param route - The base cdn route\n\t * @param hash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the link\n\t */\n\tprivate dynamicMakeURL(\n\t\troute: string,\n\t\thash: string,\n\t\t{ forceStatic = false, ...options }: Readonly = {},\n\t): string {\n\t\treturn this.makeURL(route, !forceStatic && hash.startsWith('a_') ? { ...options, extension: 'gif' } : options);\n\t}\n\n\t/**\n\t * Constructs the URL for the resource\n\t *\n\t * @param route - The base cdn route\n\t * @param options - The extension/size options for the link\n\t */\n\tprivate makeURL(\n\t\troute: string,\n\t\t{ allowedExtensions = ALLOWED_EXTENSIONS, extension = 'webp', size }: Readonly = {},\n\t): string {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\textension = String(extension).toLowerCase();\n\n\t\tif (!allowedExtensions.includes(extension)) {\n\t\t\tthrow new RangeError(`Invalid extension provided: ${extension}\\nMust be one of: ${allowedExtensions.join(', ')}`);\n\t\t}\n\n\t\tif (size && !ALLOWED_SIZES.includes(size)) {\n\t\t\tthrow new RangeError(`Invalid size provided: ${size}\\nMust be one of: ${ALLOWED_SIZES.join(', ')}`);\n\t\t}\n\n\t\tconst url = new URL(`${this.base}${route}.${extension}`);\n\n\t\tif (size) {\n\t\t\turl.searchParams.set('size', String(size));\n\t\t}\n\n\t\treturn url.toString();\n\t}\n}\n","import process from 'node:process';\nimport { APIVersion } from 'discord-api-types/v10';\nimport { Agent } from 'undici';\nimport type { RESTOptions } from '../REST.js';\n\nexport const DefaultUserAgent =\n\t`DiscordBot (https://discord.js.org, 1.7.1)` as `DiscordBot (https://discord.js.org, ${string})`;\n\n/**\n * The default string to append onto the user agent.\n */\nexport const DefaultUserAgentAppendix = process.release?.name === 'node' ? `Node.js/${process.version}` : '';\n\nexport const DefaultRestOptions = {\n\tget agent() {\n\t\treturn new Agent({\n\t\t\tconnect: {\n\t\t\t\ttimeout: 30_000,\n\t\t\t},\n\t\t});\n\t},\n\tapi: 'https://discord.com/api',\n\tauthPrefix: 'Bot',\n\tcdn: 'https://cdn.discordapp.com',\n\theaders: {},\n\tinvalidRequestWarningInterval: 0,\n\tglobalRequestsPerSecond: 50,\n\toffset: 50,\n\trejectOnRateLimit: null,\n\tretries: 3,\n\ttimeout: 15_000,\n\tuserAgentAppendix: DefaultUserAgentAppendix,\n\tversion: APIVersion,\n\thashSweepInterval: 14_400_000, // 4 Hours\n\thashLifetime: 86_400_000, // 24 Hours\n\thandlerSweepInterval: 3_600_000, // 1 Hour\n} as const satisfies Required;\n\n/**\n * The events that the REST manager emits\n */\nexport enum RESTEvents {\n\tDebug = 'restDebug',\n\tHandlerSweep = 'handlerSweep',\n\tHashSweep = 'hashSweep',\n\tInvalidRequestWarning = 'invalidRequestWarning',\n\tRateLimited = 'rateLimited',\n\tResponse = 'response',\n}\n\nexport const ALLOWED_EXTENSIONS = ['webp', 'png', 'jpg', 'jpeg', 'gif'] as const satisfies readonly string[];\nexport const ALLOWED_STICKER_EXTENSIONS = ['png', 'json', 'gif'] as const satisfies readonly string[];\nexport const ALLOWED_SIZES = [16, 32, 64, 128, 256, 512, 1_024, 2_048, 4_096] as const satisfies readonly number[];\n\nexport type ImageExtension = (typeof ALLOWED_EXTENSIONS)[number];\nexport type StickerExtension = (typeof ALLOWED_STICKER_EXTENSIONS)[number];\nexport type ImageSize = (typeof ALLOWED_SIZES)[number];\n\nexport const OverwrittenMimeTypes = {\n\t// https://github.com/discordjs/discord.js/issues/8557\n\t'image/apng': 'image/png',\n} as const satisfies Readonly>;\n\nexport const BurstHandlerMajorIdKey = 'burst';\n","import type { InternalRequest, RawFile } from '../RequestManager.js';\n\ninterface DiscordErrorFieldInformation {\n\tcode: string;\n\tmessage: string;\n}\n\ninterface DiscordErrorGroupWrapper {\n\t_errors: DiscordError[];\n}\n\ntype DiscordError = DiscordErrorFieldInformation | DiscordErrorGroupWrapper | string | { [k: string]: DiscordError };\n\nexport interface DiscordErrorData {\n\tcode: number;\n\terrors?: DiscordError;\n\tmessage: string;\n}\n\nexport interface OAuthErrorData {\n\terror: string;\n\terror_description?: string;\n}\n\nexport interface RequestBody {\n\tfiles: RawFile[] | undefined;\n\tjson: unknown | undefined;\n}\n\nfunction isErrorGroupWrapper(error: DiscordError): error is DiscordErrorGroupWrapper {\n\treturn Reflect.has(error as Record, '_errors');\n}\n\nfunction isErrorResponse(error: DiscordError): error is DiscordErrorFieldInformation {\n\treturn typeof Reflect.get(error as Record, 'message') === 'string';\n}\n\n/**\n * Represents an API error returned by Discord\n */\nexport class DiscordAPIError extends Error {\n\tpublic requestBody: RequestBody;\n\n\t/**\n\t * @param rawError - The error reported by Discord\n\t * @param code - The error code reported by Discord\n\t * @param status - The status code of the response\n\t * @param method - The method of the request that erred\n\t * @param url - The url of the request that erred\n\t * @param bodyData - The unparsed data for the request that errored\n\t */\n\tpublic constructor(\n\t\tpublic rawError: DiscordErrorData | OAuthErrorData,\n\t\tpublic code: number | string,\n\t\tpublic status: number,\n\t\tpublic method: string,\n\t\tpublic url: string,\n\t\tbodyData: Pick,\n\t) {\n\t\tsuper(DiscordAPIError.getMessage(rawError));\n\n\t\tthis.requestBody = { files: bodyData.files, json: bodyData.body };\n\t}\n\n\t/**\n\t * The name of the error\n\t */\n\tpublic override get name(): string {\n\t\treturn `${DiscordAPIError.name}[${this.code}]`;\n\t}\n\n\tprivate static getMessage(error: DiscordErrorData | OAuthErrorData) {\n\t\tlet flattened = '';\n\t\tif ('code' in error) {\n\t\t\tif (error.errors) {\n\t\t\t\tflattened = [...this.flattenDiscordError(error.errors)].join('\\n');\n\t\t\t}\n\n\t\t\treturn error.message && flattened\n\t\t\t\t? `${error.message}\\n${flattened}`\n\t\t\t\t: error.message || flattened || 'Unknown Error';\n\t\t}\n\n\t\treturn error.error_description ?? 'No Description';\n\t}\n\n\tprivate static *flattenDiscordError(obj: DiscordError, key = ''): IterableIterator {\n\t\tif (isErrorResponse(obj)) {\n\t\t\treturn yield `${key.length ? `${key}[${obj.code}]` : `${obj.code}`}: ${obj.message}`.trim();\n\t\t}\n\n\t\tfor (const [otherKey, val] of Object.entries(obj)) {\n\t\t\tconst nextKey = otherKey.startsWith('_')\n\t\t\t\t? key\n\t\t\t\t: key\n\t\t\t\t? Number.isNaN(Number(otherKey))\n\t\t\t\t\t? `${key}.${otherKey}`\n\t\t\t\t\t: `${key}[${otherKey}]`\n\t\t\t\t: otherKey;\n\n\t\t\tif (typeof val === 'string') {\n\t\t\t\tyield val;\n\t\t\t} else if (isErrorGroupWrapper(val)) {\n\t\t\t\tfor (const error of val._errors) {\n\t\t\t\t\tyield* this.flattenDiscordError(error, nextKey);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tyield* this.flattenDiscordError(val, nextKey);\n\t\t\t}\n\t\t}\n\t}\n}\n","import { STATUS_CODES } from 'node:http';\nimport type { InternalRequest } from '../RequestManager.js';\nimport type { RequestBody } from './DiscordAPIError.js';\n\n/**\n * Represents a HTTP error\n */\nexport class HTTPError extends Error {\n\tpublic requestBody: RequestBody;\n\n\tpublic override name = HTTPError.name;\n\n\t/**\n\t * @param status - The status code of the response\n\t * @param method - The method of the request that erred\n\t * @param url - The url of the request that erred\n\t * @param bodyData - The unparsed data for the request that errored\n\t */\n\tpublic constructor(\n\t\tpublic status: number,\n\t\tpublic method: string,\n\t\tpublic url: string,\n\t\tbodyData: Pick,\n\t) {\n\t\tsuper(STATUS_CODES[status]);\n\n\t\tthis.requestBody = { files: bodyData.files, json: bodyData.body };\n\t}\n}\n","import type { RateLimitData } from '../REST.js';\n\nexport class RateLimitError extends Error implements RateLimitData {\n\tpublic timeToReset: number;\n\n\tpublic limit: number;\n\n\tpublic method: string;\n\n\tpublic hash: string;\n\n\tpublic url: string;\n\n\tpublic route: string;\n\n\tpublic majorParameter: string;\n\n\tpublic global: boolean;\n\n\tpublic constructor({ timeToReset, limit, method, hash, url, route, majorParameter, global }: RateLimitData) {\n\t\tsuper();\n\t\tthis.timeToReset = timeToReset;\n\t\tthis.limit = limit;\n\t\tthis.method = method;\n\t\tthis.hash = hash;\n\t\tthis.url = url;\n\t\tthis.route = route;\n\t\tthis.majorParameter = majorParameter;\n\t\tthis.global = global;\n\t}\n\n\t/**\n\t * The name of the error\n\t */\n\tpublic override get name(): string {\n\t\treturn `${RateLimitError.name}[${this.route}]`;\n\t}\n}\n","import { Blob, Buffer } from 'node:buffer';\nimport { EventEmitter } from 'node:events';\nimport { setInterval, clearInterval } from 'node:timers';\nimport type { URLSearchParams } from 'node:url';\nimport { Collection } from '@discordjs/collection';\nimport { lazy } from '@discordjs/util';\nimport { DiscordSnowflake } from '@sapphire/snowflake';\nimport { FormData, type RequestInit, type BodyInit, type Dispatcher, type Agent } from 'undici';\nimport type { RESTOptions, RestEvents, RequestOptions } from './REST.js';\nimport { BurstHandler } from './handlers/BurstHandler.js';\nimport type { IHandler } from './handlers/IHandler.js';\nimport { SequentialHandler } from './handlers/SequentialHandler.js';\nimport {\n\tBurstHandlerMajorIdKey,\n\tDefaultRestOptions,\n\tDefaultUserAgent,\n\tOverwrittenMimeTypes,\n\tRESTEvents,\n} from './utils/constants.js';\nimport { resolveBody } from './utils/utils.js';\n\n// Make this a lazy dynamic import as file-type is a pure ESM package\nconst getFileType = lazy(async () => import('file-type'));\n\n/**\n * Represents a file to be added to the request\n */\nexport interface RawFile {\n\t/**\n\t * Content-Type of the file\n\t */\n\tcontentType?: string;\n\t/**\n\t * The actual data for the file\n\t */\n\tdata: Buffer | boolean | number | string;\n\t/**\n\t * An explicit key to use for key of the formdata field for this file.\n\t * When not provided, the index of the file in the files array is used in the form `files[${index}]`.\n\t * If you wish to alter the placeholder snowflake, you must provide this property in the same form (`files[${placeholder}]`)\n\t */\n\tkey?: string;\n\t/**\n\t * The name of the file\n\t */\n\tname: string;\n}\n\n/**\n * Represents possible data to be given to an endpoint\n */\nexport interface RequestData {\n\t/**\n\t * Whether to append JSON data to form data instead of `payload_json` when sending files\n\t */\n\tappendToFormData?: boolean;\n\t/**\n\t * If this request needs the `Authorization` header\n\t *\n\t * @defaultValue `true`\n\t */\n\tauth?: boolean;\n\t/**\n\t * The authorization prefix to use for this request, useful if you use this with bearer tokens\n\t *\n\t * @defaultValue `'Bot'`\n\t */\n\tauthPrefix?: 'Bearer' | 'Bot';\n\t/**\n\t * The body to send to this request.\n\t * If providing as BodyInit, set `passThroughBody: true`\n\t */\n\tbody?: BodyInit | unknown;\n\t/**\n\t * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} to use for the request.\n\t */\n\tdispatcher?: Agent;\n\t/**\n\t * Files to be attached to this request\n\t */\n\tfiles?: RawFile[] | undefined;\n\t/**\n\t * Additional headers to add to this request\n\t */\n\theaders?: Record;\n\t/**\n\t * Whether to pass-through the body property directly to `fetch()`.\n\t * This only applies when files is NOT present\n\t */\n\tpassThroughBody?: boolean;\n\t/**\n\t * Query string parameters to append to the called endpoint\n\t */\n\tquery?: URLSearchParams;\n\t/**\n\t * Reason to show in the audit logs\n\t */\n\treason?: string | undefined;\n\t/**\n\t * The signal to abort the queue entry or the REST call, where applicable\n\t */\n\tsignal?: AbortSignal | undefined;\n\t/**\n\t * If this request should be versioned\n\t *\n\t * @defaultValue `true`\n\t */\n\tversioned?: boolean;\n}\n\n/**\n * Possible headers for an API call\n */\nexport interface RequestHeaders {\n\tAuthorization?: string;\n\t'User-Agent': string;\n\t'X-Audit-Log-Reason'?: string;\n}\n\n/**\n * Possible API methods to be used when doing requests\n */\nexport enum RequestMethod {\n\tDelete = 'DELETE',\n\tGet = 'GET',\n\tPatch = 'PATCH',\n\tPost = 'POST',\n\tPut = 'PUT',\n}\n\nexport type RouteLike = `/${string}`;\n\n/**\n * Internal request options\n *\n * @internal\n */\nexport interface InternalRequest extends RequestData {\n\tfullRoute: RouteLike;\n\tmethod: RequestMethod;\n}\n\nexport type HandlerRequestData = Pick;\n\n/**\n * Parsed route data for an endpoint\n *\n * @internal\n */\nexport interface RouteData {\n\tbucketRoute: string;\n\tmajorParameter: string;\n\toriginal: RouteLike;\n}\n\n/**\n * Represents a hash and its associated fields\n *\n * @internal\n */\nexport interface HashData {\n\tlastAccess: number;\n\tvalue: string;\n}\n\nexport interface RequestManager {\n\temit: ((event: K, ...args: RestEvents[K]) => boolean) &\n\t\t((event: Exclude, ...args: any[]) => boolean);\n\n\toff: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\ton: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tonce: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tremoveAllListeners: ((event?: K) => this) &\n\t\t((event?: Exclude) => this);\n}\n\n/**\n * Represents the class that manages handlers for endpoints\n */\nexport class RequestManager extends EventEmitter {\n\t/**\n\t * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} for all requests\n\t * performed by this manager.\n\t */\n\tpublic agent: Dispatcher | null = null;\n\n\t/**\n\t * The number of requests remaining in the global bucket\n\t */\n\tpublic globalRemaining: number;\n\n\t/**\n\t * The promise used to wait out the global rate limit\n\t */\n\tpublic globalDelay: Promise | null = null;\n\n\t/**\n\t * The timestamp at which the global bucket resets\n\t */\n\tpublic globalReset = -1;\n\n\t/**\n\t * API bucket hashes that are cached from provided routes\n\t */\n\tpublic readonly hashes = new Collection();\n\n\t/**\n\t * Request handlers created from the bucket hash and the major parameters\n\t */\n\tpublic readonly handlers = new Collection();\n\n\t#token: string | null = null;\n\n\tprivate hashTimer!: NodeJS.Timer;\n\n\tprivate handlerTimer!: NodeJS.Timer;\n\n\tpublic readonly options: RESTOptions;\n\n\tpublic constructor(options: Partial) {\n\t\tsuper();\n\t\tthis.options = { ...DefaultRestOptions, ...options };\n\t\tthis.options.offset = Math.max(0, this.options.offset);\n\t\tthis.globalRemaining = this.options.globalRequestsPerSecond;\n\t\tthis.agent = options.agent ?? null;\n\n\t\t// Start sweepers\n\t\tthis.setupSweepers();\n\t}\n\n\tprivate setupSweepers() {\n\t\t// eslint-disable-next-line unicorn/consistent-function-scoping\n\t\tconst validateMaxInterval = (interval: number) => {\n\t\t\tif (interval > 14_400_000) {\n\t\t\t\tthrow new Error('Cannot set an interval greater than 4 hours');\n\t\t\t}\n\t\t};\n\n\t\tif (this.options.hashSweepInterval !== 0 && this.options.hashSweepInterval !== Number.POSITIVE_INFINITY) {\n\t\t\tvalidateMaxInterval(this.options.hashSweepInterval);\n\t\t\tthis.hashTimer = setInterval(() => {\n\t\t\t\tconst sweptHashes = new Collection();\n\t\t\t\tconst currentDate = Date.now();\n\n\t\t\t\t// Begin sweeping hash based on lifetimes\n\t\t\t\tthis.hashes.sweep((val, key) => {\n\t\t\t\t\t// `-1` indicates a global hash\n\t\t\t\t\tif (val.lastAccess === -1) return false;\n\n\t\t\t\t\t// Check if lifetime has been exceeded\n\t\t\t\t\tconst shouldSweep = Math.floor(currentDate - val.lastAccess) > this.options.hashLifetime;\n\n\t\t\t\t\t// Add hash to collection of swept hashes\n\t\t\t\t\tif (shouldSweep) {\n\t\t\t\t\t\t// Add to swept hashes\n\t\t\t\t\t\tsweptHashes.set(key, val);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Emit debug information\n\t\t\t\t\tthis.emit(RESTEvents.Debug, `Hash ${val.value} for ${key} swept due to lifetime being exceeded`);\n\n\t\t\t\t\treturn shouldSweep;\n\t\t\t\t});\n\n\t\t\t\t// Fire event\n\t\t\t\tthis.emit(RESTEvents.HashSweep, sweptHashes);\n\t\t\t}, this.options.hashSweepInterval).unref();\n\t\t}\n\n\t\tif (this.options.handlerSweepInterval !== 0 && this.options.handlerSweepInterval !== Number.POSITIVE_INFINITY) {\n\t\t\tvalidateMaxInterval(this.options.handlerSweepInterval);\n\t\t\tthis.handlerTimer = setInterval(() => {\n\t\t\t\tconst sweptHandlers = new Collection();\n\n\t\t\t\t// Begin sweeping handlers based on activity\n\t\t\t\tthis.handlers.sweep((val, key) => {\n\t\t\t\t\tconst { inactive } = val;\n\n\t\t\t\t\t// Collect inactive handlers\n\t\t\t\t\tif (inactive) {\n\t\t\t\t\t\tsweptHandlers.set(key, val);\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.emit(RESTEvents.Debug, `Handler ${val.id} for ${key} swept due to being inactive`);\n\t\t\t\t\treturn inactive;\n\t\t\t\t});\n\n\t\t\t\t// Fire event\n\t\t\t\tthis.emit(RESTEvents.HandlerSweep, sweptHandlers);\n\t\t\t}, this.options.handlerSweepInterval).unref();\n\t\t}\n\t}\n\n\t/**\n\t * Sets the default agent to use for requests performed by this manager\n\t *\n\t * @param agent - The agent to use\n\t */\n\tpublic setAgent(agent: Dispatcher) {\n\t\tthis.agent = agent;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the authorization token that should be used for requests\n\t *\n\t * @param token - The authorization token to use\n\t */\n\tpublic setToken(token: string) {\n\t\tthis.#token = token;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Queues a request to be sent\n\t *\n\t * @param request - All the information needed to make a request\n\t * @returns The response from the api request\n\t */\n\tpublic async queueRequest(request: InternalRequest): Promise {\n\t\t// Generalize the endpoint to its route data\n\t\tconst routeId = RequestManager.generateRouteData(request.fullRoute, request.method);\n\t\t// Get the bucket hash for the generic route, or point to a global route otherwise\n\t\tconst hash = this.hashes.get(`${request.method}:${routeId.bucketRoute}`) ?? {\n\t\t\tvalue: `Global(${request.method}:${routeId.bucketRoute})`,\n\t\t\tlastAccess: -1,\n\t\t};\n\n\t\t// Get the request handler for the obtained hash, with its major parameter\n\t\tconst handler =\n\t\t\tthis.handlers.get(`${hash.value}:${routeId.majorParameter}`) ??\n\t\t\tthis.createHandler(hash.value, routeId.majorParameter);\n\n\t\t// Resolve the request into usable fetch options\n\t\tconst { url, fetchOptions } = await this.resolveRequest(request);\n\n\t\t// Queue the request\n\t\treturn handler.queueRequest(routeId, url, fetchOptions, {\n\t\t\tbody: request.body,\n\t\t\tfiles: request.files,\n\t\t\tauth: request.auth !== false,\n\t\t\tsignal: request.signal,\n\t\t});\n\t}\n\n\t/**\n\t * Creates a new rate limit handler from a hash, based on the hash and the major parameter\n\t *\n\t * @param hash - The hash for the route\n\t * @param majorParameter - The major parameter for this handler\n\t * @internal\n\t */\n\tprivate createHandler(hash: string, majorParameter: string) {\n\t\t// Create the async request queue to handle requests\n\t\tconst queue =\n\t\t\tmajorParameter === BurstHandlerMajorIdKey\n\t\t\t\t? new BurstHandler(this, hash, majorParameter)\n\t\t\t\t: new SequentialHandler(this, hash, majorParameter);\n\t\t// Save the queue based on its id\n\t\tthis.handlers.set(queue.id, queue);\n\n\t\treturn queue;\n\t}\n\n\t/**\n\t * Formats the request data to a usable format for fetch\n\t *\n\t * @param request - The request data\n\t */\n\tprivate async resolveRequest(request: InternalRequest): Promise<{ fetchOptions: RequestOptions; url: string }> {\n\t\tconst { options } = this;\n\n\t\tlet query = '';\n\n\t\t// If a query option is passed, use it\n\t\tif (request.query) {\n\t\t\tconst resolvedQuery = request.query.toString();\n\t\t\tif (resolvedQuery !== '') {\n\t\t\t\tquery = `?${resolvedQuery}`;\n\t\t\t}\n\t\t}\n\n\t\t// Create the required headers\n\t\tconst headers: RequestHeaders = {\n\t\t\t...this.options.headers,\n\t\t\t'User-Agent': `${DefaultUserAgent} ${options.userAgentAppendix}`.trim(),\n\t\t};\n\n\t\t// If this request requires authorization (allowing non-\"authorized\" requests for webhooks)\n\t\tif (request.auth !== false) {\n\t\t\t// If we haven't received a token, throw an error\n\t\t\tif (!this.#token) {\n\t\t\t\tthrow new Error('Expected token to be set for this request, but none was present');\n\t\t\t}\n\n\t\t\theaders.Authorization = `${request.authPrefix ?? this.options.authPrefix} ${this.#token}`;\n\t\t}\n\n\t\t// If a reason was set, set it's appropriate header\n\t\tif (request.reason?.length) {\n\t\t\theaders['X-Audit-Log-Reason'] = encodeURIComponent(request.reason);\n\t\t}\n\n\t\t// Format the full request URL (api base, optional version, endpoint, optional querystring)\n\t\tconst url = `${options.api}${request.versioned === false ? '' : `/v${options.version}`}${\n\t\t\trequest.fullRoute\n\t\t}${query}`;\n\n\t\tlet finalBody: RequestInit['body'];\n\t\tlet additionalHeaders: Record = {};\n\n\t\tif (request.files?.length) {\n\t\t\tconst formData = new FormData();\n\n\t\t\t// Attach all files to the request\n\t\t\tfor (const [index, file] of request.files.entries()) {\n\t\t\t\tconst fileKey = file.key ?? `files[${index}]`;\n\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/FormData/append#parameters\n\t\t\t\t// FormData.append only accepts a string or Blob.\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob#parameters\n\t\t\t\t// The Blob constructor accepts TypedArray/ArrayBuffer, strings, and Blobs.\n\t\t\t\tif (Buffer.isBuffer(file.data)) {\n\t\t\t\t\t// Try to infer the content type from the buffer if one isn't passed\n\t\t\t\t\tconst { fileTypeFromBuffer } = await getFileType();\n\t\t\t\t\tlet contentType = file.contentType;\n\t\t\t\t\tif (!contentType) {\n\t\t\t\t\t\tconst parsedType = (await fileTypeFromBuffer(file.data))?.mime;\n\t\t\t\t\t\tif (parsedType) {\n\t\t\t\t\t\t\tcontentType = OverwrittenMimeTypes[parsedType as keyof typeof OverwrittenMimeTypes] ?? parsedType;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tformData.append(fileKey, new Blob([file.data], { type: contentType }), file.name);\n\t\t\t\t} else {\n\t\t\t\t\tformData.append(fileKey, new Blob([`${file.data}`], { type: file.contentType }), file.name);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If a JSON body was added as well, attach it to the form data, using payload_json unless otherwise specified\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t\tif (request.body != null) {\n\t\t\t\tif (request.appendToFormData) {\n\t\t\t\t\tfor (const [key, value] of Object.entries(request.body as Record)) {\n\t\t\t\t\t\tformData.append(key, value);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tformData.append('payload_json', JSON.stringify(request.body));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Set the final body to the form data\n\t\t\tfinalBody = formData;\n\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t} else if (request.body != null) {\n\t\t\tif (request.passThroughBody) {\n\t\t\t\tfinalBody = request.body as BodyInit;\n\t\t\t} else {\n\t\t\t\t// Stringify the JSON data\n\t\t\t\tfinalBody = JSON.stringify(request.body);\n\t\t\t\t// Set the additional headers to specify the content-type\n\t\t\t\tadditionalHeaders = { 'Content-Type': 'application/json' };\n\t\t\t}\n\t\t}\n\n\t\tfinalBody = await resolveBody(finalBody);\n\n\t\tconst fetchOptions: RequestOptions = {\n\t\t\theaders: { ...request.headers, ...additionalHeaders, ...headers } as Record,\n\t\t\tmethod: request.method.toUpperCase() as Dispatcher.HttpMethod,\n\t\t};\n\n\t\tif (finalBody !== undefined) {\n\t\t\tfetchOptions.body = finalBody as Exclude;\n\t\t}\n\n\t\t// Prioritize setting an agent per request, use the agent for this instance otherwise.\n\t\tfetchOptions.dispatcher = request.dispatcher ?? this.agent ?? undefined!;\n\n\t\treturn { url, fetchOptions };\n\t}\n\n\t/**\n\t * Stops the hash sweeping interval\n\t */\n\tpublic clearHashSweeper() {\n\t\tclearInterval(this.hashTimer);\n\t}\n\n\t/**\n\t * Stops the request handler sweeping interval\n\t */\n\tpublic clearHandlerSweeper() {\n\t\tclearInterval(this.handlerTimer);\n\t}\n\n\t/**\n\t * Generates route data for an endpoint:method\n\t *\n\t * @param endpoint - The raw endpoint to generalize\n\t * @param method - The HTTP method this endpoint is called without\n\t * @internal\n\t */\n\tprivate static generateRouteData(endpoint: RouteLike, method: RequestMethod): RouteData {\n\t\tif (endpoint.startsWith('/interactions/') && endpoint.endsWith('/callback')) {\n\t\t\treturn {\n\t\t\t\tmajorParameter: BurstHandlerMajorIdKey,\n\t\t\t\tbucketRoute: '/interactions/:id/:token/callback',\n\t\t\t\toriginal: endpoint,\n\t\t\t};\n\t\t}\n\n\t\tconst majorIdMatch = /^\\/(?:channels|guilds|webhooks)\\/(\\d{17,19})/.exec(endpoint);\n\n\t\t// Get the major id for this route - global otherwise\n\t\tconst majorId = majorIdMatch?.[1] ?? 'global';\n\n\t\tconst baseRoute = endpoint\n\t\t\t// Strip out all ids\n\t\t\t.replaceAll(/\\d{17,19}/g, ':id')\n\t\t\t// Strip out reaction as they fall under the same bucket\n\t\t\t.replace(/\\/reactions\\/(.*)/, '/reactions/:reaction');\n\n\t\tlet exceptions = '';\n\n\t\t// Hard-Code Old Message Deletion Exception (2 week+ old messages are a different bucket)\n\t\t// https://github.com/discord/discord-api-docs/issues/1295\n\t\tif (method === RequestMethod.Delete && baseRoute === '/channels/:id/messages/:id') {\n\t\t\tconst id = /\\d{17,19}$/.exec(endpoint)![0]!;\n\t\t\tconst timestamp = DiscordSnowflake.timestampFrom(id);\n\t\t\tif (Date.now() - timestamp > 1_000 * 60 * 60 * 24 * 14) {\n\t\t\t\texceptions += '/Delete Old Message';\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tmajorParameter: majorId,\n\t\t\tbucketRoute: baseRoute + exceptions,\n\t\t\toriginal: endpoint,\n\t\t};\n\t}\n}\n","import { setTimeout as sleep } from 'node:timers/promises';\nimport type { Dispatcher } from 'undici';\nimport type { RequestOptions } from '../REST.js';\nimport type { HandlerRequestData, RequestManager, RouteData } from '../RequestManager.js';\nimport { RESTEvents } from '../utils/constants.js';\nimport { onRateLimit, parseHeader } from '../utils/utils.js';\nimport type { IHandler } from './IHandler.js';\nimport { handleErrors, incrementInvalidCount, makeNetworkRequest } from './Shared.js';\n\n/**\n * The structure used to handle burst requests for a given bucket.\n * Burst requests have no ratelimit handling but allow for pre- and post-processing\n * of data in the same manner as sequentially queued requests.\n *\n * @remarks\n * This queue may still emit a rate limit error if an unexpected 429 is hit\n */\nexport class BurstHandler implements IHandler {\n\t/**\n\t * {@inheritdoc IHandler.id}\n\t */\n\tpublic readonly id: string;\n\n\t/**\n\t * {@inheritDoc IHandler.inactive}\n\t */\n\tpublic inactive = false;\n\n\t/**\n\t * @param manager - The request manager\n\t * @param hash - The hash that this RequestHandler handles\n\t * @param majorParameter - The major parameter for this handler\n\t */\n\tpublic constructor(\n\t\tprivate readonly manager: RequestManager,\n\t\tprivate readonly hash: string,\n\t\tprivate readonly majorParameter: string,\n\t) {\n\t\tthis.id = `${hash}:${majorParameter}`;\n\t}\n\n\t/**\n\t * Emits a debug message\n\t *\n\t * @param message - The message to debug\n\t */\n\tprivate debug(message: string) {\n\t\tthis.manager.emit(RESTEvents.Debug, `[REST ${this.id}] ${message}`);\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.queueRequest}\n\t */\n\tpublic async queueRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t): Promise {\n\t\treturn this.runRequest(routeId, url, options, requestData);\n\t}\n\n\t/**\n\t * The method that actually makes the request to the API, and updates info about the bucket accordingly\n\t *\n\t * @param routeId - The generalized API route with literal ids for major parameters\n\t * @param url - The fully resolved URL to make the request to\n\t * @param options - The fetch options needed to make the request\n\t * @param requestData - Extra data from the user's request needed for errors and additional processing\n\t * @param retries - The number of retries this request has already attempted (recursion)\n\t */\n\tprivate async runRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t\tretries = 0,\n\t): Promise {\n\t\tconst method = options.method ?? 'get';\n\n\t\tconst res = await makeNetworkRequest(this.manager, routeId, url, options, requestData, retries);\n\n\t\t// Retry requested\n\t\tif (res === null) {\n\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t}\n\n\t\tconst status = res.statusCode;\n\t\tlet retryAfter = 0;\n\t\tconst retry = parseHeader(res.headers['retry-after']);\n\n\t\t// Amount of time in milliseconds until we should retry if rate limited (globally or otherwise)\n\t\tif (retry) retryAfter = Number(retry) * 1_000 + this.manager.options.offset;\n\n\t\t// Count the invalid requests\n\t\tif (status === 401 || status === 403 || status === 429) {\n\t\t\tincrementInvalidCount(this.manager);\n\t\t}\n\n\t\tif (status >= 200 && status < 300) {\n\t\t\treturn res;\n\t\t} else if (status === 429) {\n\t\t\t// Unexpected ratelimit\n\t\t\tconst isGlobal = res.headers['x-ratelimit-global'] !== undefined;\n\t\t\tawait onRateLimit(this.manager, {\n\t\t\t\ttimeToReset: retryAfter,\n\t\t\t\tlimit: Number.POSITIVE_INFINITY,\n\t\t\t\tmethod,\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t});\n\t\t\tthis.debug(\n\t\t\t\t[\n\t\t\t\t\t'Encountered unexpected 429 rate limit',\n\t\t\t\t\t` Global : ${isGlobal}`,\n\t\t\t\t\t` Method : ${method}`,\n\t\t\t\t\t` URL : ${url}`,\n\t\t\t\t\t` Bucket : ${routeId.bucketRoute}`,\n\t\t\t\t\t` Major parameter: ${routeId.majorParameter}`,\n\t\t\t\t\t` Hash : ${this.hash}`,\n\t\t\t\t\t` Limit : ${Number.POSITIVE_INFINITY}`,\n\t\t\t\t\t` Retry After : ${retryAfter}ms`,\n\t\t\t\t\t` Sublimit : None`,\n\t\t\t\t].join('\\n'),\n\t\t\t);\n\n\t\t\t// We are bypassing all other limits, but an encountered limit should be respected (it's probably a non-punished rate limit anyways)\n\t\t\tawait sleep(retryAfter);\n\n\t\t\t// Since this is not a server side issue, the next request should pass, so we don't bump the retries counter\n\t\t\treturn this.runRequest(routeId, url, options, requestData, retries);\n\t\t} else {\n\t\t\tconst handled = await handleErrors(this.manager, res, method, url, requestData, retries);\n\t\t\tif (handled === null) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t\t}\n\n\t\t\treturn handled;\n\t\t}\n\t}\n}\n","import { Blob, Buffer } from 'node:buffer';\nimport { URLSearchParams } from 'node:url';\nimport { types } from 'node:util';\nimport type { RESTPatchAPIChannelJSONBody } from 'discord-api-types/v10';\nimport { FormData, type Dispatcher, type RequestInit } from 'undici';\nimport type { RateLimitData, RequestOptions } from '../REST.js';\nimport { type RequestManager, RequestMethod } from '../RequestManager.js';\nimport { RateLimitError } from '../errors/RateLimitError.js';\n\nexport function parseHeader(header: string[] | string | undefined): string | undefined {\n\tif (header === undefined || typeof header === 'string') {\n\t\treturn header;\n\t}\n\n\treturn header.join(';');\n}\n\nfunction serializeSearchParam(value: unknown): string | null {\n\tswitch (typeof value) {\n\t\tcase 'string':\n\t\t\treturn value;\n\t\tcase 'number':\n\t\tcase 'bigint':\n\t\tcase 'boolean':\n\t\t\treturn value.toString();\n\t\tcase 'object':\n\t\t\tif (value === null) return null;\n\t\t\tif (value instanceof Date) {\n\t\t\t\treturn Number.isNaN(value.getTime()) ? null : value.toISOString();\n\t\t\t}\n\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-base-to-string\n\t\t\tif (typeof value.toString === 'function' && value.toString !== Object.prototype.toString) return value.toString();\n\t\t\treturn null;\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/**\n * Creates and populates an URLSearchParams instance from an object, stripping\n * out null and undefined values, while also coercing non-strings to strings.\n *\n * @param options - The options to use\n * @returns A populated URLSearchParams instance\n */\nexport function makeURLSearchParams(options?: Readonly) {\n\tconst params = new URLSearchParams();\n\tif (!options) return params;\n\n\tfor (const [key, value] of Object.entries(options)) {\n\t\tconst serialized = serializeSearchParam(value);\n\t\tif (serialized !== null) params.append(key, serialized);\n\t}\n\n\treturn params;\n}\n\n/**\n * Converts the response to usable data\n *\n * @param res - The fetch response\n */\nexport async function parseResponse(res: Dispatcher.ResponseData): Promise {\n\tconst header = parseHeader(res.headers['content-type']);\n\tif (header?.startsWith('application/json')) {\n\t\treturn res.body.json();\n\t}\n\n\treturn res.body.arrayBuffer();\n}\n\n/**\n * Check whether a request falls under a sublimit\n *\n * @param bucketRoute - The buckets route identifier\n * @param body - The options provided as JSON data\n * @param method - The HTTP method that will be used to make the request\n * @returns Whether the request falls under a sublimit\n */\nexport function hasSublimit(bucketRoute: string, body?: unknown, method?: string): boolean {\n\t// TODO: Update for new sublimits\n\t// Currently known sublimits:\n\t// Editing channel `name` or `topic`\n\tif (bucketRoute === '/channels/:id') {\n\t\tif (typeof body !== 'object' || body === null) return false;\n\t\t// This should never be a POST body, but just in case\n\t\tif (method !== RequestMethod.Patch) return false;\n\t\tconst castedBody = body as RESTPatchAPIChannelJSONBody;\n\t\treturn ['name', 'topic'].some((key) => Reflect.has(castedBody, key));\n\t}\n\n\t// If we are checking if a request has a sublimit on a route not checked above, sublimit all requests to avoid a flood of 429s\n\treturn true;\n}\n\nexport async function resolveBody(body: RequestInit['body']): Promise {\n\t// eslint-disable-next-line no-eq-null, eqeqeq\n\tif (body == null) {\n\t\treturn null;\n\t} else if (typeof body === 'string') {\n\t\treturn body;\n\t} else if (types.isUint8Array(body)) {\n\t\treturn body;\n\t} else if (types.isArrayBuffer(body)) {\n\t\treturn new Uint8Array(body);\n\t} else if (body instanceof URLSearchParams) {\n\t\treturn body.toString();\n\t} else if (body instanceof DataView) {\n\t\treturn new Uint8Array(body.buffer);\n\t} else if (body instanceof Blob) {\n\t\treturn new Uint8Array(await body.arrayBuffer());\n\t} else if (body instanceof FormData) {\n\t\treturn body;\n\t} else if ((body as Iterable)[Symbol.iterator]) {\n\t\tconst chunks = [...(body as Iterable)];\n\t\tconst length = chunks.reduce((a, b) => a + b.length, 0);\n\n\t\tconst uint8 = new Uint8Array(length);\n\t\tlet lengthUsed = 0;\n\n\t\treturn chunks.reduce((a, b) => {\n\t\t\ta.set(b, lengthUsed);\n\t\t\tlengthUsed += b.length;\n\t\t\treturn a;\n\t\t}, uint8);\n\t} else if ((body as AsyncIterable)[Symbol.asyncIterator]) {\n\t\tconst chunks: Uint8Array[] = [];\n\n\t\tfor await (const chunk of body as AsyncIterable) {\n\t\t\tchunks.push(chunk);\n\t\t}\n\n\t\treturn Buffer.concat(chunks);\n\t}\n\n\tthrow new TypeError(`Unable to resolve body.`);\n}\n\n/**\n * Check whether an error indicates that a retry can be attempted\n *\n * @param error - The error thrown by the network request\n * @returns Whether the error indicates a retry should be attempted\n */\nexport function shouldRetry(error: Error | NodeJS.ErrnoException) {\n\t// Retry for possible timed out requests\n\tif (error.name === 'AbortError') return true;\n\t// Downlevel ECONNRESET to retry as it may be recoverable\n\treturn ('code' in error && error.code === 'ECONNRESET') || error.message.includes('ECONNRESET');\n}\n\n/**\n * Determines whether the request should be queued or whether a RateLimitError should be thrown\n *\n * @internal\n */\nexport async function onRateLimit(manager: RequestManager, rateLimitData: RateLimitData) {\n\tconst { options } = manager;\n\tif (!options.rejectOnRateLimit) return;\n\n\tconst shouldThrow =\n\t\ttypeof options.rejectOnRateLimit === 'function'\n\t\t\t? await options.rejectOnRateLimit(rateLimitData)\n\t\t\t: options.rejectOnRateLimit.some((route) => rateLimitData.route.startsWith(route.toLowerCase()));\n\tif (shouldThrow) {\n\t\tthrow new RateLimitError(rateLimitData);\n\t}\n}\n","import { setTimeout, clearTimeout } from 'node:timers';\nimport { request, type Dispatcher } from 'undici';\nimport type { RequestOptions } from '../REST.js';\nimport type { HandlerRequestData, RequestManager, RouteData } from '../RequestManager.js';\nimport type { DiscordErrorData, OAuthErrorData } from '../errors/DiscordAPIError.js';\nimport { DiscordAPIError } from '../errors/DiscordAPIError.js';\nimport { HTTPError } from '../errors/HTTPError.js';\nimport { RESTEvents } from '../utils/constants.js';\nimport { parseResponse, shouldRetry } from '../utils/utils.js';\nimport type { PolyFillAbortSignal } from './IHandler.js';\n\n/**\n * Invalid request limiting is done on a per-IP basis, not a per-token basis.\n * The best we can do is track invalid counts process-wide (on the theory that\n * users could have multiple bots run from one process) rather than per-bot.\n * Therefore, store these at file scope here rather than in the client's\n * RESTManager object.\n */\nlet invalidCount = 0;\nlet invalidCountResetTime: number | null = null;\n\n/**\n * Increment the invalid request count and emit warning if necessary\n *\n * @internal\n */\nexport function incrementInvalidCount(manager: RequestManager) {\n\tif (!invalidCountResetTime || invalidCountResetTime < Date.now()) {\n\t\tinvalidCountResetTime = Date.now() + 1_000 * 60 * 10;\n\t\tinvalidCount = 0;\n\t}\n\n\tinvalidCount++;\n\n\tconst emitInvalid =\n\t\tmanager.options.invalidRequestWarningInterval > 0 &&\n\t\tinvalidCount % manager.options.invalidRequestWarningInterval === 0;\n\tif (emitInvalid) {\n\t\t// Let library users know periodically about invalid requests\n\t\tmanager.emit(RESTEvents.InvalidRequestWarning, {\n\t\t\tcount: invalidCount,\n\t\t\tremainingTime: invalidCountResetTime - Date.now(),\n\t\t});\n\t}\n}\n\n/**\n * Performs the actual network request for a request handler\n *\n * @param manager - The manager that holds options and emits informational events\n * @param routeId - The generalized api route with literal ids for major parameters\n * @param url - The fully resolved url to make the request to\n * @param options - The fetch options needed to make the request\n * @param requestData - Extra data from the user's request needed for errors and additional processing\n * @param retries - The number of retries this request has already attempted (recursion occurs on the handler)\n * @returns The respond from the network or `null` when the request should be retried\n * @internal\n */\nexport async function makeNetworkRequest(\n\tmanager: RequestManager,\n\trouteId: RouteData,\n\turl: string,\n\toptions: RequestOptions,\n\trequestData: HandlerRequestData,\n\tretries: number,\n) {\n\tconst controller = new AbortController();\n\tconst timeout = setTimeout(() => controller.abort(), manager.options.timeout).unref();\n\tif (requestData.signal) {\n\t\t// The type polyfill is required because Node.js's types are incomplete.\n\t\tconst signal = requestData.signal as unknown as PolyFillAbortSignal;\n\t\t// If the user signal was aborted, abort the controller, else abort the local signal.\n\t\t// The reason why we don't re-use the user's signal, is because users may use the same signal for multiple\n\t\t// requests, and we do not want to cause unexpected side-effects.\n\t\tif (signal.aborted) controller.abort();\n\t\telse signal.addEventListener('abort', () => controller.abort());\n\t}\n\n\tlet res: Dispatcher.ResponseData;\n\ttry {\n\t\tres = await request(url, { ...options, signal: controller.signal });\n\t} catch (error: unknown) {\n\t\tif (!(error instanceof Error)) throw error;\n\t\t// Retry the specified number of times if needed\n\t\tif (shouldRetry(error) && retries !== manager.options.retries) {\n\t\t\t// Retry is handled by the handler upon receiving null\n\t\t\treturn null;\n\t\t}\n\n\t\tthrow error;\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n\n\tif (manager.listenerCount(RESTEvents.Response)) {\n\t\tmanager.emit(\n\t\t\tRESTEvents.Response,\n\t\t\t{\n\t\t\t\tmethod: options.method ?? 'get',\n\t\t\t\tpath: routeId.original,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\toptions,\n\t\t\t\tdata: requestData,\n\t\t\t\tretries,\n\t\t\t},\n\t\t\t{ ...res },\n\t\t);\n\t}\n\n\treturn res;\n}\n\n/**\n * Handles 5xx and 4xx errors (not 429's) conventionally. 429's should be handled before calling this function\n *\n * @param manager - The manager that holds options and emits informational events\n * @param res - The response received from {@link makeNetworkRequest}\n * @param method - The method used to make the request\n * @param url - The fully resolved url to make the request to\n * @param requestData - Extra data from the user's request needed for errors and additional processing\n * @param retries - The number of retries this request has already attempted (recursion occurs on the handler)\n * @returns - The response if the status code is not handled or null to request a retry\n */\nexport async function handleErrors(\n\tmanager: RequestManager,\n\tres: Dispatcher.ResponseData,\n\tmethod: string,\n\turl: string,\n\trequestData: HandlerRequestData,\n\tretries: number,\n) {\n\tconst status = res.statusCode;\n\tif (status >= 500 && status < 600) {\n\t\t// Retry the specified number of times for possible server side issues\n\t\tif (retries !== manager.options.retries) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// We are out of retries, throw an error\n\t\tthrow new HTTPError(status, method, url, requestData);\n\t} else {\n\t\t// Handle possible malformed requests\n\t\tif (status >= 400 && status < 500) {\n\t\t\t// If we receive this status code, it means the token we had is no longer valid.\n\t\t\tif (status === 401 && requestData.auth) {\n\t\t\t\tmanager.setToken(null!);\n\t\t\t}\n\n\t\t\t// The request will not succeed for some reason, parse the error returned from the api\n\t\t\tconst data = (await parseResponse(res)) as DiscordErrorData | OAuthErrorData;\n\t\t\t// throw the API error\n\t\t\tthrow new DiscordAPIError(data, 'code' in data ? data.code : data.error, status, method, url, requestData);\n\t\t}\n\n\t\treturn res;\n\t}\n}\n","import { setTimeout as sleep } from 'node:timers/promises';\nimport { AsyncQueue } from '@sapphire/async-queue';\nimport type { Dispatcher } from 'undici';\nimport type { RateLimitData, RequestOptions } from '../REST.js';\nimport type { HandlerRequestData, RequestManager, RouteData } from '../RequestManager.js';\nimport { RESTEvents } from '../utils/constants.js';\nimport { hasSublimit, onRateLimit, parseHeader } from '../utils/utils.js';\nimport type { IHandler } from './IHandler.js';\nimport { handleErrors, incrementInvalidCount, makeNetworkRequest } from './Shared.js';\n\nconst enum QueueType {\n\tStandard,\n\tSublimit,\n}\n\n/**\n * The structure used to handle sequential requests for a given bucket\n */\nexport class SequentialHandler implements IHandler {\n\t/**\n\t * {@inheritDoc IHandler.id}\n\t */\n\tpublic readonly id: string;\n\n\t/**\n\t * The time this rate limit bucket will reset\n\t */\n\tprivate reset = -1;\n\n\t/**\n\t * The remaining requests that can be made before we are rate limited\n\t */\n\tprivate remaining = 1;\n\n\t/**\n\t * The total number of requests that can be made before we are rate limited\n\t */\n\tprivate limit = Number.POSITIVE_INFINITY;\n\n\t/**\n\t * The interface used to sequence async requests sequentially\n\t */\n\t#asyncQueue = new AsyncQueue();\n\n\t/**\n\t * The interface used to sequence sublimited async requests sequentially\n\t */\n\t#sublimitedQueue: AsyncQueue | null = null;\n\n\t/**\n\t * A promise wrapper for when the sublimited queue is finished being processed or null when not being processed\n\t */\n\t#sublimitPromise: { promise: Promise; resolve(): void } | null = null;\n\n\t/**\n\t * Whether the sublimit queue needs to be shifted in the finally block\n\t */\n\t#shiftSublimit = false;\n\n\t/**\n\t * @param manager - The request manager\n\t * @param hash - The hash that this RequestHandler handles\n\t * @param majorParameter - The major parameter for this handler\n\t */\n\tpublic constructor(\n\t\tprivate readonly manager: RequestManager,\n\t\tprivate readonly hash: string,\n\t\tprivate readonly majorParameter: string,\n\t) {\n\t\tthis.id = `${hash}:${majorParameter}`;\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.inactive}\n\t */\n\tpublic get inactive(): boolean {\n\t\treturn (\n\t\t\tthis.#asyncQueue.remaining === 0 &&\n\t\t\t(this.#sublimitedQueue === null || this.#sublimitedQueue.remaining === 0) &&\n\t\t\t!this.limited\n\t\t);\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited by the global limit\n\t */\n\tprivate get globalLimited(): boolean {\n\t\treturn this.manager.globalRemaining <= 0 && Date.now() < this.manager.globalReset;\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited by its limit\n\t */\n\tprivate get localLimited(): boolean {\n\t\treturn this.remaining <= 0 && Date.now() < this.reset;\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited\n\t */\n\tprivate get limited(): boolean {\n\t\treturn this.globalLimited || this.localLimited;\n\t}\n\n\t/**\n\t * The time until queued requests can continue\n\t */\n\tprivate get timeToReset(): number {\n\t\treturn this.reset + this.manager.options.offset - Date.now();\n\t}\n\n\t/**\n\t * Emits a debug message\n\t *\n\t * @param message - The message to debug\n\t */\n\tprivate debug(message: string) {\n\t\tthis.manager.emit(RESTEvents.Debug, `[REST ${this.id}] ${message}`);\n\t}\n\n\t/**\n\t * Delay all requests for the specified amount of time, handling global rate limits\n\t *\n\t * @param time - The amount of time to delay all requests for\n\t */\n\tprivate async globalDelayFor(time: number): Promise {\n\t\tawait sleep(time);\n\t\tthis.manager.globalDelay = null;\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.queueRequest}\n\t */\n\tpublic async queueRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t): Promise {\n\t\tlet queue = this.#asyncQueue;\n\t\tlet queueType = QueueType.Standard;\n\t\t// Separate sublimited requests when already sublimited\n\t\tif (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) {\n\t\t\tqueue = this.#sublimitedQueue!;\n\t\t\tqueueType = QueueType.Sublimit;\n\t\t}\n\n\t\t// Wait for any previous requests to be completed before this one is run\n\t\tawait queue.wait({ signal: requestData.signal });\n\t\t// This set handles retroactively sublimiting requests\n\t\tif (queueType === QueueType.Standard) {\n\t\t\tif (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) {\n\t\t\t\t/**\n\t\t\t\t * Remove the request from the standard queue, it should never be possible to get here while processing the\n\t\t\t\t * sublimit queue so there is no need to worry about shifting the wrong request\n\t\t\t\t */\n\t\t\t\tqueue = this.#sublimitedQueue!;\n\t\t\t\tconst wait = queue.wait();\n\t\t\t\tthis.#asyncQueue.shift();\n\t\t\t\tawait wait;\n\t\t\t} else if (this.#sublimitPromise) {\n\t\t\t\t// Stall requests while the sublimit queue gets processed\n\t\t\t\tawait this.#sublimitPromise.promise;\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t// Make the request, and return the results\n\t\t\treturn await this.runRequest(routeId, url, options, requestData);\n\t\t} finally {\n\t\t\t// Allow the next request to fire\n\t\t\tqueue.shift();\n\t\t\tif (this.#shiftSublimit) {\n\t\t\t\tthis.#shiftSublimit = false;\n\t\t\t\tthis.#sublimitedQueue?.shift();\n\t\t\t}\n\n\t\t\t// If this request is the last request in a sublimit\n\t\t\tif (this.#sublimitedQueue?.remaining === 0) {\n\t\t\t\tthis.#sublimitPromise?.resolve();\n\t\t\t\tthis.#sublimitedQueue = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * The method that actually makes the request to the api, and updates info about the bucket accordingly\n\t *\n\t * @param routeId - The generalized api route with literal ids for major parameters\n\t * @param url - The fully resolved url to make the request to\n\t * @param options - The fetch options needed to make the request\n\t * @param requestData - Extra data from the user's request needed for errors and additional processing\n\t * @param retries - The number of retries this request has already attempted (recursion)\n\t */\n\tprivate async runRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t\tretries = 0,\n\t): Promise {\n\t\t/*\n\t\t * After calculations have been done, pre-emptively stop further requests\n\t\t * Potentially loop until this task can run if e.g. the global rate limit is hit twice\n\t\t */\n\t\twhile (this.limited) {\n\t\t\tconst isGlobal = this.globalLimited;\n\t\t\tlet limit: number;\n\t\t\tlet timeout: number;\n\t\t\tlet delay: Promise;\n\n\t\t\tif (isGlobal) {\n\t\t\t\t// Set RateLimitData based on the global limit\n\t\t\t\tlimit = this.manager.options.globalRequestsPerSecond;\n\t\t\t\ttimeout = this.manager.globalReset + this.manager.options.offset - Date.now();\n\t\t\t\t// If this is the first task to reach the global timeout, set the global delay\n\t\t\t\tif (!this.manager.globalDelay) {\n\t\t\t\t\t// The global delay function clears the global delay state when it is resolved\n\t\t\t\t\tthis.manager.globalDelay = this.globalDelayFor(timeout);\n\t\t\t\t}\n\n\t\t\t\tdelay = this.manager.globalDelay;\n\t\t\t} else {\n\t\t\t\t// Set RateLimitData based on the route-specific limit\n\t\t\t\tlimit = this.limit;\n\t\t\t\ttimeout = this.timeToReset;\n\t\t\t\tdelay = sleep(timeout);\n\t\t\t}\n\n\t\t\tconst rateLimitData: RateLimitData = {\n\t\t\t\ttimeToReset: timeout,\n\t\t\t\tlimit,\n\t\t\t\tmethod: options.method ?? 'get',\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t};\n\t\t\t// Let library users know they have hit a rate limit\n\t\t\tthis.manager.emit(RESTEvents.RateLimited, rateLimitData);\n\t\t\t// Determine whether a RateLimitError should be thrown\n\t\t\tawait onRateLimit(this.manager, rateLimitData);\n\t\t\t// When not erroring, emit debug for what is happening\n\t\t\tif (isGlobal) {\n\t\t\t\tthis.debug(`Global rate limit hit, blocking all requests for ${timeout}ms`);\n\t\t\t} else {\n\t\t\t\tthis.debug(`Waiting ${timeout}ms for rate limit to pass`);\n\t\t\t}\n\n\t\t\t// Wait the remaining time left before the rate limit resets\n\t\t\tawait delay;\n\t\t}\n\n\t\t// As the request goes out, update the global usage information\n\t\tif (!this.manager.globalReset || this.manager.globalReset < Date.now()) {\n\t\t\tthis.manager.globalReset = Date.now() + 1_000;\n\t\t\tthis.manager.globalRemaining = this.manager.options.globalRequestsPerSecond;\n\t\t}\n\n\t\tthis.manager.globalRemaining--;\n\n\t\tconst method = options.method ?? 'get';\n\n\t\tconst res = await makeNetworkRequest(this.manager, routeId, url, options, requestData, retries);\n\n\t\t// Retry requested\n\t\tif (res === null) {\n\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t}\n\n\t\tconst status = res.statusCode;\n\t\tlet retryAfter = 0;\n\n\t\tconst limit = parseHeader(res.headers['x-ratelimit-limit']);\n\t\tconst remaining = parseHeader(res.headers['x-ratelimit-remaining']);\n\t\tconst reset = parseHeader(res.headers['x-ratelimit-reset-after']);\n\t\tconst hash = parseHeader(res.headers['x-ratelimit-bucket']);\n\t\tconst retry = parseHeader(res.headers['retry-after']);\n\n\t\t// Update the total number of requests that can be made before the rate limit resets\n\t\tthis.limit = limit ? Number(limit) : Number.POSITIVE_INFINITY;\n\t\t// Update the number of remaining requests that can be made before the rate limit resets\n\t\tthis.remaining = remaining ? Number(remaining) : 1;\n\t\t// Update the time when this rate limit resets (reset-after is in seconds)\n\t\tthis.reset = reset ? Number(reset) * 1_000 + Date.now() + this.manager.options.offset : Date.now();\n\n\t\t// Amount of time in milliseconds until we should retry if rate limited (globally or otherwise)\n\t\tif (retry) retryAfter = Number(retry) * 1_000 + this.manager.options.offset;\n\n\t\t// Handle buckets via the hash header retroactively\n\t\tif (hash && hash !== this.hash) {\n\t\t\t// Let library users know when rate limit buckets have been updated\n\t\t\tthis.debug(['Received bucket hash update', ` Old Hash : ${this.hash}`, ` New Hash : ${hash}`].join('\\n'));\n\t\t\t// This queue will eventually be eliminated via attrition\n\t\t\tthis.manager.hashes.set(`${method}:${routeId.bucketRoute}`, { value: hash, lastAccess: Date.now() });\n\t\t} else if (hash) {\n\t\t\t// Handle the case where hash value doesn't change\n\t\t\t// Fetch the hash data from the manager\n\t\t\tconst hashData = this.manager.hashes.get(`${method}:${routeId.bucketRoute}`);\n\n\t\t\t// When fetched, update the last access of the hash\n\t\t\tif (hashData) {\n\t\t\t\thashData.lastAccess = Date.now();\n\t\t\t}\n\t\t}\n\n\t\t// Handle retryAfter, which means we have actually hit a rate limit\n\t\tlet sublimitTimeout: number | null = null;\n\t\tif (retryAfter > 0) {\n\t\t\tif (res.headers['x-ratelimit-global'] !== undefined) {\n\t\t\t\tthis.manager.globalRemaining = 0;\n\t\t\t\tthis.manager.globalReset = Date.now() + retryAfter;\n\t\t\t} else if (!this.localLimited) {\n\t\t\t\t/*\n\t\t\t\t * This is a sublimit (e.g. 2 channel name changes/10 minutes) since the headers don't indicate a\n\t\t\t\t * route-wide rate limit. Don't update remaining or reset to avoid rate limiting the whole\n\t\t\t\t * endpoint, just set a reset time on the request itself to avoid retrying too soon.\n\t\t\t\t */\n\t\t\t\tsublimitTimeout = retryAfter;\n\t\t\t}\n\t\t}\n\n\t\t// Count the invalid requests\n\t\tif (status === 401 || status === 403 || status === 429) {\n\t\t\tincrementInvalidCount(this.manager);\n\t\t}\n\n\t\tif (status >= 200 && status < 300) {\n\t\t\treturn res;\n\t\t} else if (status === 429) {\n\t\t\t// A rate limit was hit - this may happen if the route isn't associated with an official bucket hash yet, or when first globally rate limited\n\t\t\tconst isGlobal = this.globalLimited;\n\t\t\tlet limit: number;\n\t\t\tlet timeout: number;\n\n\t\t\tif (isGlobal) {\n\t\t\t\t// Set RateLimitData based on the global limit\n\t\t\t\tlimit = this.manager.options.globalRequestsPerSecond;\n\t\t\t\ttimeout = this.manager.globalReset + this.manager.options.offset - Date.now();\n\t\t\t} else {\n\t\t\t\t// Set RateLimitData based on the route-specific limit\n\t\t\t\tlimit = this.limit;\n\t\t\t\ttimeout = this.timeToReset;\n\t\t\t}\n\n\t\t\tawait onRateLimit(this.manager, {\n\t\t\t\ttimeToReset: timeout,\n\t\t\t\tlimit,\n\t\t\t\tmethod,\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t});\n\t\t\tthis.debug(\n\t\t\t\t[\n\t\t\t\t\t'Encountered unexpected 429 rate limit',\n\t\t\t\t\t` Global : ${isGlobal.toString()}`,\n\t\t\t\t\t` Method : ${method}`,\n\t\t\t\t\t` URL : ${url}`,\n\t\t\t\t\t` Bucket : ${routeId.bucketRoute}`,\n\t\t\t\t\t` Major parameter: ${routeId.majorParameter}`,\n\t\t\t\t\t` Hash : ${this.hash}`,\n\t\t\t\t\t` Limit : ${limit}`,\n\t\t\t\t\t` Retry After : ${retryAfter}ms`,\n\t\t\t\t\t` Sublimit : ${sublimitTimeout ? `${sublimitTimeout}ms` : 'None'}`,\n\t\t\t\t].join('\\n'),\n\t\t\t);\n\t\t\t// If caused by a sublimit, wait it out here so other requests on the route can be handled\n\t\t\tif (sublimitTimeout) {\n\t\t\t\t// Normally the sublimit queue will not exist, however, if a sublimit is hit while in the sublimit queue, it will\n\t\t\t\tconst firstSublimit = !this.#sublimitedQueue;\n\t\t\t\tif (firstSublimit) {\n\t\t\t\t\tthis.#sublimitedQueue = new AsyncQueue();\n\t\t\t\t\tvoid this.#sublimitedQueue.wait();\n\t\t\t\t\tthis.#asyncQueue.shift();\n\t\t\t\t}\n\n\t\t\t\tthis.#sublimitPromise?.resolve();\n\t\t\t\tthis.#sublimitPromise = null;\n\t\t\t\tawait sleep(sublimitTimeout);\n\t\t\t\tlet resolve: () => void;\n\t\t\t\t// eslint-disable-next-line promise/param-names, no-promise-executor-return\n\t\t\t\tconst promise = new Promise((res) => (resolve = res));\n\t\t\t\tthis.#sublimitPromise = { promise, resolve: resolve! };\n\t\t\t\tif (firstSublimit) {\n\t\t\t\t\t// Re-queue this request so it can be shifted by the finally\n\t\t\t\t\tawait this.#asyncQueue.wait();\n\t\t\t\t\tthis.#shiftSublimit = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Since this is not a server side issue, the next request should pass, so we don't bump the retries counter\n\t\t\treturn this.runRequest(routeId, url, options, requestData, retries);\n\t\t} else {\n\t\t\tconst handled = await handleErrors(this.manager, res, method, url, requestData, retries);\n\t\t\tif (handled === null) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t\t}\n\n\t\t\treturn handled;\n\t\t}\n\t}\n}\n","import { EventEmitter } from 'node:events';\nimport type { Collection } from '@discordjs/collection';\nimport type { request, Dispatcher } from 'undici';\nimport { CDN } from './CDN.js';\nimport {\n\tRequestManager,\n\tRequestMethod,\n\ttype HashData,\n\ttype HandlerRequestData,\n\ttype InternalRequest,\n\ttype RequestData,\n\ttype RouteLike,\n} from './RequestManager.js';\nimport type { IHandler } from './handlers/IHandler.js';\nimport { DefaultRestOptions, RESTEvents } from './utils/constants.js';\nimport { parseResponse } from './utils/utils.js';\n\n/**\n * Options to be passed when creating the REST instance\n */\nexport interface RESTOptions {\n\t/**\n\t * The agent to set globally\n\t */\n\tagent: Dispatcher;\n\t/**\n\t * The base api path, without version\n\t *\n\t * @defaultValue `'https://discord.com/api'`\n\t */\n\tapi: string;\n\t/**\n\t * The authorization prefix to use for requests, useful if you want to use\n\t * bearer tokens\n\t *\n\t * @defaultValue `'Bot'`\n\t */\n\tauthPrefix: 'Bearer' | 'Bot';\n\t/**\n\t * The cdn path\n\t *\n\t * @defaultValue 'https://cdn.discordapp.com'\n\t */\n\tcdn: string;\n\t/**\n\t * How many requests to allow sending per second (Infinity for unlimited, 50 for the standard global limit used by Discord)\n\t *\n\t * @defaultValue `50`\n\t */\n\tglobalRequestsPerSecond: number;\n\t/**\n\t * The amount of time in milliseconds that passes between each hash sweep. (defaults to 1h)\n\t *\n\t * @defaultValue `3_600_000`\n\t */\n\thandlerSweepInterval: number;\n\t/**\n\t * The maximum amount of time a hash can exist in milliseconds without being hit with a request (defaults to 24h)\n\t *\n\t * @defaultValue `86_400_000`\n\t */\n\thashLifetime: number;\n\t/**\n\t * The amount of time in milliseconds that passes between each hash sweep. (defaults to 4h)\n\t *\n\t * @defaultValue `14_400_000`\n\t */\n\thashSweepInterval: number;\n\t/**\n\t * Additional headers to send for all API requests\n\t *\n\t * @defaultValue `{}`\n\t */\n\theaders: Record;\n\t/**\n\t * The number of invalid REST requests (those that return 401, 403, or 429) in a 10 minute window between emitted warnings (0 for no warnings).\n\t * That is, if set to 500, warnings will be emitted at invalid request number 500, 1000, 1500, and so on.\n\t *\n\t * @defaultValue `0`\n\t */\n\tinvalidRequestWarningInterval: number;\n\t/**\n\t * The extra offset to add to rate limits in milliseconds\n\t *\n\t * @defaultValue `50`\n\t */\n\toffset: number;\n\t/**\n\t * Determines how rate limiting and pre-emptive throttling should be handled.\n\t * When an array of strings, each element is treated as a prefix for the request route\n\t * (e.g. `/channels` to match any route starting with `/channels` such as `/channels/:id/messages`)\n\t * for which to throw {@link RateLimitError}s. All other request routes will be queued normally\n\t *\n\t * @defaultValue `null`\n\t */\n\trejectOnRateLimit: RateLimitQueueFilter | string[] | null;\n\t/**\n\t * The number of retries for errors with the 500 code, or errors\n\t * that timeout\n\t *\n\t * @defaultValue `3`\n\t */\n\tretries: number;\n\t/**\n\t * The time to wait in milliseconds before a request is aborted\n\t *\n\t * @defaultValue `15_000`\n\t */\n\ttimeout: number;\n\t/**\n\t * Extra information to add to the user agent\n\t *\n\t * @defaultValue DefaultUserAgentAppendix\n\t */\n\tuserAgentAppendix: string;\n\t/**\n\t * The version of the API to use\n\t *\n\t * @defaultValue `'10'`\n\t */\n\tversion: string;\n}\n\n/**\n * Data emitted on `RESTEvents.RateLimited`\n */\nexport interface RateLimitData {\n\t/**\n\t * Whether the rate limit that was reached was the global limit\n\t */\n\tglobal: boolean;\n\t/**\n\t * The bucket hash for this request\n\t */\n\thash: string;\n\t/**\n\t * The amount of requests we can perform before locking requests\n\t */\n\tlimit: number;\n\t/**\n\t * The major parameter of the route\n\t *\n\t * For example, in `/channels/x`, this will be `x`.\n\t * If there is no major parameter (e.g: `/bot/gateway`) this will be `global`.\n\t */\n\tmajorParameter: string;\n\t/**\n\t * The HTTP method being performed\n\t */\n\tmethod: string;\n\t/**\n\t * The route being hit in this request\n\t */\n\troute: string;\n\t/**\n\t * The time, in milliseconds, until the request-lock is reset\n\t */\n\ttimeToReset: number;\n\t/**\n\t * The full URL for this request\n\t */\n\turl: string;\n}\n\n/**\n * A function that determines whether the rate limit hit should throw an Error\n */\nexport type RateLimitQueueFilter = (rateLimitData: RateLimitData) => Promise | boolean;\n\nexport interface APIRequest {\n\t/**\n\t * The data that was used to form the body of this request\n\t */\n\tdata: HandlerRequestData;\n\t/**\n\t * The HTTP method used in this request\n\t */\n\tmethod: string;\n\t/**\n\t * Additional HTTP options for this request\n\t */\n\toptions: RequestOptions;\n\t/**\n\t * The full path used to make the request\n\t */\n\tpath: RouteLike;\n\t/**\n\t * The number of times this request has been attempted\n\t */\n\tretries: number;\n\t/**\n\t * The API route identifying the ratelimit for this request\n\t */\n\troute: string;\n}\n\nexport interface InvalidRequestWarningData {\n\t/**\n\t * Number of invalid requests that have been made in the window\n\t */\n\tcount: number;\n\t/**\n\t * Time in milliseconds remaining before the count resets\n\t */\n\tremainingTime: number;\n}\n\nexport interface RestEvents {\n\thandlerSweep: [sweptHandlers: Collection];\n\thashSweep: [sweptHashes: Collection];\n\tinvalidRequestWarning: [invalidRequestInfo: InvalidRequestWarningData];\n\tnewListener: [name: string, listener: (...args: any) => void];\n\trateLimited: [rateLimitInfo: RateLimitData];\n\tremoveListener: [name: string, listener: (...args: any) => void];\n\tresponse: [request: APIRequest, response: Dispatcher.ResponseData];\n\trestDebug: [info: string];\n}\n\nexport interface REST {\n\temit: ((event: K, ...args: RestEvents[K]) => boolean) &\n\t\t((event: Exclude, ...args: any[]) => boolean);\n\n\toff: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\ton: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tonce: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tremoveAllListeners: ((event?: K) => this) &\n\t\t((event?: Exclude) => this);\n}\n\nexport type RequestOptions = Exclude[1], undefined>;\n\nexport class REST extends EventEmitter {\n\tpublic readonly cdn: CDN;\n\n\tpublic readonly requestManager: RequestManager;\n\n\tpublic constructor(options: Partial = {}) {\n\t\tsuper();\n\t\tthis.cdn = new CDN(options.cdn ?? DefaultRestOptions.cdn);\n\t\tthis.requestManager = new RequestManager(options)\n\t\t\t.on(RESTEvents.Debug, this.emit.bind(this, RESTEvents.Debug))\n\t\t\t.on(RESTEvents.RateLimited, this.emit.bind(this, RESTEvents.RateLimited))\n\t\t\t.on(RESTEvents.InvalidRequestWarning, this.emit.bind(this, RESTEvents.InvalidRequestWarning))\n\t\t\t.on(RESTEvents.HashSweep, this.emit.bind(this, RESTEvents.HashSweep));\n\n\t\tthis.on('newListener', (name, listener) => {\n\t\t\tif (name === RESTEvents.Response) this.requestManager.on(name, listener);\n\t\t});\n\t\tthis.on('removeListener', (name, listener) => {\n\t\t\tif (name === RESTEvents.Response) this.requestManager.off(name, listener);\n\t\t});\n\t}\n\n\t/**\n\t * Gets the agent set for this instance\n\t */\n\tpublic getAgent() {\n\t\treturn this.requestManager.agent;\n\t}\n\n\t/**\n\t * Sets the default agent to use for requests performed by this instance\n\t *\n\t * @param agent - Sets the agent to use\n\t */\n\tpublic setAgent(agent: Dispatcher) {\n\t\tthis.requestManager.setAgent(agent);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the authorization token that should be used for requests\n\t *\n\t * @param token - The authorization token to use\n\t */\n\tpublic setToken(token: string) {\n\t\tthis.requestManager.setToken(token);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a get request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async get(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Get });\n\t}\n\n\t/**\n\t * Runs a delete request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async delete(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Delete });\n\t}\n\n\t/**\n\t * Runs a post request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async post(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Post });\n\t}\n\n\t/**\n\t * Runs a put request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async put(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Put });\n\t}\n\n\t/**\n\t * Runs a patch request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async patch(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Patch });\n\t}\n\n\t/**\n\t * Runs a request from the api\n\t *\n\t * @param options - Request options\n\t */\n\tpublic async request(options: InternalRequest) {\n\t\tconst response = await this.raw(options);\n\t\treturn parseResponse(response);\n\t}\n\n\t/**\n\t * Runs a request from the API, yielding the raw Response object\n\t *\n\t * @param options - Request options\n\t */\n\tpublic async raw(options: InternalRequest) {\n\t\treturn this.requestManager.queueRequest(options);\n\t}\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA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,EAAE,GAAG,SAAS,WAAW,wBAA0B,CAAC;AAAA,EACzE;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQA,MAAa,MAAM,WAAsB,UAAuB,CAAC,GAAG;AACnE,WAAO,KAAK,QAAQ,EAAE,GAAG,SAAS,WAAW,4BAA4B,CAAC;AAAA,EAC3E;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAa,QAAQ,SAA0B;AAC9C,UAAM,WAAW,MAAM,KAAK,IAAI,OAAO;AACvC,WAAO,cAAc,QAAQ;AAAA,EAC9B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAa,IAAI,SAA0B;AAC1C,WAAO,KAAK,eAAe,aAAa,OAAO;AAAA,EAChD;AACD;AArHa;;;AX/NN,IAAM,UAAU;","names":["process","RESTEvents","import_node_buffer","import_node_timers","import_undici","import_node_url","import_undici","import_undici","sleep","import_promises","sleep","limit","res","RequestMethod","request","import_node_events"]} \ No newline at end of file diff --git a/node_modules/@discordjs/rest/dist/index.mjs b/node_modules/@discordjs/rest/dist/index.mjs index 053523a..850f466 100644 --- a/node_modules/@discordjs/rest/dist/index.mjs +++ b/node_modules/@discordjs/rest/dist/index.mjs @@ -8,7 +8,8 @@ import { URL } from "node:url"; import process from "node:process"; import { APIVersion } from "discord-api-types/v10"; import { Agent } from "undici"; -var DefaultUserAgent = `DiscordBot (https://discord.js.org, 1.5.0)`; +var DefaultUserAgent = `DiscordBot (https://discord.js.org, 1.7.1)`; +var DefaultUserAgentAppendix = process.release?.name === "node" ? `Node.js/${process.version}` : ""; var DefaultRestOptions = { get agent() { return new Agent({ @@ -27,11 +28,14 @@ var DefaultRestOptions = { rejectOnRateLimit: null, retries: 3, timeout: 15e3, - userAgentAppendix: `Node.js ${process.version}`, + userAgentAppendix: DefaultUserAgentAppendix, version: APIVersion, hashSweepInterval: 144e5, + // 4 Hours hashLifetime: 864e5, + // 24 Hours handlerSweepInterval: 36e5 + // 1 Hour }; var RESTEvents = /* @__PURE__ */ ((RESTEvents2) => { RESTEvents2["Debug"] = "restDebug"; @@ -43,71 +47,204 @@ var RESTEvents = /* @__PURE__ */ ((RESTEvents2) => { return RESTEvents2; })(RESTEvents || {}); var ALLOWED_EXTENSIONS = ["webp", "png", "jpg", "jpeg", "gif"]; -var ALLOWED_STICKER_EXTENSIONS = ["png", "json"]; +var ALLOWED_STICKER_EXTENSIONS = ["png", "json", "gif"]; var ALLOWED_SIZES = [16, 32, 64, 128, 256, 512, 1024, 2048, 4096]; +var OverwrittenMimeTypes = { + // https://github.com/discordjs/discord.js/issues/8557 + "image/apng": "image/png" +}; +var BurstHandlerMajorIdKey = "burst"; // src/lib/CDN.ts var CDN = class { constructor(base = DefaultRestOptions.cdn) { this.base = base; } + /** + * Generates an app asset URL for a client's asset. + * + * @param clientId - The client id that has the asset + * @param assetHash - The hash provided by Discord for this asset + * @param options - Optional options for the asset + */ appAsset(clientId, assetHash, options) { return this.makeURL(`/app-assets/${clientId}/${assetHash}`, options); } + /** + * Generates an app icon URL for a client's icon. + * + * @param clientId - The client id that has the icon + * @param iconHash - The hash provided by Discord for this icon + * @param options - Optional options for the icon + */ appIcon(clientId, iconHash, options) { return this.makeURL(`/app-icons/${clientId}/${iconHash}`, options); } + /** + * Generates an avatar URL, e.g. for a user or a webhook. + * + * @param id - The id that has the icon + * @param avatarHash - The hash provided by Discord for this avatar + * @param options - Optional options for the avatar + */ avatar(id, avatarHash, options) { return this.dynamicMakeURL(`/avatars/${id}/${avatarHash}`, avatarHash, options); } + /** + * Generates a banner URL, e.g. for a user or a guild. + * + * @param id - The id that has the banner splash + * @param bannerHash - The hash provided by Discord for this banner + * @param options - Optional options for the banner + */ banner(id, bannerHash, options) { return this.dynamicMakeURL(`/banners/${id}/${bannerHash}`, bannerHash, options); } + /** + * Generates an icon URL for a channel, e.g. a group DM. + * + * @param channelId - The channel id that has the icon + * @param iconHash - The hash provided by Discord for this channel + * @param options - Optional options for the icon + */ channelIcon(channelId, iconHash, options) { return this.makeURL(`/channel-icons/${channelId}/${iconHash}`, options); } + /** + * Generates the default avatar URL for a discriminator. + * + * @param discriminator - The discriminator modulo 5 + */ defaultAvatar(discriminator) { return this.makeURL(`/embed/avatars/${discriminator}`, { extension: "png" }); } + /** + * Generates a discovery splash URL for a guild's discovery splash. + * + * @param guildId - The guild id that has the discovery splash + * @param splashHash - The hash provided by Discord for this splash + * @param options - Optional options for the splash + */ discoverySplash(guildId, splashHash, options) { return this.makeURL(`/discovery-splashes/${guildId}/${splashHash}`, options); } + /** + * Generates an emoji's URL for an emoji. + * + * @param emojiId - The emoji id + * @param extension - The extension of the emoji + */ emoji(emojiId, extension) { return this.makeURL(`/emojis/${emojiId}`, { extension }); } + /** + * Generates a guild member avatar URL. + * + * @param guildId - The id of the guild + * @param userId - The id of the user + * @param avatarHash - The hash provided by Discord for this avatar + * @param options - Optional options for the avatar + */ guildMemberAvatar(guildId, userId, avatarHash, options) { return this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/avatars/${avatarHash}`, avatarHash, options); } + /** + * Generates a guild member banner URL. + * + * @param guildId - The id of the guild + * @param userId - The id of the user + * @param bannerHash - The hash provided by Discord for this banner + * @param options - Optional options for the banner + */ guildMemberBanner(guildId, userId, bannerHash, options) { return this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/banner`, bannerHash, options); } + /** + * Generates an icon URL, e.g. for a guild. + * + * @param id - The id that has the icon splash + * @param iconHash - The hash provided by Discord for this icon + * @param options - Optional options for the icon + */ icon(id, iconHash, options) { return this.dynamicMakeURL(`/icons/${id}/${iconHash}`, iconHash, options); } + /** + * Generates a URL for the icon of a role + * + * @param roleId - The id of the role that has the icon + * @param roleIconHash - The hash provided by Discord for this role icon + * @param options - Optional options for the role icon + */ roleIcon(roleId, roleIconHash, options) { return this.makeURL(`/role-icons/${roleId}/${roleIconHash}`, options); } + /** + * Generates a guild invite splash URL for a guild's invite splash. + * + * @param guildId - The guild id that has the invite splash + * @param splashHash - The hash provided by Discord for this splash + * @param options - Optional options for the splash + */ splash(guildId, splashHash, options) { return this.makeURL(`/splashes/${guildId}/${splashHash}`, options); } - sticker(stickerId, extension) { - return this.makeURL(`/stickers/${stickerId}`, { - allowedExtensions: ALLOWED_STICKER_EXTENSIONS, - extension: extension ?? "png" - }); - } + /** + * Generates a sticker URL. + * + * @param stickerId - The sticker id + * @param extension - The extension of the sticker + * @privateRemarks + * Stickers cannot have a `.webp` extension, so we default to a `.png` + */ + sticker(stickerId, extension = "png") { + return this.makeURL(`/stickers/${stickerId}`, { allowedExtensions: ALLOWED_STICKER_EXTENSIONS, extension }); + } + /** + * Generates a sticker pack banner URL. + * + * @param bannerId - The banner id + * @param options - Optional options for the banner + */ stickerPackBanner(bannerId, options) { return this.makeURL(`/app-assets/710982414301790216/store/${bannerId}`, options); } + /** + * Generates a team icon URL for a team's icon. + * + * @param teamId - The team id that has the icon + * @param iconHash - The hash provided by Discord for this icon + * @param options - Optional options for the icon + */ teamIcon(teamId, iconHash, options) { return this.makeURL(`/team-icons/${teamId}/${iconHash}`, options); } + /** + * Generates a cover image for a guild scheduled event. + * + * @param scheduledEventId - The scheduled event id + * @param coverHash - The hash provided by discord for this cover image + * @param options - Optional options for the cover image + */ guildScheduledEventCover(scheduledEventId, coverHash, options) { return this.makeURL(`/guild-events/${scheduledEventId}/${coverHash}`, options); } + /** + * Constructs the URL for the resource, checking whether or not `hash` starts with `a_` if `dynamic` is set to `true`. + * + * @param route - The base cdn route + * @param hash - The hash provided by Discord for this icon + * @param options - Optional options for the link + */ dynamicMakeURL(route, hash, { forceStatic = false, ...options } = {}) { return this.makeURL(route, !forceStatic && hash.startsWith("a_") ? { ...options, extension: "gif" } : options); } + /** + * Constructs the URL for the resource + * + * @param route - The base cdn route + * @param options - The extension/size options for the link + */ makeURL(route, { allowedExtensions = ALLOWED_EXTENSIONS, extension = "webp", size } = {}) { extension = String(extension).toLowerCase(); if (!allowedExtensions.includes(extension)) { @@ -137,6 +274,14 @@ function isErrorResponse(error) { } __name(isErrorResponse, "isErrorResponse"); var DiscordAPIError = class extends Error { + /** + * @param rawError - The error reported by Discord + * @param code - The error code reported by Discord + * @param status - The status code of the response + * @param method - The method of the request that erred + * @param url - The url of the request that erred + * @param bodyData - The unparsed data for the request that errored + */ constructor(rawError, code, status, method, url, bodyData) { super(DiscordAPIError.getMessage(rawError)); this.rawError = rawError; @@ -147,6 +292,9 @@ var DiscordAPIError = class extends Error { this.requestBody = { files: bodyData.files, json: bodyData.body }; } requestBody; + /** + * The name of the error + */ get name() { return `${DiscordAPIError.name}[${this.code}]`; } @@ -184,6 +332,12 @@ __name(DiscordAPIError, "DiscordAPIError"); // src/lib/errors/HTTPError.ts import { STATUS_CODES } from "node:http"; var HTTPError = class extends Error { + /** + * @param status - The status code of the response + * @param method - The method of the request that erred + * @param url - The url of the request that erred + * @param bodyData - The unparsed data for the request that errored + */ constructor(status, method, url, bodyData) { super(STATUS_CODES[status]); this.status = status; @@ -217,6 +371,9 @@ var RateLimitError = class extends Error { this.majorParameter = majorParameter; this.global = global; } + /** + * The name of the error + */ get name() { return `${RateLimitError.name}[${this.route}]`; } @@ -232,11 +389,8 @@ import { lazy } from "@discordjs/util"; import { DiscordSnowflake } from "@sapphire/snowflake"; import { FormData as FormData2 } from "undici"; -// src/lib/handlers/SequentialHandler.ts -import { setTimeout, clearTimeout } from "node:timers"; +// src/lib/handlers/BurstHandler.ts import { setTimeout as sleep } from "node:timers/promises"; -import { AsyncQueue } from "@sapphire/async-queue"; -import { request } from "undici"; // src/lib/utils/utils.ts import { Blob, Buffer as Buffer2 } from "node:buffer"; @@ -347,56 +501,293 @@ function shouldRetry(error) { return "code" in error && error.code === "ECONNRESET" || error.message.includes("ECONNRESET"); } __name(shouldRetry, "shouldRetry"); +async function onRateLimit(manager, rateLimitData) { + const { options } = manager; + if (!options.rejectOnRateLimit) + return; + const shouldThrow = typeof options.rejectOnRateLimit === "function" ? await options.rejectOnRateLimit(rateLimitData) : options.rejectOnRateLimit.some((route) => rateLimitData.route.startsWith(route.toLowerCase())); + if (shouldThrow) { + throw new RateLimitError(rateLimitData); + } +} +__name(onRateLimit, "onRateLimit"); -// src/lib/handlers/SequentialHandler.ts +// src/lib/handlers/Shared.ts +import { setTimeout, clearTimeout } from "node:timers"; +import { request } from "undici"; var invalidCount = 0; var invalidCountResetTime = null; +function incrementInvalidCount(manager) { + if (!invalidCountResetTime || invalidCountResetTime < Date.now()) { + invalidCountResetTime = Date.now() + 1e3 * 60 * 10; + invalidCount = 0; + } + invalidCount++; + const emitInvalid = manager.options.invalidRequestWarningInterval > 0 && invalidCount % manager.options.invalidRequestWarningInterval === 0; + if (emitInvalid) { + manager.emit("invalidRequestWarning" /* InvalidRequestWarning */, { + count: invalidCount, + remainingTime: invalidCountResetTime - Date.now() + }); + } +} +__name(incrementInvalidCount, "incrementInvalidCount"); +async function makeNetworkRequest(manager, routeId, url, options, requestData, retries) { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), manager.options.timeout).unref(); + if (requestData.signal) { + const signal = requestData.signal; + if (signal.aborted) + controller.abort(); + else + signal.addEventListener("abort", () => controller.abort()); + } + let res; + try { + res = await request(url, { ...options, signal: controller.signal }); + } catch (error) { + if (!(error instanceof Error)) + throw error; + if (shouldRetry(error) && retries !== manager.options.retries) { + return null; + } + throw error; + } finally { + clearTimeout(timeout); + } + if (manager.listenerCount("response" /* Response */)) { + manager.emit( + "response" /* Response */, + { + method: options.method ?? "get", + path: routeId.original, + route: routeId.bucketRoute, + options, + data: requestData, + retries + }, + { ...res } + ); + } + return res; +} +__name(makeNetworkRequest, "makeNetworkRequest"); +async function handleErrors(manager, res, method, url, requestData, retries) { + const status = res.statusCode; + if (status >= 500 && status < 600) { + if (retries !== manager.options.retries) { + return null; + } + throw new HTTPError(status, method, url, requestData); + } else { + if (status >= 400 && status < 500) { + if (status === 401 && requestData.auth) { + manager.setToken(null); + } + const data = await parseResponse(res); + throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData); + } + return res; + } +} +__name(handleErrors, "handleErrors"); + +// src/lib/handlers/BurstHandler.ts +var BurstHandler = class { + /** + * @param manager - The request manager + * @param hash - The hash that this RequestHandler handles + * @param majorParameter - The major parameter for this handler + */ + constructor(manager, hash, majorParameter) { + this.manager = manager; + this.hash = hash; + this.majorParameter = majorParameter; + this.id = `${hash}:${majorParameter}`; + } + /** + * {@inheritdoc IHandler.id} + */ + id; + /** + * {@inheritDoc IHandler.inactive} + */ + inactive = false; + /** + * Emits a debug message + * + * @param message - The message to debug + */ + debug(message) { + this.manager.emit("restDebug" /* Debug */, `[REST ${this.id}] ${message}`); + } + /** + * {@inheritDoc IHandler.queueRequest} + */ + async queueRequest(routeId, url, options, requestData) { + return this.runRequest(routeId, url, options, requestData); + } + /** + * The method that actually makes the request to the API, and updates info about the bucket accordingly + * + * @param routeId - The generalized API route with literal ids for major parameters + * @param url - The fully resolved URL to make the request to + * @param options - The fetch options needed to make the request + * @param requestData - Extra data from the user's request needed for errors and additional processing + * @param retries - The number of retries this request has already attempted (recursion) + */ + async runRequest(routeId, url, options, requestData, retries = 0) { + const method = options.method ?? "get"; + const res = await makeNetworkRequest(this.manager, routeId, url, options, requestData, retries); + if (res === null) { + return this.runRequest(routeId, url, options, requestData, ++retries); + } + const status = res.statusCode; + let retryAfter = 0; + const retry = parseHeader(res.headers["retry-after"]); + if (retry) + retryAfter = Number(retry) * 1e3 + this.manager.options.offset; + if (status === 401 || status === 403 || status === 429) { + incrementInvalidCount(this.manager); + } + if (status >= 200 && status < 300) { + return res; + } else if (status === 429) { + const isGlobal = res.headers["x-ratelimit-global"] !== void 0; + await onRateLimit(this.manager, { + timeToReset: retryAfter, + limit: Number.POSITIVE_INFINITY, + method, + hash: this.hash, + url, + route: routeId.bucketRoute, + majorParameter: this.majorParameter, + global: isGlobal + }); + this.debug( + [ + "Encountered unexpected 429 rate limit", + ` Global : ${isGlobal}`, + ` Method : ${method}`, + ` URL : ${url}`, + ` Bucket : ${routeId.bucketRoute}`, + ` Major parameter: ${routeId.majorParameter}`, + ` Hash : ${this.hash}`, + ` Limit : ${Number.POSITIVE_INFINITY}`, + ` Retry After : ${retryAfter}ms`, + ` Sublimit : None` + ].join("\n") + ); + await sleep(retryAfter); + return this.runRequest(routeId, url, options, requestData, retries); + } else { + const handled = await handleErrors(this.manager, res, method, url, requestData, retries); + if (handled === null) { + return this.runRequest(routeId, url, options, requestData, ++retries); + } + return handled; + } + } +}; +__name(BurstHandler, "BurstHandler"); + +// src/lib/handlers/SequentialHandler.ts +import { setTimeout as sleep2 } from "node:timers/promises"; +import { AsyncQueue } from "@sapphire/async-queue"; var SequentialHandler = class { + /** + * @param manager - The request manager + * @param hash - The hash that this RequestHandler handles + * @param majorParameter - The major parameter for this handler + */ constructor(manager, hash, majorParameter) { this.manager = manager; this.hash = hash; this.majorParameter = majorParameter; this.id = `${hash}:${majorParameter}`; } + /** + * {@inheritDoc IHandler.id} + */ id; + /** + * The time this rate limit bucket will reset + */ reset = -1; + /** + * The remaining requests that can be made before we are rate limited + */ remaining = 1; + /** + * The total number of requests that can be made before we are rate limited + */ limit = Number.POSITIVE_INFINITY; + /** + * The interface used to sequence async requests sequentially + */ #asyncQueue = new AsyncQueue(); + /** + * The interface used to sequence sublimited async requests sequentially + */ #sublimitedQueue = null; + /** + * A promise wrapper for when the sublimited queue is finished being processed or null when not being processed + */ #sublimitPromise = null; + /** + * Whether the sublimit queue needs to be shifted in the finally block + */ #shiftSublimit = false; + /** + * {@inheritDoc IHandler.inactive} + */ get inactive() { return this.#asyncQueue.remaining === 0 && (this.#sublimitedQueue === null || this.#sublimitedQueue.remaining === 0) && !this.limited; } + /** + * If the rate limit bucket is currently limited by the global limit + */ get globalLimited() { return this.manager.globalRemaining <= 0 && Date.now() < this.manager.globalReset; } + /** + * If the rate limit bucket is currently limited by its limit + */ get localLimited() { return this.remaining <= 0 && Date.now() < this.reset; } + /** + * If the rate limit bucket is currently limited + */ get limited() { return this.globalLimited || this.localLimited; } + /** + * The time until queued requests can continue + */ get timeToReset() { return this.reset + this.manager.options.offset - Date.now(); } + /** + * Emits a debug message + * + * @param message - The message to debug + */ debug(message) { this.manager.emit("restDebug" /* Debug */, `[REST ${this.id}] ${message}`); } + /** + * Delay all requests for the specified amount of time, handling global rate limits + * + * @param time - The amount of time to delay all requests for + */ async globalDelayFor(time) { - await sleep(time); + await sleep2(time); this.manager.globalDelay = null; } - async onRateLimit(rateLimitData) { - const { options } = this.manager; - if (!options.rejectOnRateLimit) - return; - const shouldThrow = typeof options.rejectOnRateLimit === "function" ? await options.rejectOnRateLimit(rateLimitData) : options.rejectOnRateLimit.some((route) => rateLimitData.route.startsWith(route.toLowerCase())); - if (shouldThrow) { - throw new RateLimitError(rateLimitData); - } - } + /** + * {@inheritDoc IHandler.queueRequest} + */ async queueRequest(routeId, url, options, requestData) { let queue = this.#asyncQueue; let queueType = 0 /* Standard */; @@ -429,26 +820,35 @@ var SequentialHandler = class { } } } + /** + * The method that actually makes the request to the api, and updates info about the bucket accordingly + * + * @param routeId - The generalized api route with literal ids for major parameters + * @param url - The fully resolved url to make the request to + * @param options - The fetch options needed to make the request + * @param requestData - Extra data from the user's request needed for errors and additional processing + * @param retries - The number of retries this request has already attempted (recursion) + */ async runRequest(routeId, url, options, requestData, retries = 0) { while (this.limited) { const isGlobal = this.globalLimited; let limit2; - let timeout2; + let timeout; let delay; if (isGlobal) { limit2 = this.manager.options.globalRequestsPerSecond; - timeout2 = this.manager.globalReset + this.manager.options.offset - Date.now(); + timeout = this.manager.globalReset + this.manager.options.offset - Date.now(); if (!this.manager.globalDelay) { - this.manager.globalDelay = this.globalDelayFor(timeout2); + this.manager.globalDelay = this.globalDelayFor(timeout); } delay = this.manager.globalDelay; } else { limit2 = this.limit; - timeout2 = this.timeToReset; - delay = sleep(timeout2); + timeout = this.timeToReset; + delay = sleep2(timeout); } const rateLimitData = { - timeToReset: timeout2, + timeToReset: timeout, limit: limit2, method: options.method ?? "get", hash: this.hash, @@ -458,11 +858,11 @@ var SequentialHandler = class { global: isGlobal }; this.manager.emit("rateLimited" /* RateLimited */, rateLimitData); - await this.onRateLimit(rateLimitData); + await onRateLimit(this.manager, rateLimitData); if (isGlobal) { - this.debug(`Global rate limit hit, blocking all requests for ${timeout2}ms`); + this.debug(`Global rate limit hit, blocking all requests for ${timeout}ms`); } else { - this.debug(`Waiting ${timeout2}ms for rate limit to pass`); + this.debug(`Waiting ${timeout}ms for rate limit to pass`); } await delay; } @@ -472,41 +872,9 @@ var SequentialHandler = class { } this.manager.globalRemaining--; const method = options.method ?? "get"; - const controller = new AbortController(); - const timeout = setTimeout(() => controller.abort(), this.manager.options.timeout).unref(); - if (requestData.signal) { - const signal = requestData.signal; - if (signal.aborted) - controller.abort(); - else - signal.addEventListener("abort", () => controller.abort()); - } - let res; - try { - res = await request(url, { ...options, signal: controller.signal }); - } catch (error) { - if (!(error instanceof Error)) - throw error; - if (shouldRetry(error) && retries !== this.manager.options.retries) { - return await this.runRequest(routeId, url, options, requestData, ++retries); - } - throw error; - } finally { - clearTimeout(timeout); - } - if (this.manager.listenerCount("response" /* Response */)) { - this.manager.emit( - "response" /* Response */, - { - method, - path: routeId.original, - route: routeId.bucketRoute, - options, - data: requestData, - retries - }, - { ...res } - ); + const res = await makeNetworkRequest(this.manager, routeId, url, options, requestData, retries); + if (res === null) { + return this.runRequest(routeId, url, options, requestData, ++retries); } const status = res.statusCode; let retryAfter = 0; @@ -539,34 +907,23 @@ var SequentialHandler = class { } } if (status === 401 || status === 403 || status === 429) { - if (!invalidCountResetTime || invalidCountResetTime < Date.now()) { - invalidCountResetTime = Date.now() + 1e3 * 60 * 10; - invalidCount = 0; - } - invalidCount++; - const emitInvalid = this.manager.options.invalidRequestWarningInterval > 0 && invalidCount % this.manager.options.invalidRequestWarningInterval === 0; - if (emitInvalid) { - this.manager.emit("invalidRequestWarning" /* InvalidRequestWarning */, { - count: invalidCount, - remainingTime: invalidCountResetTime - Date.now() - }); - } + incrementInvalidCount(this.manager); } if (status >= 200 && status < 300) { return res; } else if (status === 429) { const isGlobal = this.globalLimited; let limit2; - let timeout2; + let timeout; if (isGlobal) { limit2 = this.manager.options.globalRequestsPerSecond; - timeout2 = this.manager.globalReset + this.manager.options.offset - Date.now(); + timeout = this.manager.globalReset + this.manager.options.offset - Date.now(); } else { limit2 = this.limit; - timeout2 = this.timeToReset; + timeout = this.timeToReset; } - await this.onRateLimit({ - timeToReset: timeout2, + await onRateLimit(this.manager, { + timeToReset: timeout, limit: limit2, method, hash: this.hash, @@ -598,7 +955,7 @@ var SequentialHandler = class { } this.#sublimitPromise?.resolve(); this.#sublimitPromise = null; - await sleep(sublimitTimeout); + await sleep2(sublimitTimeout); let resolve; const promise = new Promise((res2) => resolve = res2); this.#sublimitPromise = { promise, resolve }; @@ -608,20 +965,12 @@ var SequentialHandler = class { } } return this.runRequest(routeId, url, options, requestData, retries); - } else if (status >= 500 && status < 600) { - if (retries !== this.manager.options.retries) { - return this.runRequest(routeId, url, options, requestData, ++retries); - } - throw new HTTPError(status, method, url, requestData); } else { - if (status >= 400 && status < 500) { - if (status === 401 && requestData.auth) { - this.manager.setToken(null); - } - const data = await parseResponse(res); - throw new DiscordAPIError(data, "code" in data ? data.code : data.error, status, method, url, requestData); + const handled = await handleErrors(this.manager, res, method, url, requestData, retries); + if (handled === null) { + return this.runRequest(routeId, url, options, requestData, ++retries); } - return res; + return handled; } } }; @@ -638,11 +987,30 @@ var RequestMethod = /* @__PURE__ */ ((RequestMethod2) => { return RequestMethod2; })(RequestMethod || {}); var RequestManager = class extends EventEmitter { + /** + * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} for all requests + * performed by this manager. + */ agent = null; + /** + * The number of requests remaining in the global bucket + */ globalRemaining; + /** + * The promise used to wait out the global rate limit + */ globalDelay = null; + /** + * The timestamp at which the global bucket resets + */ globalReset = -1; + /** + * API bucket hashes that are cached from provided routes + */ hashes = new Collection(); + /** + * Request handlers created from the bucket hash and the major parameters + */ handlers = new Collection(); #token = null; hashTimer; @@ -696,14 +1064,30 @@ var RequestManager = class extends EventEmitter { }, this.options.handlerSweepInterval).unref(); } } + /** + * Sets the default agent to use for requests performed by this manager + * + * @param agent - The agent to use + */ setAgent(agent) { this.agent = agent; return this; } + /** + * Sets the authorization token that should be used for requests + * + * @param token - The authorization token to use + */ setToken(token) { this.#token = token; return this; } + /** + * Queues a request to be sent + * + * @param request - All the information needed to make a request + * @returns The response from the api request + */ async queueRequest(request2) { const routeId = RequestManager.generateRouteData(request2.fullRoute, request2.method); const hash = this.hashes.get(`${request2.method}:${routeId.bucketRoute}`) ?? { @@ -719,11 +1103,23 @@ var RequestManager = class extends EventEmitter { signal: request2.signal }); } + /** + * Creates a new rate limit handler from a hash, based on the hash and the major parameter + * + * @param hash - The hash for the route + * @param majorParameter - The major parameter for this handler + * @internal + */ createHandler(hash, majorParameter) { - const queue = new SequentialHandler(this, hash, majorParameter); + const queue = majorParameter === BurstHandlerMajorIdKey ? new BurstHandler(this, hash, majorParameter) : new SequentialHandler(this, hash, majorParameter); this.handlers.set(queue.id, queue); return queue; } + /** + * Formats the request data to a usable format for fetch + * + * @param request - The request data + */ async resolveRequest(request2) { const { options } = this; let query = ""; @@ -755,7 +1151,13 @@ var RequestManager = class extends EventEmitter { const fileKey = file.key ?? `files[${index}]`; if (Buffer3.isBuffer(file.data)) { const { fileTypeFromBuffer } = await getFileType(); - const contentType = file.contentType ?? (await fileTypeFromBuffer(file.data))?.mime; + let contentType = file.contentType; + if (!contentType) { + const parsedType = (await fileTypeFromBuffer(file.data))?.mime; + if (parsedType) { + contentType = OverwrittenMimeTypes[parsedType] ?? parsedType; + } + } formData.append(fileKey, new Blob2([file.data], { type: contentType }), file.name); } else { formData.append(fileKey, new Blob2([`${file.data}`], { type: file.contentType }), file.name); @@ -790,19 +1192,39 @@ var RequestManager = class extends EventEmitter { fetchOptions.dispatcher = request2.dispatcher ?? this.agent ?? void 0; return { url, fetchOptions }; } + /** + * Stops the hash sweeping interval + */ clearHashSweeper() { clearInterval(this.hashTimer); } + /** + * Stops the request handler sweeping interval + */ clearHandlerSweeper() { clearInterval(this.handlerTimer); } + /** + * Generates route data for an endpoint:method + * + * @param endpoint - The raw endpoint to generalize + * @param method - The HTTP method this endpoint is called without + * @internal + */ static generateRouteData(endpoint, method) { - const majorIdMatch = /^\/(?:channels|guilds|webhooks)\/(\d{16,19})/.exec(endpoint); + if (endpoint.startsWith("/interactions/") && endpoint.endsWith("/callback")) { + return { + majorParameter: BurstHandlerMajorIdKey, + bucketRoute: "/interactions/:id/:token/callback", + original: endpoint + }; + } + const majorIdMatch = /^\/(?:channels|guilds|webhooks)\/(\d{17,19})/.exec(endpoint); const majorId = majorIdMatch?.[1] ?? "global"; - const baseRoute = endpoint.replaceAll(/\d{16,19}/g, ":id").replace(/\/reactions\/(.*)/, "/reactions/:reaction"); + const baseRoute = endpoint.replaceAll(/\d{17,19}/g, ":id").replace(/\/reactions\/(.*)/, "/reactions/:reaction"); let exceptions = ""; if (method === "DELETE" /* Delete */ && baseRoute === "/channels/:id/messages/:id") { - const id = /\d{16,19}$/.exec(endpoint)[0]; + const id = /\d{17,19}$/.exec(endpoint)[0]; const timestamp = DiscordSnowflake.timestampFrom(id); if (Date.now() - timestamp > 1e3 * 60 * 60 * 24 * 14) { exceptions += "/Delete Old Message"; @@ -835,36 +1257,89 @@ var REST = class extends EventEmitter2 { this.requestManager.off(name, listener); }); } + /** + * Gets the agent set for this instance + */ getAgent() { return this.requestManager.agent; } + /** + * Sets the default agent to use for requests performed by this instance + * + * @param agent - Sets the agent to use + */ setAgent(agent) { this.requestManager.setAgent(agent); return this; } + /** + * Sets the authorization token that should be used for requests + * + * @param token - The authorization token to use + */ setToken(token) { this.requestManager.setToken(token); return this; } + /** + * Runs a get request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async get(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "GET" /* Get */ }); } + /** + * Runs a delete request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async delete(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "DELETE" /* Delete */ }); } + /** + * Runs a post request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async post(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "POST" /* Post */ }); } + /** + * Runs a put request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async put(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "PUT" /* Put */ }); } + /** + * Runs a patch request from the api + * + * @param fullRoute - The full route to query + * @param options - Optional request options + */ async patch(fullRoute, options = {}) { return this.request({ ...options, fullRoute, method: "PATCH" /* Patch */ }); } + /** + * Runs a request from the api + * + * @param options - Request options + */ async request(options) { const response = await this.raw(options); return parseResponse(response); } + /** + * Runs a request from the API, yielding the raw Response object + * + * @param options - Request options + */ async raw(options) { return this.requestManager.queueRequest(options); } @@ -872,16 +1347,19 @@ var REST = class extends EventEmitter2 { __name(REST, "REST"); // src/index.ts -var version = "1.5.0"; +var version = "1.7.1"; export { ALLOWED_EXTENSIONS, ALLOWED_SIZES, ALLOWED_STICKER_EXTENSIONS, + BurstHandlerMajorIdKey, CDN, DefaultRestOptions, DefaultUserAgent, + DefaultUserAgentAppendix, DiscordAPIError, HTTPError, + OverwrittenMimeTypes, REST, RESTEvents, RateLimitError, diff --git a/node_modules/@discordjs/rest/dist/index.mjs.map b/node_modules/@discordjs/rest/dist/index.mjs.map index 0ccc6de..85bb8eb 100644 --- a/node_modules/@discordjs/rest/dist/index.mjs.map +++ b/node_modules/@discordjs/rest/dist/index.mjs.map @@ -1 +1 @@ -{"version":3,"sources":["../src/lib/CDN.ts","../src/lib/utils/constants.ts","../src/lib/errors/DiscordAPIError.ts","../src/lib/errors/HTTPError.ts","../src/lib/errors/RateLimitError.ts","../src/lib/RequestManager.ts","../src/lib/handlers/SequentialHandler.ts","../src/lib/utils/utils.ts","../src/lib/REST.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable jsdoc/check-param-names */\nimport { URL } from 'node:url';\nimport {\n\tALLOWED_EXTENSIONS,\n\tALLOWED_SIZES,\n\tALLOWED_STICKER_EXTENSIONS,\n\tDefaultRestOptions,\n\ttype ImageExtension,\n\ttype ImageSize,\n\ttype StickerExtension,\n} from './utils/constants.js';\n\n/**\n * The options used for image URLs\n */\nexport interface BaseImageURLOptions {\n\t/**\n\t * The extension to use for the image URL\n\t *\n\t * @defaultValue `'webp'`\n\t */\n\textension?: ImageExtension;\n\t/**\n\t * The size specified in the image URL\n\t */\n\tsize?: ImageSize;\n}\n\n/**\n * The options used for image URLs with animated content\n */\nexport interface ImageURLOptions extends BaseImageURLOptions {\n\t/**\n\t * Whether or not to prefer the static version of an image asset.\n\t */\n\tforceStatic?: boolean;\n}\n\n/**\n * The options to use when making a CDN URL\n */\nexport interface MakeURLOptions {\n\t/**\n\t * The allowed extensions that can be used\n\t */\n\tallowedExtensions?: readonly string[];\n\t/**\n\t * The extension to use for the image URL\n\t *\n\t * @defaultValue `'webp'`\n\t */\n\textension?: string | undefined;\n\t/**\n\t * The size specified in the image URL\n\t */\n\tsize?: ImageSize;\n}\n\n/**\n * The CDN link builder\n */\nexport class CDN {\n\tpublic constructor(private readonly base: string = DefaultRestOptions.cdn) {}\n\n\t/**\n\t * Generates an app asset URL for a client's asset.\n\t *\n\t * @param clientId - The client id that has the asset\n\t * @param assetHash - The hash provided by Discord for this asset\n\t * @param options - Optional options for the asset\n\t */\n\tpublic appAsset(clientId: string, assetHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-assets/${clientId}/${assetHash}`, options);\n\t}\n\n\t/**\n\t * Generates an app icon URL for a client's icon.\n\t *\n\t * @param clientId - The client id that has the icon\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic appIcon(clientId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-icons/${clientId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates an avatar URL, e.g. for a user or a webhook.\n\t *\n\t * @param id - The id that has the icon\n\t * @param avatarHash - The hash provided by Discord for this avatar\n\t * @param options - Optional options for the avatar\n\t */\n\tpublic avatar(id: string, avatarHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/avatars/${id}/${avatarHash}`, avatarHash, options);\n\t}\n\n\t/**\n\t * Generates a banner URL, e.g. for a user or a guild.\n\t *\n\t * @param id - The id that has the banner splash\n\t * @param bannerHash - The hash provided by Discord for this banner\n\t * @param options - Optional options for the banner\n\t */\n\tpublic banner(id: string, bannerHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/banners/${id}/${bannerHash}`, bannerHash, options);\n\t}\n\n\t/**\n\t * Generates an icon URL for a channel, e.g. a group DM.\n\t *\n\t * @param channelId - The channel id that has the icon\n\t * @param iconHash - The hash provided by Discord for this channel\n\t * @param options - Optional options for the icon\n\t */\n\tpublic channelIcon(channelId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/channel-icons/${channelId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates the default avatar URL for a discriminator.\n\t *\n\t * @param discriminator - The discriminator modulo 5\n\t */\n\tpublic defaultAvatar(discriminator: number): string {\n\t\treturn this.makeURL(`/embed/avatars/${discriminator}`, { extension: 'png' });\n\t}\n\n\t/**\n\t * Generates a discovery splash URL for a guild's discovery splash.\n\t *\n\t * @param guildId - The guild id that has the discovery splash\n\t * @param splashHash - The hash provided by Discord for this splash\n\t * @param options - Optional options for the splash\n\t */\n\tpublic discoverySplash(guildId: string, splashHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/discovery-splashes/${guildId}/${splashHash}`, options);\n\t}\n\n\t/**\n\t * Generates an emoji's URL for an emoji.\n\t *\n\t * @param emojiId - The emoji id\n\t * @param extension - The extension of the emoji\n\t */\n\tpublic emoji(emojiId: string, extension?: ImageExtension): string {\n\t\treturn this.makeURL(`/emojis/${emojiId}`, { extension });\n\t}\n\n\t/**\n\t * Generates a guild member avatar URL.\n\t *\n\t * @param guildId - The id of the guild\n\t * @param userId - The id of the user\n\t * @param avatarHash - The hash provided by Discord for this avatar\n\t * @param options - Optional options for the avatar\n\t */\n\tpublic guildMemberAvatar(\n\t\tguildId: string,\n\t\tuserId: string,\n\t\tavatarHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/avatars/${avatarHash}`, avatarHash, options);\n\t}\n\n\t/**\n\t * Generates a guild member banner URL.\n\t *\n\t * @param guildId - The id of the guild\n\t * @param userId - The id of the user\n\t * @param bannerHash - The hash provided by Discord for this banner\n\t * @param options - Optional options for the banner\n\t */\n\tpublic guildMemberBanner(\n\t\tguildId: string,\n\t\tuserId: string,\n\t\tbannerHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/banner`, bannerHash, options);\n\t}\n\n\t/**\n\t * Generates an icon URL, e.g. for a guild.\n\t *\n\t * @param id - The id that has the icon splash\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic icon(id: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/icons/${id}/${iconHash}`, iconHash, options);\n\t}\n\n\t/**\n\t * Generates a URL for the icon of a role\n\t *\n\t * @param roleId - The id of the role that has the icon\n\t * @param roleIconHash - The hash provided by Discord for this role icon\n\t * @param options - Optional options for the role icon\n\t */\n\tpublic roleIcon(roleId: string, roleIconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/role-icons/${roleId}/${roleIconHash}`, options);\n\t}\n\n\t/**\n\t * Generates a guild invite splash URL for a guild's invite splash.\n\t *\n\t * @param guildId - The guild id that has the invite splash\n\t * @param splashHash - The hash provided by Discord for this splash\n\t * @param options - Optional options for the splash\n\t */\n\tpublic splash(guildId: string, splashHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/splashes/${guildId}/${splashHash}`, options);\n\t}\n\n\t/**\n\t * Generates a sticker URL.\n\t *\n\t * @param stickerId - The sticker id\n\t * @param extension - The extension of the sticker\n\t */\n\tpublic sticker(stickerId: string, extension?: StickerExtension): string {\n\t\treturn this.makeURL(`/stickers/${stickerId}`, {\n\t\t\tallowedExtensions: ALLOWED_STICKER_EXTENSIONS,\n\t\t\textension: extension ?? 'png', // Stickers cannot have a `.webp` extension, so we default to a `.png`\n\t\t});\n\t}\n\n\t/**\n\t * Generates a sticker pack banner URL.\n\t *\n\t * @param bannerId - The banner id\n\t * @param options - Optional options for the banner\n\t */\n\tpublic stickerPackBanner(bannerId: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-assets/710982414301790216/store/${bannerId}`, options);\n\t}\n\n\t/**\n\t * Generates a team icon URL for a team's icon.\n\t *\n\t * @param teamId - The team id that has the icon\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic teamIcon(teamId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/team-icons/${teamId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates a cover image for a guild scheduled event.\n\t *\n\t * @param scheduledEventId - The scheduled event id\n\t * @param coverHash - The hash provided by discord for this cover image\n\t * @param options - Optional options for the cover image\n\t */\n\tpublic guildScheduledEventCover(\n\t\tscheduledEventId: string,\n\t\tcoverHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.makeURL(`/guild-events/${scheduledEventId}/${coverHash}`, options);\n\t}\n\n\t/**\n\t * Constructs the URL for the resource, checking whether or not `hash` starts with `a_` if `dynamic` is set to `true`.\n\t *\n\t * @param route - The base cdn route\n\t * @param hash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the link\n\t */\n\tprivate dynamicMakeURL(\n\t\troute: string,\n\t\thash: string,\n\t\t{ forceStatic = false, ...options }: Readonly = {},\n\t): string {\n\t\treturn this.makeURL(route, !forceStatic && hash.startsWith('a_') ? { ...options, extension: 'gif' } : options);\n\t}\n\n\t/**\n\t * Constructs the URL for the resource\n\t *\n\t * @param route - The base cdn route\n\t * @param options - The extension/size options for the link\n\t */\n\tprivate makeURL(\n\t\troute: string,\n\t\t{ allowedExtensions = ALLOWED_EXTENSIONS, extension = 'webp', size }: Readonly = {},\n\t): string {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\textension = String(extension).toLowerCase();\n\n\t\tif (!allowedExtensions.includes(extension)) {\n\t\t\tthrow new RangeError(`Invalid extension provided: ${extension}\\nMust be one of: ${allowedExtensions.join(', ')}`);\n\t\t}\n\n\t\tif (size && !ALLOWED_SIZES.includes(size)) {\n\t\t\tthrow new RangeError(`Invalid size provided: ${size}\\nMust be one of: ${ALLOWED_SIZES.join(', ')}`);\n\t\t}\n\n\t\tconst url = new URL(`${this.base}${route}.${extension}`);\n\n\t\tif (size) {\n\t\t\turl.searchParams.set('size', String(size));\n\t\t}\n\n\t\treturn url.toString();\n\t}\n}\n","import process from 'node:process';\nimport { APIVersion } from 'discord-api-types/v10';\nimport { Agent } from 'undici';\nimport type { RESTOptions } from '../REST.js';\n\nexport const DefaultUserAgent = `DiscordBot (https://discord.js.org, 1.5.0)`;\n\nexport const DefaultRestOptions = {\n\tget agent() {\n\t\treturn new Agent({\n\t\t\tconnect: {\n\t\t\t\ttimeout: 30_000,\n\t\t\t},\n\t\t});\n\t},\n\tapi: 'https://discord.com/api',\n\tauthPrefix: 'Bot',\n\tcdn: 'https://cdn.discordapp.com',\n\theaders: {},\n\tinvalidRequestWarningInterval: 0,\n\tglobalRequestsPerSecond: 50,\n\toffset: 50,\n\trejectOnRateLimit: null,\n\tretries: 3,\n\ttimeout: 15_000,\n\tuserAgentAppendix: `Node.js ${process.version}`,\n\tversion: APIVersion,\n\thashSweepInterval: 14_400_000, // 4 Hours\n\thashLifetime: 86_400_000, // 24 Hours\n\thandlerSweepInterval: 3_600_000, // 1 Hour\n} as const satisfies Required;\n\n/**\n * The events that the REST manager emits\n */\nexport const enum RESTEvents {\n\tDebug = 'restDebug',\n\tHandlerSweep = 'handlerSweep',\n\tHashSweep = 'hashSweep',\n\tInvalidRequestWarning = 'invalidRequestWarning',\n\tRateLimited = 'rateLimited',\n\tResponse = 'response',\n}\n\nexport const ALLOWED_EXTENSIONS = ['webp', 'png', 'jpg', 'jpeg', 'gif'] as const satisfies readonly string[];\nexport const ALLOWED_STICKER_EXTENSIONS = ['png', 'json'] as const satisfies readonly string[];\nexport const ALLOWED_SIZES = [16, 32, 64, 128, 256, 512, 1_024, 2_048, 4_096] as const satisfies readonly number[];\n\nexport type ImageExtension = typeof ALLOWED_EXTENSIONS[number];\nexport type StickerExtension = typeof ALLOWED_STICKER_EXTENSIONS[number];\nexport type ImageSize = typeof ALLOWED_SIZES[number];\n","import type { InternalRequest, RawFile } from '../RequestManager.js';\n\ninterface DiscordErrorFieldInformation {\n\tcode: string;\n\tmessage: string;\n}\n\ninterface DiscordErrorGroupWrapper {\n\t_errors: DiscordError[];\n}\n\ntype DiscordError = DiscordErrorFieldInformation | DiscordErrorGroupWrapper | string | { [k: string]: DiscordError };\n\nexport interface DiscordErrorData {\n\tcode: number;\n\terrors?: DiscordError;\n\tmessage: string;\n}\n\nexport interface OAuthErrorData {\n\terror: string;\n\terror_description?: string;\n}\n\nexport interface RequestBody {\n\tfiles: RawFile[] | undefined;\n\tjson: unknown | undefined;\n}\n\nfunction isErrorGroupWrapper(error: DiscordError): error is DiscordErrorGroupWrapper {\n\treturn Reflect.has(error as Record, '_errors');\n}\n\nfunction isErrorResponse(error: DiscordError): error is DiscordErrorFieldInformation {\n\treturn typeof Reflect.get(error as Record, 'message') === 'string';\n}\n\n/**\n * Represents an API error returned by Discord\n */\nexport class DiscordAPIError extends Error {\n\tpublic requestBody: RequestBody;\n\n\t/**\n\t * @param rawError - The error reported by Discord\n\t * @param code - The error code reported by Discord\n\t * @param status - The status code of the response\n\t * @param method - The method of the request that erred\n\t * @param url - The url of the request that erred\n\t * @param bodyData - The unparsed data for the request that errored\n\t */\n\tpublic constructor(\n\t\tpublic rawError: DiscordErrorData | OAuthErrorData,\n\t\tpublic code: number | string,\n\t\tpublic status: number,\n\t\tpublic method: string,\n\t\tpublic url: string,\n\t\tbodyData: Pick,\n\t) {\n\t\tsuper(DiscordAPIError.getMessage(rawError));\n\n\t\tthis.requestBody = { files: bodyData.files, json: bodyData.body };\n\t}\n\n\t/**\n\t * The name of the error\n\t */\n\tpublic override get name(): string {\n\t\treturn `${DiscordAPIError.name}[${this.code}]`;\n\t}\n\n\tprivate static getMessage(error: DiscordErrorData | OAuthErrorData) {\n\t\tlet flattened = '';\n\t\tif ('code' in error) {\n\t\t\tif (error.errors) {\n\t\t\t\tflattened = [...this.flattenDiscordError(error.errors)].join('\\n');\n\t\t\t}\n\n\t\t\treturn error.message && flattened\n\t\t\t\t? `${error.message}\\n${flattened}`\n\t\t\t\t: error.message || flattened || 'Unknown Error';\n\t\t}\n\n\t\treturn error.error_description ?? 'No Description';\n\t}\n\n\tprivate static *flattenDiscordError(obj: DiscordError, key = ''): IterableIterator {\n\t\tif (isErrorResponse(obj)) {\n\t\t\treturn yield `${key.length ? `${key}[${obj.code}]` : `${obj.code}`}: ${obj.message}`.trim();\n\t\t}\n\n\t\tfor (const [otherKey, val] of Object.entries(obj)) {\n\t\t\tconst nextKey = otherKey.startsWith('_')\n\t\t\t\t? key\n\t\t\t\t: key\n\t\t\t\t? Number.isNaN(Number(otherKey))\n\t\t\t\t\t? `${key}.${otherKey}`\n\t\t\t\t\t: `${key}[${otherKey}]`\n\t\t\t\t: otherKey;\n\n\t\t\tif (typeof val === 'string') {\n\t\t\t\tyield val;\n\t\t\t} else if (isErrorGroupWrapper(val)) {\n\t\t\t\tfor (const error of val._errors) {\n\t\t\t\t\tyield* this.flattenDiscordError(error, nextKey);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tyield* this.flattenDiscordError(val, nextKey);\n\t\t\t}\n\t\t}\n\t}\n}\n","import { STATUS_CODES } from 'node:http';\nimport type { InternalRequest } from '../RequestManager.js';\nimport type { RequestBody } from './DiscordAPIError.js';\n\n/**\n * Represents a HTTP error\n */\nexport class HTTPError extends Error {\n\tpublic requestBody: RequestBody;\n\n\tpublic override name = HTTPError.name;\n\n\t/**\n\t * @param status - The status code of the response\n\t * @param method - The method of the request that erred\n\t * @param url - The url of the request that erred\n\t * @param bodyData - The unparsed data for the request that errored\n\t */\n\tpublic constructor(\n\t\tpublic status: number,\n\t\tpublic method: string,\n\t\tpublic url: string,\n\t\tbodyData: Pick,\n\t) {\n\t\tsuper(STATUS_CODES[status]);\n\n\t\tthis.requestBody = { files: bodyData.files, json: bodyData.body };\n\t}\n}\n","import type { RateLimitData } from '../REST';\n\nexport class RateLimitError extends Error implements RateLimitData {\n\tpublic timeToReset: number;\n\n\tpublic limit: number;\n\n\tpublic method: string;\n\n\tpublic hash: string;\n\n\tpublic url: string;\n\n\tpublic route: string;\n\n\tpublic majorParameter: string;\n\n\tpublic global: boolean;\n\n\tpublic constructor({ timeToReset, limit, method, hash, url, route, majorParameter, global }: RateLimitData) {\n\t\tsuper();\n\t\tthis.timeToReset = timeToReset;\n\t\tthis.limit = limit;\n\t\tthis.method = method;\n\t\tthis.hash = hash;\n\t\tthis.url = url;\n\t\tthis.route = route;\n\t\tthis.majorParameter = majorParameter;\n\t\tthis.global = global;\n\t}\n\n\t/**\n\t * The name of the error\n\t */\n\tpublic override get name(): string {\n\t\treturn `${RateLimitError.name}[${this.route}]`;\n\t}\n}\n","import { Blob, Buffer } from 'node:buffer';\nimport { EventEmitter } from 'node:events';\nimport { setInterval, clearInterval } from 'node:timers';\nimport type { URLSearchParams } from 'node:url';\nimport { Collection } from '@discordjs/collection';\nimport { lazy } from '@discordjs/util';\nimport { DiscordSnowflake } from '@sapphire/snowflake';\nimport { FormData, type RequestInit, type BodyInit, type Dispatcher, type Agent } from 'undici';\nimport type { RESTOptions, RestEvents, RequestOptions } from './REST.js';\nimport type { IHandler } from './handlers/IHandler.js';\nimport { SequentialHandler } from './handlers/SequentialHandler.js';\nimport { DefaultRestOptions, DefaultUserAgent, RESTEvents } from './utils/constants.js';\nimport { resolveBody } from './utils/utils.js';\n\n// Make this a lazy dynamic import as file-type is a pure ESM package\nconst getFileType = lazy(async () => import('file-type'));\n\n/**\n * Represents a file to be added to the request\n */\nexport interface RawFile {\n\t/**\n\t * Content-Type of the file\n\t */\n\tcontentType?: string;\n\t/**\n\t * The actual data for the file\n\t */\n\tdata: Buffer | boolean | number | string;\n\t/**\n\t * An explicit key to use for key of the formdata field for this file.\n\t * When not provided, the index of the file in the files array is used in the form `files[${index}]`.\n\t * If you wish to alter the placeholder snowflake, you must provide this property in the same form (`files[${placeholder}]`)\n\t */\n\tkey?: string;\n\t/**\n\t * The name of the file\n\t */\n\tname: string;\n}\n\n/**\n * Represents possible data to be given to an endpoint\n */\nexport interface RequestData {\n\t/**\n\t * Whether to append JSON data to form data instead of `payload_json` when sending files\n\t */\n\tappendToFormData?: boolean;\n\t/**\n\t * If this request needs the `Authorization` header\n\t *\n\t * @defaultValue `true`\n\t */\n\tauth?: boolean;\n\t/**\n\t * The authorization prefix to use for this request, useful if you use this with bearer tokens\n\t *\n\t * @defaultValue `'Bot'`\n\t */\n\tauthPrefix?: 'Bearer' | 'Bot';\n\t/**\n\t * The body to send to this request.\n\t * If providing as BodyInit, set `passThroughBody: true`\n\t */\n\tbody?: BodyInit | unknown;\n\t/**\n\t * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} to use for the request.\n\t */\n\tdispatcher?: Agent;\n\t/**\n\t * Files to be attached to this request\n\t */\n\tfiles?: RawFile[] | undefined;\n\t/**\n\t * Additional headers to add to this request\n\t */\n\theaders?: Record;\n\t/**\n\t * Whether to pass-through the body property directly to `fetch()`.\n\t * This only applies when files is NOT present\n\t */\n\tpassThroughBody?: boolean;\n\t/**\n\t * Query string parameters to append to the called endpoint\n\t */\n\tquery?: URLSearchParams;\n\t/**\n\t * Reason to show in the audit logs\n\t */\n\treason?: string | undefined;\n\t/**\n\t * The signal to abort the queue entry or the REST call, where applicable\n\t */\n\tsignal?: AbortSignal | undefined;\n\t/**\n\t * If this request should be versioned\n\t *\n\t * @defaultValue `true`\n\t */\n\tversioned?: boolean;\n}\n\n/**\n * Possible headers for an API call\n */\nexport interface RequestHeaders {\n\tAuthorization?: string;\n\t'User-Agent': string;\n\t'X-Audit-Log-Reason'?: string;\n}\n\n/**\n * Possible API methods to be used when doing requests\n */\nexport const enum RequestMethod {\n\tDelete = 'DELETE',\n\tGet = 'GET',\n\tPatch = 'PATCH',\n\tPost = 'POST',\n\tPut = 'PUT',\n}\n\nexport type RouteLike = `/${string}`;\n\n/**\n * Internal request options\n *\n * @internal\n */\nexport interface InternalRequest extends RequestData {\n\tfullRoute: RouteLike;\n\tmethod: RequestMethod;\n}\n\nexport type HandlerRequestData = Pick;\n\n/**\n * Parsed route data for an endpoint\n *\n * @internal\n */\nexport interface RouteData {\n\tbucketRoute: string;\n\tmajorParameter: string;\n\toriginal: RouteLike;\n}\n\n/**\n * Represents a hash and its associated fields\n *\n * @internal\n */\nexport interface HashData {\n\tlastAccess: number;\n\tvalue: string;\n}\n\nexport interface RequestManager {\n\temit: ((event: K, ...args: RestEvents[K]) => boolean) &\n\t\t((event: Exclude, ...args: any[]) => boolean);\n\n\toff: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\ton: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tonce: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tremoveAllListeners: ((event?: K) => this) &\n\t\t((event?: Exclude) => this);\n}\n\n/**\n * Represents the class that manages handlers for endpoints\n */\nexport class RequestManager extends EventEmitter {\n\t/**\n\t * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} for all requests\n\t * performed by this manager.\n\t */\n\tpublic agent: Dispatcher | null = null;\n\n\t/**\n\t * The number of requests remaining in the global bucket\n\t */\n\tpublic globalRemaining: number;\n\n\t/**\n\t * The promise used to wait out the global rate limit\n\t */\n\tpublic globalDelay: Promise | null = null;\n\n\t/**\n\t * The timestamp at which the global bucket resets\n\t */\n\tpublic globalReset = -1;\n\n\t/**\n\t * API bucket hashes that are cached from provided routes\n\t */\n\tpublic readonly hashes = new Collection();\n\n\t/**\n\t * Request handlers created from the bucket hash and the major parameters\n\t */\n\tpublic readonly handlers = new Collection();\n\n\t#token: string | null = null;\n\n\tprivate hashTimer!: NodeJS.Timer;\n\n\tprivate handlerTimer!: NodeJS.Timer;\n\n\tpublic readonly options: RESTOptions;\n\n\tpublic constructor(options: Partial) {\n\t\tsuper();\n\t\tthis.options = { ...DefaultRestOptions, ...options };\n\t\tthis.options.offset = Math.max(0, this.options.offset);\n\t\tthis.globalRemaining = this.options.globalRequestsPerSecond;\n\t\tthis.agent = options.agent ?? null;\n\n\t\t// Start sweepers\n\t\tthis.setupSweepers();\n\t}\n\n\tprivate setupSweepers() {\n\t\t// eslint-disable-next-line unicorn/consistent-function-scoping\n\t\tconst validateMaxInterval = (interval: number) => {\n\t\t\tif (interval > 14_400_000) {\n\t\t\t\tthrow new Error('Cannot set an interval greater than 4 hours');\n\t\t\t}\n\t\t};\n\n\t\tif (this.options.hashSweepInterval !== 0 && this.options.hashSweepInterval !== Number.POSITIVE_INFINITY) {\n\t\t\tvalidateMaxInterval(this.options.hashSweepInterval);\n\t\t\tthis.hashTimer = setInterval(() => {\n\t\t\t\tconst sweptHashes = new Collection();\n\t\t\t\tconst currentDate = Date.now();\n\n\t\t\t\t// Begin sweeping hash based on lifetimes\n\t\t\t\tthis.hashes.sweep((val, key) => {\n\t\t\t\t\t// `-1` indicates a global hash\n\t\t\t\t\tif (val.lastAccess === -1) return false;\n\n\t\t\t\t\t// Check if lifetime has been exceeded\n\t\t\t\t\tconst shouldSweep = Math.floor(currentDate - val.lastAccess) > this.options.hashLifetime;\n\n\t\t\t\t\t// Add hash to collection of swept hashes\n\t\t\t\t\tif (shouldSweep) {\n\t\t\t\t\t\t// Add to swept hashes\n\t\t\t\t\t\tsweptHashes.set(key, val);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Emit debug information\n\t\t\t\t\tthis.emit(RESTEvents.Debug, `Hash ${val.value} for ${key} swept due to lifetime being exceeded`);\n\n\t\t\t\t\treturn shouldSweep;\n\t\t\t\t});\n\n\t\t\t\t// Fire event\n\t\t\t\tthis.emit(RESTEvents.HashSweep, sweptHashes);\n\t\t\t}, this.options.hashSweepInterval).unref();\n\t\t}\n\n\t\tif (this.options.handlerSweepInterval !== 0 && this.options.handlerSweepInterval !== Number.POSITIVE_INFINITY) {\n\t\t\tvalidateMaxInterval(this.options.handlerSweepInterval);\n\t\t\tthis.handlerTimer = setInterval(() => {\n\t\t\t\tconst sweptHandlers = new Collection();\n\n\t\t\t\t// Begin sweeping handlers based on activity\n\t\t\t\tthis.handlers.sweep((val, key) => {\n\t\t\t\t\tconst { inactive } = val;\n\n\t\t\t\t\t// Collect inactive handlers\n\t\t\t\t\tif (inactive) {\n\t\t\t\t\t\tsweptHandlers.set(key, val);\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.emit(RESTEvents.Debug, `Handler ${val.id} for ${key} swept due to being inactive`);\n\t\t\t\t\treturn inactive;\n\t\t\t\t});\n\n\t\t\t\t// Fire event\n\t\t\t\tthis.emit(RESTEvents.HandlerSweep, sweptHandlers);\n\t\t\t}, this.options.handlerSweepInterval).unref();\n\t\t}\n\t}\n\n\t/**\n\t * Sets the default agent to use for requests performed by this manager\n\t *\n\t * @param agent - The agent to use\n\t */\n\tpublic setAgent(agent: Dispatcher) {\n\t\tthis.agent = agent;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the authorization token that should be used for requests\n\t *\n\t * @param token - The authorization token to use\n\t */\n\tpublic setToken(token: string) {\n\t\tthis.#token = token;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Queues a request to be sent\n\t *\n\t * @param request - All the information needed to make a request\n\t * @returns The response from the api request\n\t */\n\tpublic async queueRequest(request: InternalRequest): Promise {\n\t\t// Generalize the endpoint to its route data\n\t\tconst routeId = RequestManager.generateRouteData(request.fullRoute, request.method);\n\t\t// Get the bucket hash for the generic route, or point to a global route otherwise\n\t\tconst hash = this.hashes.get(`${request.method}:${routeId.bucketRoute}`) ?? {\n\t\t\tvalue: `Global(${request.method}:${routeId.bucketRoute})`,\n\t\t\tlastAccess: -1,\n\t\t};\n\n\t\t// Get the request handler for the obtained hash, with its major parameter\n\t\tconst handler =\n\t\t\tthis.handlers.get(`${hash.value}:${routeId.majorParameter}`) ??\n\t\t\tthis.createHandler(hash.value, routeId.majorParameter);\n\n\t\t// Resolve the request into usable fetch options\n\t\tconst { url, fetchOptions } = await this.resolveRequest(request);\n\n\t\t// Queue the request\n\t\treturn handler.queueRequest(routeId, url, fetchOptions, {\n\t\t\tbody: request.body,\n\t\t\tfiles: request.files,\n\t\t\tauth: request.auth !== false,\n\t\t\tsignal: request.signal,\n\t\t});\n\t}\n\n\t/**\n\t * Creates a new rate limit handler from a hash, based on the hash and the major parameter\n\t *\n\t * @param hash - The hash for the route\n\t * @param majorParameter - The major parameter for this handler\n\t * @internal\n\t */\n\tprivate createHandler(hash: string, majorParameter: string) {\n\t\t// Create the async request queue to handle requests\n\t\tconst queue = new SequentialHandler(this, hash, majorParameter);\n\t\t// Save the queue based on its id\n\t\tthis.handlers.set(queue.id, queue);\n\n\t\treturn queue;\n\t}\n\n\t/**\n\t * Formats the request data to a usable format for fetch\n\t *\n\t * @param request - The request data\n\t */\n\tprivate async resolveRequest(request: InternalRequest): Promise<{ fetchOptions: RequestOptions; url: string }> {\n\t\tconst { options } = this;\n\n\t\tlet query = '';\n\n\t\t// If a query option is passed, use it\n\t\tif (request.query) {\n\t\t\tconst resolvedQuery = request.query.toString();\n\t\t\tif (resolvedQuery !== '') {\n\t\t\t\tquery = `?${resolvedQuery}`;\n\t\t\t}\n\t\t}\n\n\t\t// Create the required headers\n\t\tconst headers: RequestHeaders = {\n\t\t\t...this.options.headers,\n\t\t\t'User-Agent': `${DefaultUserAgent} ${options.userAgentAppendix}`.trim(),\n\t\t};\n\n\t\t// If this request requires authorization (allowing non-\"authorized\" requests for webhooks)\n\t\tif (request.auth !== false) {\n\t\t\t// If we haven't received a token, throw an error\n\t\t\tif (!this.#token) {\n\t\t\t\tthrow new Error('Expected token to be set for this request, but none was present');\n\t\t\t}\n\n\t\t\theaders.Authorization = `${request.authPrefix ?? this.options.authPrefix} ${this.#token}`;\n\t\t}\n\n\t\t// If a reason was set, set it's appropriate header\n\t\tif (request.reason?.length) {\n\t\t\theaders['X-Audit-Log-Reason'] = encodeURIComponent(request.reason);\n\t\t}\n\n\t\t// Format the full request URL (api base, optional version, endpoint, optional querystring)\n\t\tconst url = `${options.api}${request.versioned === false ? '' : `/v${options.version}`}${\n\t\t\trequest.fullRoute\n\t\t}${query}`;\n\n\t\tlet finalBody: RequestInit['body'];\n\t\tlet additionalHeaders: Record = {};\n\n\t\tif (request.files?.length) {\n\t\t\tconst formData = new FormData();\n\n\t\t\t// Attach all files to the request\n\t\t\tfor (const [index, file] of request.files.entries()) {\n\t\t\t\tconst fileKey = file.key ?? `files[${index}]`;\n\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/FormData/append#parameters\n\t\t\t\t// FormData.append only accepts a string or Blob.\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob#parameters\n\t\t\t\t// The Blob constructor accepts TypedArray/ArrayBuffer, strings, and Blobs.\n\t\t\t\tif (Buffer.isBuffer(file.data)) {\n\t\t\t\t\t// Try to infer the content type from the buffer if one isn't passed\n\t\t\t\t\tconst { fileTypeFromBuffer } = await getFileType();\n\t\t\t\t\tconst contentType = file.contentType ?? (await fileTypeFromBuffer(file.data))?.mime;\n\t\t\t\t\tformData.append(fileKey, new Blob([file.data], { type: contentType }), file.name);\n\t\t\t\t} else {\n\t\t\t\t\tformData.append(fileKey, new Blob([`${file.data}`], { type: file.contentType }), file.name);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If a JSON body was added as well, attach it to the form data, using payload_json unless otherwise specified\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t\tif (request.body != null) {\n\t\t\t\tif (request.appendToFormData) {\n\t\t\t\t\tfor (const [key, value] of Object.entries(request.body as Record)) {\n\t\t\t\t\t\tformData.append(key, value);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tformData.append('payload_json', JSON.stringify(request.body));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Set the final body to the form data\n\t\t\tfinalBody = formData;\n\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t} else if (request.body != null) {\n\t\t\tif (request.passThroughBody) {\n\t\t\t\tfinalBody = request.body as BodyInit;\n\t\t\t} else {\n\t\t\t\t// Stringify the JSON data\n\t\t\t\tfinalBody = JSON.stringify(request.body);\n\t\t\t\t// Set the additional headers to specify the content-type\n\t\t\t\tadditionalHeaders = { 'Content-Type': 'application/json' };\n\t\t\t}\n\t\t}\n\n\t\tfinalBody = await resolveBody(finalBody);\n\n\t\tconst fetchOptions: RequestOptions = {\n\t\t\theaders: { ...request.headers, ...additionalHeaders, ...headers } as Record,\n\t\t\tmethod: request.method.toUpperCase() as Dispatcher.HttpMethod,\n\t\t};\n\n\t\tif (finalBody !== undefined) {\n\t\t\tfetchOptions.body = finalBody as Exclude;\n\t\t}\n\n\t\t// Prioritize setting an agent per request, use the agent for this instance otherwise.\n\t\tfetchOptions.dispatcher = request.dispatcher ?? this.agent ?? undefined!;\n\n\t\treturn { url, fetchOptions };\n\t}\n\n\t/**\n\t * Stops the hash sweeping interval\n\t */\n\tpublic clearHashSweeper() {\n\t\tclearInterval(this.hashTimer);\n\t}\n\n\t/**\n\t * Stops the request handler sweeping interval\n\t */\n\tpublic clearHandlerSweeper() {\n\t\tclearInterval(this.handlerTimer);\n\t}\n\n\t/**\n\t * Generates route data for an endpoint:method\n\t *\n\t * @param endpoint - The raw endpoint to generalize\n\t * @param method - The HTTP method this endpoint is called without\n\t * @internal\n\t */\n\tprivate static generateRouteData(endpoint: RouteLike, method: RequestMethod): RouteData {\n\t\tconst majorIdMatch = /^\\/(?:channels|guilds|webhooks)\\/(\\d{16,19})/.exec(endpoint);\n\n\t\t// Get the major id for this route - global otherwise\n\t\tconst majorId = majorIdMatch?.[1] ?? 'global';\n\n\t\tconst baseRoute = endpoint\n\t\t\t// Strip out all ids\n\t\t\t.replaceAll(/\\d{16,19}/g, ':id')\n\t\t\t// Strip out reaction as they fall under the same bucket\n\t\t\t.replace(/\\/reactions\\/(.*)/, '/reactions/:reaction');\n\n\t\tlet exceptions = '';\n\n\t\t// Hard-Code Old Message Deletion Exception (2 week+ old messages are a different bucket)\n\t\t// https://github.com/discord/discord-api-docs/issues/1295\n\t\tif (method === RequestMethod.Delete && baseRoute === '/channels/:id/messages/:id') {\n\t\t\tconst id = /\\d{16,19}$/.exec(endpoint)![0]!;\n\t\t\tconst timestamp = DiscordSnowflake.timestampFrom(id);\n\t\t\tif (Date.now() - timestamp > 1_000 * 60 * 60 * 24 * 14) {\n\t\t\t\texceptions += '/Delete Old Message';\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tmajorParameter: majorId,\n\t\t\tbucketRoute: baseRoute + exceptions,\n\t\t\toriginal: endpoint,\n\t\t};\n\t}\n}\n","import { setTimeout, clearTimeout } from 'node:timers';\nimport { setTimeout as sleep } from 'node:timers/promises';\nimport { AsyncQueue } from '@sapphire/async-queue';\nimport { request, type Dispatcher } from 'undici';\nimport type { RateLimitData, RequestOptions } from '../REST';\nimport type { HandlerRequestData, RequestManager, RouteData } from '../RequestManager';\nimport { DiscordAPIError, type DiscordErrorData, type OAuthErrorData } from '../errors/DiscordAPIError.js';\nimport { HTTPError } from '../errors/HTTPError.js';\nimport { RateLimitError } from '../errors/RateLimitError.js';\nimport { RESTEvents } from '../utils/constants.js';\nimport { hasSublimit, parseHeader, parseResponse, shouldRetry } from '../utils/utils.js';\nimport type { IHandler } from './IHandler.js';\n\n/**\n * Invalid request limiting is done on a per-IP basis, not a per-token basis.\n * The best we can do is track invalid counts process-wide (on the theory that\n * users could have multiple bots run from one process) rather than per-bot.\n * Therefore, store these at file scope here rather than in the client's\n * RESTManager object.\n */\nlet invalidCount = 0;\nlet invalidCountResetTime: number | null = null;\n\nconst enum QueueType {\n\tStandard,\n\tSublimit,\n}\n\n/**\n * The structure used to handle requests for a given bucket\n */\nexport class SequentialHandler implements IHandler {\n\t/**\n\t * {@inheritDoc IHandler.id}\n\t */\n\tpublic readonly id: string;\n\n\t/**\n\t * The time this rate limit bucket will reset\n\t */\n\tprivate reset = -1;\n\n\t/**\n\t * The remaining requests that can be made before we are rate limited\n\t */\n\tprivate remaining = 1;\n\n\t/**\n\t * The total number of requests that can be made before we are rate limited\n\t */\n\tprivate limit = Number.POSITIVE_INFINITY;\n\n\t/**\n\t * The interface used to sequence async requests sequentially\n\t */\n\t#asyncQueue = new AsyncQueue();\n\n\t/**\n\t * The interface used to sequence sublimited async requests sequentially\n\t */\n\t#sublimitedQueue: AsyncQueue | null = null;\n\n\t/**\n\t * A promise wrapper for when the sublimited queue is finished being processed or null when not being processed\n\t */\n\t#sublimitPromise: { promise: Promise; resolve(): void } | null = null;\n\n\t/**\n\t * Whether the sublimit queue needs to be shifted in the finally block\n\t */\n\t#shiftSublimit = false;\n\n\t/**\n\t * @param manager - The request manager\n\t * @param hash - The hash that this RequestHandler handles\n\t * @param majorParameter - The major parameter for this handler\n\t */\n\tpublic constructor(\n\t\tprivate readonly manager: RequestManager,\n\t\tprivate readonly hash: string,\n\t\tprivate readonly majorParameter: string,\n\t) {\n\t\tthis.id = `${hash}:${majorParameter}`;\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.inactive}\n\t */\n\tpublic get inactive(): boolean {\n\t\treturn (\n\t\t\tthis.#asyncQueue.remaining === 0 &&\n\t\t\t(this.#sublimitedQueue === null || this.#sublimitedQueue.remaining === 0) &&\n\t\t\t!this.limited\n\t\t);\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited by the global limit\n\t */\n\tprivate get globalLimited(): boolean {\n\t\treturn this.manager.globalRemaining <= 0 && Date.now() < this.manager.globalReset;\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited by its limit\n\t */\n\tprivate get localLimited(): boolean {\n\t\treturn this.remaining <= 0 && Date.now() < this.reset;\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited\n\t */\n\tprivate get limited(): boolean {\n\t\treturn this.globalLimited || this.localLimited;\n\t}\n\n\t/**\n\t * The time until queued requests can continue\n\t */\n\tprivate get timeToReset(): number {\n\t\treturn this.reset + this.manager.options.offset - Date.now();\n\t}\n\n\t/**\n\t * Emits a debug message\n\t *\n\t * @param message - The message to debug\n\t */\n\tprivate debug(message: string) {\n\t\tthis.manager.emit(RESTEvents.Debug, `[REST ${this.id}] ${message}`);\n\t}\n\n\t/**\n\t * Delay all requests for the specified amount of time, handling global rate limits\n\t *\n\t * @param time - The amount of time to delay all requests for\n\t */\n\tprivate async globalDelayFor(time: number): Promise {\n\t\tawait sleep(time);\n\t\tthis.manager.globalDelay = null;\n\t}\n\n\t/*\n\t * Determines whether the request should be queued or whether a RateLimitError should be thrown\n\t */\n\tprivate async onRateLimit(rateLimitData: RateLimitData) {\n\t\tconst { options } = this.manager;\n\t\tif (!options.rejectOnRateLimit) return;\n\n\t\tconst shouldThrow =\n\t\t\ttypeof options.rejectOnRateLimit === 'function'\n\t\t\t\t? await options.rejectOnRateLimit(rateLimitData)\n\t\t\t\t: options.rejectOnRateLimit.some((route) => rateLimitData.route.startsWith(route.toLowerCase()));\n\t\tif (shouldThrow) {\n\t\t\tthrow new RateLimitError(rateLimitData);\n\t\t}\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.queueRequest}\n\t */\n\tpublic async queueRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t): Promise {\n\t\tlet queue = this.#asyncQueue;\n\t\tlet queueType = QueueType.Standard;\n\t\t// Separate sublimited requests when already sublimited\n\t\tif (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) {\n\t\t\tqueue = this.#sublimitedQueue!;\n\t\t\tqueueType = QueueType.Sublimit;\n\t\t}\n\n\t\t// Wait for any previous requests to be completed before this one is run\n\t\tawait queue.wait({ signal: requestData.signal });\n\t\t// This set handles retroactively sublimiting requests\n\t\tif (queueType === QueueType.Standard) {\n\t\t\tif (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) {\n\t\t\t\t/**\n\t\t\t\t * Remove the request from the standard queue, it should never be possible to get here while processing the\n\t\t\t\t * sublimit queue so there is no need to worry about shifting the wrong request\n\t\t\t\t */\n\t\t\t\tqueue = this.#sublimitedQueue!;\n\t\t\t\tconst wait = queue.wait();\n\t\t\t\tthis.#asyncQueue.shift();\n\t\t\t\tawait wait;\n\t\t\t} else if (this.#sublimitPromise) {\n\t\t\t\t// Stall requests while the sublimit queue gets processed\n\t\t\t\tawait this.#sublimitPromise.promise;\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t// Make the request, and return the results\n\t\t\treturn await this.runRequest(routeId, url, options, requestData);\n\t\t} finally {\n\t\t\t// Allow the next request to fire\n\t\t\tqueue.shift();\n\t\t\tif (this.#shiftSublimit) {\n\t\t\t\tthis.#shiftSublimit = false;\n\t\t\t\tthis.#sublimitedQueue?.shift();\n\t\t\t}\n\n\t\t\t// If this request is the last request in a sublimit\n\t\t\tif (this.#sublimitedQueue?.remaining === 0) {\n\t\t\t\tthis.#sublimitPromise?.resolve();\n\t\t\t\tthis.#sublimitedQueue = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * The method that actually makes the request to the api, and updates info about the bucket accordingly\n\t *\n\t * @param routeId - The generalized api route with literal ids for major parameters\n\t * @param url - The fully resolved url to make the request to\n\t * @param options - The fetch options needed to make the request\n\t * @param requestData - Extra data from the user's request needed for errors and additional processing\n\t * @param retries - The number of retries this request has already attempted (recursion)\n\t */\n\tprivate async runRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t\tretries = 0,\n\t): Promise {\n\t\t/*\n\t\t * After calculations have been done, pre-emptively stop further requests\n\t\t * Potentially loop until this task can run if e.g. the global rate limit is hit twice\n\t\t */\n\t\twhile (this.limited) {\n\t\t\tconst isGlobal = this.globalLimited;\n\t\t\tlet limit: number;\n\t\t\tlet timeout: number;\n\t\t\tlet delay: Promise;\n\n\t\t\tif (isGlobal) {\n\t\t\t\t// Set RateLimitData based on the global limit\n\t\t\t\tlimit = this.manager.options.globalRequestsPerSecond;\n\t\t\t\ttimeout = this.manager.globalReset + this.manager.options.offset - Date.now();\n\t\t\t\t// If this is the first task to reach the global timeout, set the global delay\n\t\t\t\tif (!this.manager.globalDelay) {\n\t\t\t\t\t// The global delay function clears the global delay state when it is resolved\n\t\t\t\t\tthis.manager.globalDelay = this.globalDelayFor(timeout);\n\t\t\t\t}\n\n\t\t\t\tdelay = this.manager.globalDelay;\n\t\t\t} else {\n\t\t\t\t// Set RateLimitData based on the route-specific limit\n\t\t\t\tlimit = this.limit;\n\t\t\t\ttimeout = this.timeToReset;\n\t\t\t\tdelay = sleep(timeout);\n\t\t\t}\n\n\t\t\tconst rateLimitData: RateLimitData = {\n\t\t\t\ttimeToReset: timeout,\n\t\t\t\tlimit,\n\t\t\t\tmethod: options.method ?? 'get',\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t};\n\t\t\t// Let library users know they have hit a rate limit\n\t\t\tthis.manager.emit(RESTEvents.RateLimited, rateLimitData);\n\t\t\t// Determine whether a RateLimitError should be thrown\n\t\t\tawait this.onRateLimit(rateLimitData);\n\t\t\t// When not erroring, emit debug for what is happening\n\t\t\tif (isGlobal) {\n\t\t\t\tthis.debug(`Global rate limit hit, blocking all requests for ${timeout}ms`);\n\t\t\t} else {\n\t\t\t\tthis.debug(`Waiting ${timeout}ms for rate limit to pass`);\n\t\t\t}\n\n\t\t\t// Wait the remaining time left before the rate limit resets\n\t\t\tawait delay;\n\t\t}\n\n\t\t// As the request goes out, update the global usage information\n\t\tif (!this.manager.globalReset || this.manager.globalReset < Date.now()) {\n\t\t\tthis.manager.globalReset = Date.now() + 1_000;\n\t\t\tthis.manager.globalRemaining = this.manager.options.globalRequestsPerSecond;\n\t\t}\n\n\t\tthis.manager.globalRemaining--;\n\n\t\tconst method = options.method ?? 'get';\n\n\t\tconst controller = new AbortController();\n\t\tconst timeout = setTimeout(() => controller.abort(), this.manager.options.timeout).unref();\n\t\tif (requestData.signal) {\n\t\t\t// The type polyfill is required because Node.js's types are incomplete.\n\t\t\tconst signal = requestData.signal as PolyFillAbortSignal;\n\t\t\t// If the user signal was aborted, abort the controller, else abort the local signal.\n\t\t\t// The reason why we don't re-use the user's signal, is because users may use the same signal for multiple\n\t\t\t// requests, and we do not want to cause unexpected side-effects.\n\t\t\tif (signal.aborted) controller.abort();\n\t\t\telse signal.addEventListener('abort', () => controller.abort());\n\t\t}\n\n\t\tlet res: Dispatcher.ResponseData;\n\t\ttry {\n\t\t\tres = await request(url, { ...options, signal: controller.signal });\n\t\t} catch (error: unknown) {\n\t\t\tif (!(error instanceof Error)) throw error;\n\t\t\t// Retry the specified number of times if needed\n\t\t\tif (shouldRetry(error) && retries !== this.manager.options.retries) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\treturn await this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t\t}\n\n\t\t\tthrow error;\n\t\t} finally {\n\t\t\tclearTimeout(timeout);\n\t\t}\n\n\t\tif (this.manager.listenerCount(RESTEvents.Response)) {\n\t\t\tthis.manager.emit(\n\t\t\t\tRESTEvents.Response,\n\t\t\t\t{\n\t\t\t\t\tmethod,\n\t\t\t\t\tpath: routeId.original,\n\t\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\t\toptions,\n\t\t\t\t\tdata: requestData,\n\t\t\t\t\tretries,\n\t\t\t\t},\n\t\t\t\t{ ...res },\n\t\t\t);\n\t\t}\n\n\t\tconst status = res.statusCode;\n\t\tlet retryAfter = 0;\n\n\t\tconst limit = parseHeader(res.headers['x-ratelimit-limit']);\n\t\tconst remaining = parseHeader(res.headers['x-ratelimit-remaining']);\n\t\tconst reset = parseHeader(res.headers['x-ratelimit-reset-after']);\n\t\tconst hash = parseHeader(res.headers['x-ratelimit-bucket']);\n\t\tconst retry = parseHeader(res.headers['retry-after']);\n\n\t\t// Update the total number of requests that can be made before the rate limit resets\n\t\tthis.limit = limit ? Number(limit) : Number.POSITIVE_INFINITY;\n\t\t// Update the number of remaining requests that can be made before the rate limit resets\n\t\tthis.remaining = remaining ? Number(remaining) : 1;\n\t\t// Update the time when this rate limit resets (reset-after is in seconds)\n\t\tthis.reset = reset ? Number(reset) * 1_000 + Date.now() + this.manager.options.offset : Date.now();\n\n\t\t// Amount of time in milliseconds until we should retry if rate limited (globally or otherwise)\n\t\tif (retry) retryAfter = Number(retry) * 1_000 + this.manager.options.offset;\n\n\t\t// Handle buckets via the hash header retroactively\n\t\tif (hash && hash !== this.hash) {\n\t\t\t// Let library users know when rate limit buckets have been updated\n\t\t\tthis.debug(['Received bucket hash update', ` Old Hash : ${this.hash}`, ` New Hash : ${hash}`].join('\\n'));\n\t\t\t// This queue will eventually be eliminated via attrition\n\t\t\tthis.manager.hashes.set(`${method}:${routeId.bucketRoute}`, { value: hash, lastAccess: Date.now() });\n\t\t} else if (hash) {\n\t\t\t// Handle the case where hash value doesn't change\n\t\t\t// Fetch the hash data from the manager\n\t\t\tconst hashData = this.manager.hashes.get(`${method}:${routeId.bucketRoute}`);\n\n\t\t\t// When fetched, update the last access of the hash\n\t\t\tif (hashData) {\n\t\t\t\thashData.lastAccess = Date.now();\n\t\t\t}\n\t\t}\n\n\t\t// Handle retryAfter, which means we have actually hit a rate limit\n\t\tlet sublimitTimeout: number | null = null;\n\t\tif (retryAfter > 0) {\n\t\t\tif (res.headers['x-ratelimit-global'] !== undefined) {\n\t\t\t\tthis.manager.globalRemaining = 0;\n\t\t\t\tthis.manager.globalReset = Date.now() + retryAfter;\n\t\t\t} else if (!this.localLimited) {\n\t\t\t\t/*\n\t\t\t\t * This is a sublimit (e.g. 2 channel name changes/10 minutes) since the headers don't indicate a\n\t\t\t\t * route-wide rate limit. Don't update remaining or reset to avoid rate limiting the whole\n\t\t\t\t * endpoint, just set a reset time on the request itself to avoid retrying too soon.\n\t\t\t\t */\n\t\t\t\tsublimitTimeout = retryAfter;\n\t\t\t}\n\t\t}\n\n\t\t// Count the invalid requests\n\t\tif (status === 401 || status === 403 || status === 429) {\n\t\t\tif (!invalidCountResetTime || invalidCountResetTime < Date.now()) {\n\t\t\t\tinvalidCountResetTime = Date.now() + 1_000 * 60 * 10;\n\t\t\t\tinvalidCount = 0;\n\t\t\t}\n\n\t\t\tinvalidCount++;\n\n\t\t\tconst emitInvalid =\n\t\t\t\tthis.manager.options.invalidRequestWarningInterval > 0 &&\n\t\t\t\tinvalidCount % this.manager.options.invalidRequestWarningInterval === 0;\n\t\t\tif (emitInvalid) {\n\t\t\t\t// Let library users know periodically about invalid requests\n\t\t\t\tthis.manager.emit(RESTEvents.InvalidRequestWarning, {\n\t\t\t\t\tcount: invalidCount,\n\t\t\t\t\tremainingTime: invalidCountResetTime - Date.now(),\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\n\t\tif (status >= 200 && status < 300) {\n\t\t\treturn res;\n\t\t} else if (status === 429) {\n\t\t\t// A rate limit was hit - this may happen if the route isn't associated with an official bucket hash yet, or when first globally rate limited\n\t\t\tconst isGlobal = this.globalLimited;\n\t\t\tlet limit: number;\n\t\t\tlet timeout: number;\n\n\t\t\tif (isGlobal) {\n\t\t\t\t// Set RateLimitData based on the global limit\n\t\t\t\tlimit = this.manager.options.globalRequestsPerSecond;\n\t\t\t\ttimeout = this.manager.globalReset + this.manager.options.offset - Date.now();\n\t\t\t} else {\n\t\t\t\t// Set RateLimitData based on the route-specific limit\n\t\t\t\tlimit = this.limit;\n\t\t\t\ttimeout = this.timeToReset;\n\t\t\t}\n\n\t\t\tawait this.onRateLimit({\n\t\t\t\ttimeToReset: timeout,\n\t\t\t\tlimit,\n\t\t\t\tmethod,\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t});\n\t\t\tthis.debug(\n\t\t\t\t[\n\t\t\t\t\t'Encountered unexpected 429 rate limit',\n\t\t\t\t\t` Global : ${isGlobal.toString()}`,\n\t\t\t\t\t` Method : ${method}`,\n\t\t\t\t\t` URL : ${url}`,\n\t\t\t\t\t` Bucket : ${routeId.bucketRoute}`,\n\t\t\t\t\t` Major parameter: ${routeId.majorParameter}`,\n\t\t\t\t\t` Hash : ${this.hash}`,\n\t\t\t\t\t` Limit : ${limit}`,\n\t\t\t\t\t` Retry After : ${retryAfter}ms`,\n\t\t\t\t\t` Sublimit : ${sublimitTimeout ? `${sublimitTimeout}ms` : 'None'}`,\n\t\t\t\t].join('\\n'),\n\t\t\t);\n\t\t\t// If caused by a sublimit, wait it out here so other requests on the route can be handled\n\t\t\tif (sublimitTimeout) {\n\t\t\t\t// Normally the sublimit queue will not exist, however, if a sublimit is hit while in the sublimit queue, it will\n\t\t\t\tconst firstSublimit = !this.#sublimitedQueue;\n\t\t\t\tif (firstSublimit) {\n\t\t\t\t\tthis.#sublimitedQueue = new AsyncQueue();\n\t\t\t\t\tvoid this.#sublimitedQueue.wait();\n\t\t\t\t\tthis.#asyncQueue.shift();\n\t\t\t\t}\n\n\t\t\t\tthis.#sublimitPromise?.resolve();\n\t\t\t\tthis.#sublimitPromise = null;\n\t\t\t\tawait sleep(sublimitTimeout);\n\t\t\t\tlet resolve: () => void;\n\t\t\t\t// eslint-disable-next-line promise/param-names, no-promise-executor-return\n\t\t\t\tconst promise = new Promise((res) => (resolve = res));\n\t\t\t\tthis.#sublimitPromise = { promise, resolve: resolve! };\n\t\t\t\tif (firstSublimit) {\n\t\t\t\t\t// Re-queue this request so it can be shifted by the finally\n\t\t\t\t\tawait this.#asyncQueue.wait();\n\t\t\t\t\tthis.#shiftSublimit = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Since this is not a server side issue, the next request should pass, so we don't bump the retries counter\n\t\t\treturn this.runRequest(routeId, url, options, requestData, retries);\n\t\t} else if (status >= 500 && status < 600) {\n\t\t\t// Retry the specified number of times for possible server side issues\n\t\t\tif (retries !== this.manager.options.retries) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t\t}\n\n\t\t\t// We are out of retries, throw an error\n\t\t\tthrow new HTTPError(status, method, url, requestData);\n\t\t} else {\n\t\t\t// Handle possible malformed requests\n\t\t\tif (status >= 400 && status < 500) {\n\t\t\t\t// If we receive this status code, it means the token we had is no longer valid.\n\t\t\t\tif (status === 401 && requestData.auth) {\n\t\t\t\t\tthis.manager.setToken(null!);\n\t\t\t\t}\n\n\t\t\t\t// The request will not succeed for some reason, parse the error returned from the api\n\t\t\t\tconst data = (await parseResponse(res)) as DiscordErrorData | OAuthErrorData;\n\t\t\t\t// throw the API error\n\t\t\t\tthrow new DiscordAPIError(data, 'code' in data ? data.code : data.error, status, method, url, requestData);\n\t\t\t}\n\n\t\t\treturn res;\n\t\t}\n\t}\n}\n\ninterface PolyFillAbortSignal {\n\treadonly aborted: boolean;\n\taddEventListener(type: 'abort', listener: () => void): void;\n\tremoveEventListener(type: 'abort', listener: () => void): void;\n}\n","import { Blob, Buffer } from 'node:buffer';\nimport { URLSearchParams } from 'node:url';\nimport { types } from 'node:util';\nimport type { RESTPatchAPIChannelJSONBody } from 'discord-api-types/v10';\nimport { FormData, type Dispatcher, type RequestInit } from 'undici';\nimport type { RequestOptions } from '../REST.js';\nimport { RequestMethod } from '../RequestManager.js';\n\nexport function parseHeader(header: string[] | string | undefined): string | undefined {\n\tif (header === undefined || typeof header === 'string') {\n\t\treturn header;\n\t}\n\n\treturn header.join(';');\n}\n\nfunction serializeSearchParam(value: unknown): string | null {\n\tswitch (typeof value) {\n\t\tcase 'string':\n\t\t\treturn value;\n\t\tcase 'number':\n\t\tcase 'bigint':\n\t\tcase 'boolean':\n\t\t\treturn value.toString();\n\t\tcase 'object':\n\t\t\tif (value === null) return null;\n\t\t\tif (value instanceof Date) {\n\t\t\t\treturn Number.isNaN(value.getTime()) ? null : value.toISOString();\n\t\t\t}\n\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-base-to-string\n\t\t\tif (typeof value.toString === 'function' && value.toString !== Object.prototype.toString) return value.toString();\n\t\t\treturn null;\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/**\n * Creates and populates an URLSearchParams instance from an object, stripping\n * out null and undefined values, while also coercing non-strings to strings.\n *\n * @param options - The options to use\n * @returns A populated URLSearchParams instance\n */\nexport function makeURLSearchParams(options?: Readonly) {\n\tconst params = new URLSearchParams();\n\tif (!options) return params;\n\n\tfor (const [key, value] of Object.entries(options)) {\n\t\tconst serialized = serializeSearchParam(value);\n\t\tif (serialized !== null) params.append(key, serialized);\n\t}\n\n\treturn params;\n}\n\n/**\n * Converts the response to usable data\n *\n * @param res - The fetch response\n */\nexport async function parseResponse(res: Dispatcher.ResponseData): Promise {\n\tconst header = parseHeader(res.headers['content-type']);\n\tif (header?.startsWith('application/json')) {\n\t\treturn res.body.json();\n\t}\n\n\treturn res.body.arrayBuffer();\n}\n\n/**\n * Check whether a request falls under a sublimit\n *\n * @param bucketRoute - The buckets route identifier\n * @param body - The options provided as JSON data\n * @param method - The HTTP method that will be used to make the request\n * @returns Whether the request falls under a sublimit\n */\nexport function hasSublimit(bucketRoute: string, body?: unknown, method?: string): boolean {\n\t// TODO: Update for new sublimits\n\t// Currently known sublimits:\n\t// Editing channel `name` or `topic`\n\tif (bucketRoute === '/channels/:id') {\n\t\tif (typeof body !== 'object' || body === null) return false;\n\t\t// This should never be a POST body, but just in case\n\t\tif (method !== RequestMethod.Patch) return false;\n\t\tconst castedBody = body as RESTPatchAPIChannelJSONBody;\n\t\treturn ['name', 'topic'].some((key) => Reflect.has(castedBody, key));\n\t}\n\n\t// If we are checking if a request has a sublimit on a route not checked above, sublimit all requests to avoid a flood of 429s\n\treturn true;\n}\n\nexport async function resolveBody(body: RequestInit['body']): Promise {\n\t// eslint-disable-next-line no-eq-null, eqeqeq\n\tif (body == null) {\n\t\treturn null;\n\t} else if (typeof body === 'string') {\n\t\treturn body;\n\t} else if (types.isUint8Array(body)) {\n\t\treturn body;\n\t} else if (types.isArrayBuffer(body)) {\n\t\treturn new Uint8Array(body);\n\t} else if (body instanceof URLSearchParams) {\n\t\treturn body.toString();\n\t} else if (body instanceof DataView) {\n\t\treturn new Uint8Array(body.buffer);\n\t} else if (body instanceof Blob) {\n\t\treturn new Uint8Array(await body.arrayBuffer());\n\t} else if (body instanceof FormData) {\n\t\treturn body;\n\t} else if ((body as Iterable)[Symbol.iterator]) {\n\t\tconst chunks = [...(body as Iterable)];\n\t\tconst length = chunks.reduce((a, b) => a + b.length, 0);\n\n\t\tconst uint8 = new Uint8Array(length);\n\t\tlet lengthUsed = 0;\n\n\t\treturn chunks.reduce((a, b) => {\n\t\t\ta.set(b, lengthUsed);\n\t\t\tlengthUsed += b.length;\n\t\t\treturn a;\n\t\t}, uint8);\n\t} else if ((body as AsyncIterable)[Symbol.asyncIterator]) {\n\t\tconst chunks: Uint8Array[] = [];\n\n\t\tfor await (const chunk of body as AsyncIterable) {\n\t\t\tchunks.push(chunk);\n\t\t}\n\n\t\treturn Buffer.concat(chunks);\n\t}\n\n\tthrow new TypeError(`Unable to resolve body.`);\n}\n\n/**\n * Check whether an error indicates that a retry can be attempted\n *\n * @param error - The error thrown by the network request\n * @returns Whether the error indicates a retry should be attempted\n */\nexport function shouldRetry(error: Error | NodeJS.ErrnoException) {\n\t// Retry for possible timed out requests\n\tif (error.name === 'AbortError') return true;\n\t// Downlevel ECONNRESET to retry as it may be recoverable\n\treturn ('code' in error && error.code === 'ECONNRESET') || error.message.includes('ECONNRESET');\n}\n","import { EventEmitter } from 'node:events';\nimport type { Collection } from '@discordjs/collection';\nimport type { request, Dispatcher } from 'undici';\nimport { CDN } from './CDN.js';\nimport {\n\tRequestManager,\n\tRequestMethod,\n\ttype HashData,\n\ttype HandlerRequestData,\n\ttype InternalRequest,\n\ttype RequestData,\n\ttype RouteLike,\n} from './RequestManager.js';\nimport type { IHandler } from './handlers/IHandler.js';\nimport { DefaultRestOptions, RESTEvents } from './utils/constants.js';\nimport { parseResponse } from './utils/utils.js';\n\n/**\n * Options to be passed when creating the REST instance\n */\nexport interface RESTOptions {\n\t/**\n\t * The agent to set globally\n\t */\n\tagent: Dispatcher;\n\t/**\n\t * The base api path, without version\n\t *\n\t * @defaultValue `'https://discord.com/api'`\n\t */\n\tapi: string;\n\t/**\n\t * The authorization prefix to use for requests, useful if you want to use\n\t * bearer tokens\n\t *\n\t * @defaultValue `'Bot'`\n\t */\n\tauthPrefix: 'Bearer' | 'Bot';\n\t/**\n\t * The cdn path\n\t *\n\t * @defaultValue 'https://cdn.discordapp.com'\n\t */\n\tcdn: string;\n\t/**\n\t * How many requests to allow sending per second (Infinity for unlimited, 50 for the standard global limit used by Discord)\n\t *\n\t * @defaultValue `50`\n\t */\n\tglobalRequestsPerSecond: number;\n\t/**\n\t * The amount of time in milliseconds that passes between each hash sweep. (defaults to 1h)\n\t *\n\t * @defaultValue `3_600_000`\n\t */\n\thandlerSweepInterval: number;\n\t/**\n\t * The maximum amount of time a hash can exist in milliseconds without being hit with a request (defaults to 24h)\n\t *\n\t * @defaultValue `86_400_000`\n\t */\n\thashLifetime: number;\n\t/**\n\t * The amount of time in milliseconds that passes between each hash sweep. (defaults to 4h)\n\t *\n\t * @defaultValue `14_400_000`\n\t */\n\thashSweepInterval: number;\n\t/**\n\t * Additional headers to send for all API requests\n\t *\n\t * @defaultValue `{}`\n\t */\n\theaders: Record;\n\t/**\n\t * The number of invalid REST requests (those that return 401, 403, or 429) in a 10 minute window between emitted warnings (0 for no warnings).\n\t * That is, if set to 500, warnings will be emitted at invalid request number 500, 1000, 1500, and so on.\n\t *\n\t * @defaultValue `0`\n\t */\n\tinvalidRequestWarningInterval: number;\n\t/**\n\t * The extra offset to add to rate limits in milliseconds\n\t *\n\t * @defaultValue `50`\n\t */\n\toffset: number;\n\t/**\n\t * Determines how rate limiting and pre-emptive throttling should be handled.\n\t * When an array of strings, each element is treated as a prefix for the request route\n\t * (e.g. `/channels` to match any route starting with `/channels` such as `/channels/:id/messages`)\n\t * for which to throw {@link RateLimitError}s. All other request routes will be queued normally\n\t *\n\t * @defaultValue `null`\n\t */\n\trejectOnRateLimit: RateLimitQueueFilter | string[] | null;\n\t/**\n\t * The number of retries for errors with the 500 code, or errors\n\t * that timeout\n\t *\n\t * @defaultValue `3`\n\t */\n\tretries: number;\n\t/**\n\t * The time to wait in milliseconds before a request is aborted\n\t *\n\t * @defaultValue `15_000`\n\t */\n\ttimeout: number;\n\t/**\n\t * Extra information to add to the user agent\n\t *\n\t * @defaultValue `Node.js ${process.version}`\n\t */\n\tuserAgentAppendix: string;\n\t/**\n\t * The version of the API to use\n\t *\n\t * @defaultValue `'10'`\n\t */\n\tversion: string;\n}\n\n/**\n * Data emitted on `RESTEvents.RateLimited`\n */\nexport interface RateLimitData {\n\t/**\n\t * Whether the rate limit that was reached was the global limit\n\t */\n\tglobal: boolean;\n\t/**\n\t * The bucket hash for this request\n\t */\n\thash: string;\n\t/**\n\t * The amount of requests we can perform before locking requests\n\t */\n\tlimit: number;\n\t/**\n\t * The major parameter of the route\n\t *\n\t * For example, in `/channels/x`, this will be `x`.\n\t * If there is no major parameter (e.g: `/bot/gateway`) this will be `global`.\n\t */\n\tmajorParameter: string;\n\t/**\n\t * The HTTP method being performed\n\t */\n\tmethod: string;\n\t/**\n\t * The route being hit in this request\n\t */\n\troute: string;\n\t/**\n\t * The time, in milliseconds, until the request-lock is reset\n\t */\n\ttimeToReset: number;\n\t/**\n\t * The full URL for this request\n\t */\n\turl: string;\n}\n\n/**\n * A function that determines whether the rate limit hit should throw an Error\n */\nexport type RateLimitQueueFilter = (rateLimitData: RateLimitData) => Promise | boolean;\n\nexport interface APIRequest {\n\t/**\n\t * The data that was used to form the body of this request\n\t */\n\tdata: HandlerRequestData;\n\t/**\n\t * The HTTP method used in this request\n\t */\n\tmethod: string;\n\t/**\n\t * Additional HTTP options for this request\n\t */\n\toptions: RequestOptions;\n\t/**\n\t * The full path used to make the request\n\t */\n\tpath: RouteLike;\n\t/**\n\t * The number of times this request has been attempted\n\t */\n\tretries: number;\n\t/**\n\t * The API route identifying the ratelimit for this request\n\t */\n\troute: string;\n}\n\nexport interface InvalidRequestWarningData {\n\t/**\n\t * Number of invalid requests that have been made in the window\n\t */\n\tcount: number;\n\t/**\n\t * Time in milliseconds remaining before the count resets\n\t */\n\tremainingTime: number;\n}\n\nexport interface RestEvents {\n\thandlerSweep: [sweptHandlers: Collection];\n\thashSweep: [sweptHashes: Collection];\n\tinvalidRequestWarning: [invalidRequestInfo: InvalidRequestWarningData];\n\tnewListener: [name: string, listener: (...args: any) => void];\n\trateLimited: [rateLimitInfo: RateLimitData];\n\tremoveListener: [name: string, listener: (...args: any) => void];\n\tresponse: [request: APIRequest, response: Dispatcher.ResponseData];\n\trestDebug: [info: string];\n}\n\nexport interface REST {\n\temit: ((event: K, ...args: RestEvents[K]) => boolean) &\n\t\t((event: Exclude, ...args: any[]) => boolean);\n\n\toff: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\ton: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tonce: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tremoveAllListeners: ((event?: K) => this) &\n\t\t((event?: Exclude) => this);\n}\n\nexport type RequestOptions = Exclude[1], undefined>;\n\nexport class REST extends EventEmitter {\n\tpublic readonly cdn: CDN;\n\n\tpublic readonly requestManager: RequestManager;\n\n\tpublic constructor(options: Partial = {}) {\n\t\tsuper();\n\t\tthis.cdn = new CDN(options.cdn ?? DefaultRestOptions.cdn);\n\t\tthis.requestManager = new RequestManager(options)\n\t\t\t.on(RESTEvents.Debug, this.emit.bind(this, RESTEvents.Debug))\n\t\t\t.on(RESTEvents.RateLimited, this.emit.bind(this, RESTEvents.RateLimited))\n\t\t\t.on(RESTEvents.InvalidRequestWarning, this.emit.bind(this, RESTEvents.InvalidRequestWarning))\n\t\t\t.on(RESTEvents.HashSweep, this.emit.bind(this, RESTEvents.HashSweep));\n\n\t\tthis.on('newListener', (name, listener) => {\n\t\t\tif (name === RESTEvents.Response) this.requestManager.on(name, listener);\n\t\t});\n\t\tthis.on('removeListener', (name, listener) => {\n\t\t\tif (name === RESTEvents.Response) this.requestManager.off(name, listener);\n\t\t});\n\t}\n\n\t/**\n\t * Gets the agent set for this instance\n\t */\n\tpublic getAgent() {\n\t\treturn this.requestManager.agent;\n\t}\n\n\t/**\n\t * Sets the default agent to use for requests performed by this instance\n\t *\n\t * @param agent - Sets the agent to use\n\t */\n\tpublic setAgent(agent: Dispatcher) {\n\t\tthis.requestManager.setAgent(agent);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the authorization token that should be used for requests\n\t *\n\t * @param token - The authorization token to use\n\t */\n\tpublic setToken(token: string) {\n\t\tthis.requestManager.setToken(token);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a get request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async get(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Get });\n\t}\n\n\t/**\n\t * Runs a delete request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async delete(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Delete });\n\t}\n\n\t/**\n\t * Runs a post request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async post(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Post });\n\t}\n\n\t/**\n\t * Runs a put request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async put(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Put });\n\t}\n\n\t/**\n\t * Runs a patch request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async patch(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Patch });\n\t}\n\n\t/**\n\t * Runs a request from the api\n\t *\n\t * @param options - Request options\n\t */\n\tpublic async request(options: InternalRequest) {\n\t\tconst response = await this.raw(options);\n\t\treturn parseResponse(response);\n\t}\n\n\t/**\n\t * Runs a request from the API, yielding the raw Response object\n\t *\n\t * @param options - Request options\n\t */\n\tpublic async raw(options: InternalRequest) {\n\t\treturn this.requestManager.queueRequest(options);\n\t}\n}\n","export * from './lib/CDN.js';\nexport * from './lib/errors/DiscordAPIError.js';\nexport * from './lib/errors/HTTPError.js';\nexport * from './lib/errors/RateLimitError.js';\nexport * from './lib/RequestManager.js';\nexport * from './lib/REST.js';\nexport * from './lib/utils/constants.js';\nexport { makeURLSearchParams, parseResponse } from './lib/utils/utils.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/rest/#readme | @discordjs/rest} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\n// eslint-disable-next-line @typescript-eslint/no-inferrable-types\nexport const version: string = '1.5.0';\n"],"mappings":";;;;AACA,SAAS,WAAW;;;ACDpB,OAAO,aAAa;AACpB,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AAGf,IAAM,mBAAmB;AAEzB,IAAM,qBAAqB;AAAA,EACjC,IAAI,QAAQ;AACX,WAAO,IAAI,MAAM;AAAA,MAChB,SAAS;AAAA,QACR,SAAS;AAAA,MACV;AAAA,IACD,CAAC;AAAA,EACF;AAAA,EACA,KAAK;AAAA,EACL,YAAY;AAAA,EACZ,KAAK;AAAA,EACL,SAAS,CAAC;AAAA,EACV,+BAA+B;AAAA,EAC/B,yBAAyB;AAAA,EACzB,QAAQ;AAAA,EACR,mBAAmB;AAAA,EACnB,SAAS;AAAA,EACT,SAAS;AAAA,EACT,mBAAmB,WAAW,QAAQ;AAAA,EACtC,SAAS;AAAA,EACT,mBAAmB;AAAA,EACnB,cAAc;AAAA,EACd,sBAAsB;AACvB;AAKO,IAAW,aAAX,kBAAWA,gBAAX;AACN,EAAAA,YAAA,WAAQ;AACR,EAAAA,YAAA,kBAAe;AACf,EAAAA,YAAA,eAAY;AACZ,EAAAA,YAAA,2BAAwB;AACxB,EAAAA,YAAA,iBAAc;AACd,EAAAA,YAAA,cAAW;AANM,SAAAA;AAAA,GAAA;AASX,IAAM,qBAAqB,CAAC,QAAQ,OAAO,OAAO,QAAQ,KAAK;AAC/D,IAAM,6BAA6B,CAAC,OAAO,MAAM;AACjD,IAAM,gBAAgB,CAAC,IAAI,IAAI,IAAI,KAAK,KAAK,KAAK,MAAO,MAAO,IAAK;;;ADerE,IAAM,MAAN,MAAU;AAAA,EACT,YAA6B,OAAe,mBAAmB,KAAK;AAAvC;AAAA,EAAwC;AAAA,EASrE,SAAS,UAAkB,WAAmB,SAAiD;AACrG,WAAO,KAAK,QAAQ,eAA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EAAE,GAAG,SAAS,WAAW,0BAA2B,CAAC;AAAA,EAC1E;AAAA,EAQA,MAAa,IAAI,WAAsB,UAAuB,CAAC,GAAG;AACjE,WAAO,KAAK,QAAQ,EAAE,GAAG,SAAS,WAAW,wBAA0B,CAAC;AAAA,EACzE;AAAA,EAQA,MAAa,MAAM,WAAsB,UAAuB,CAAC,GAAG;AACnE,WAAO,KAAK,QAAQ,EAAE,GAAG,SAAS,WAAW,4BAA4B,CAAC;AAAA,EAC3E;AAAA,EAOA,MAAa,QAAQ,SAA0B;AAC9C,UAAM,WAAW,MAAM,KAAK,IAAI,OAAO;AACvC,WAAO,cAAc,QAAQ;AAAA,EAC9B;AAAA,EAOA,MAAa,IAAI,SAA0B;AAC1C,WAAO,KAAK,eAAe,aAAa,OAAO;AAAA,EAChD;AACD;AArHa;;;AC9NN,IAAM,UAAkB;","names":["RESTEvents","Blob","Buffer","FormData","Buffer","Buffer","limit","timeout","res","RequestMethod","request","FormData","Buffer","Blob","EventEmitter","EventEmitter"]} \ No newline at end of file +{"version":3,"sources":["../src/lib/CDN.ts","../src/lib/utils/constants.ts","../src/lib/errors/DiscordAPIError.ts","../src/lib/errors/HTTPError.ts","../src/lib/errors/RateLimitError.ts","../src/lib/RequestManager.ts","../src/lib/handlers/BurstHandler.ts","../src/lib/utils/utils.ts","../src/lib/handlers/Shared.ts","../src/lib/handlers/SequentialHandler.ts","../src/lib/REST.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable jsdoc/check-param-names */\nimport { URL } from 'node:url';\nimport {\n\tALLOWED_EXTENSIONS,\n\tALLOWED_SIZES,\n\tALLOWED_STICKER_EXTENSIONS,\n\tDefaultRestOptions,\n\ttype ImageExtension,\n\ttype ImageSize,\n\ttype StickerExtension,\n} from './utils/constants.js';\n\n/**\n * The options used for image URLs\n */\nexport interface BaseImageURLOptions {\n\t/**\n\t * The extension to use for the image URL\n\t *\n\t * @defaultValue `'webp'`\n\t */\n\textension?: ImageExtension;\n\t/**\n\t * The size specified in the image URL\n\t */\n\tsize?: ImageSize;\n}\n\n/**\n * The options used for image URLs with animated content\n */\nexport interface ImageURLOptions extends BaseImageURLOptions {\n\t/**\n\t * Whether or not to prefer the static version of an image asset.\n\t */\n\tforceStatic?: boolean;\n}\n\n/**\n * The options to use when making a CDN URL\n */\nexport interface MakeURLOptions {\n\t/**\n\t * The allowed extensions that can be used\n\t */\n\tallowedExtensions?: readonly string[];\n\t/**\n\t * The extension to use for the image URL\n\t *\n\t * @defaultValue `'webp'`\n\t */\n\textension?: string | undefined;\n\t/**\n\t * The size specified in the image URL\n\t */\n\tsize?: ImageSize;\n}\n\n/**\n * The CDN link builder\n */\nexport class CDN {\n\tpublic constructor(private readonly base: string = DefaultRestOptions.cdn) {}\n\n\t/**\n\t * Generates an app asset URL for a client's asset.\n\t *\n\t * @param clientId - The client id that has the asset\n\t * @param assetHash - The hash provided by Discord for this asset\n\t * @param options - Optional options for the asset\n\t */\n\tpublic appAsset(clientId: string, assetHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-assets/${clientId}/${assetHash}`, options);\n\t}\n\n\t/**\n\t * Generates an app icon URL for a client's icon.\n\t *\n\t * @param clientId - The client id that has the icon\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic appIcon(clientId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-icons/${clientId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates an avatar URL, e.g. for a user or a webhook.\n\t *\n\t * @param id - The id that has the icon\n\t * @param avatarHash - The hash provided by Discord for this avatar\n\t * @param options - Optional options for the avatar\n\t */\n\tpublic avatar(id: string, avatarHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/avatars/${id}/${avatarHash}`, avatarHash, options);\n\t}\n\n\t/**\n\t * Generates a banner URL, e.g. for a user or a guild.\n\t *\n\t * @param id - The id that has the banner splash\n\t * @param bannerHash - The hash provided by Discord for this banner\n\t * @param options - Optional options for the banner\n\t */\n\tpublic banner(id: string, bannerHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/banners/${id}/${bannerHash}`, bannerHash, options);\n\t}\n\n\t/**\n\t * Generates an icon URL for a channel, e.g. a group DM.\n\t *\n\t * @param channelId - The channel id that has the icon\n\t * @param iconHash - The hash provided by Discord for this channel\n\t * @param options - Optional options for the icon\n\t */\n\tpublic channelIcon(channelId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/channel-icons/${channelId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates the default avatar URL for a discriminator.\n\t *\n\t * @param discriminator - The discriminator modulo 5\n\t */\n\tpublic defaultAvatar(discriminator: number): string {\n\t\treturn this.makeURL(`/embed/avatars/${discriminator}`, { extension: 'png' });\n\t}\n\n\t/**\n\t * Generates a discovery splash URL for a guild's discovery splash.\n\t *\n\t * @param guildId - The guild id that has the discovery splash\n\t * @param splashHash - The hash provided by Discord for this splash\n\t * @param options - Optional options for the splash\n\t */\n\tpublic discoverySplash(guildId: string, splashHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/discovery-splashes/${guildId}/${splashHash}`, options);\n\t}\n\n\t/**\n\t * Generates an emoji's URL for an emoji.\n\t *\n\t * @param emojiId - The emoji id\n\t * @param extension - The extension of the emoji\n\t */\n\tpublic emoji(emojiId: string, extension?: ImageExtension): string {\n\t\treturn this.makeURL(`/emojis/${emojiId}`, { extension });\n\t}\n\n\t/**\n\t * Generates a guild member avatar URL.\n\t *\n\t * @param guildId - The id of the guild\n\t * @param userId - The id of the user\n\t * @param avatarHash - The hash provided by Discord for this avatar\n\t * @param options - Optional options for the avatar\n\t */\n\tpublic guildMemberAvatar(\n\t\tguildId: string,\n\t\tuserId: string,\n\t\tavatarHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/avatars/${avatarHash}`, avatarHash, options);\n\t}\n\n\t/**\n\t * Generates a guild member banner URL.\n\t *\n\t * @param guildId - The id of the guild\n\t * @param userId - The id of the user\n\t * @param bannerHash - The hash provided by Discord for this banner\n\t * @param options - Optional options for the banner\n\t */\n\tpublic guildMemberBanner(\n\t\tguildId: string,\n\t\tuserId: string,\n\t\tbannerHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.dynamicMakeURL(`/guilds/${guildId}/users/${userId}/banner`, bannerHash, options);\n\t}\n\n\t/**\n\t * Generates an icon URL, e.g. for a guild.\n\t *\n\t * @param id - The id that has the icon splash\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic icon(id: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.dynamicMakeURL(`/icons/${id}/${iconHash}`, iconHash, options);\n\t}\n\n\t/**\n\t * Generates a URL for the icon of a role\n\t *\n\t * @param roleId - The id of the role that has the icon\n\t * @param roleIconHash - The hash provided by Discord for this role icon\n\t * @param options - Optional options for the role icon\n\t */\n\tpublic roleIcon(roleId: string, roleIconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/role-icons/${roleId}/${roleIconHash}`, options);\n\t}\n\n\t/**\n\t * Generates a guild invite splash URL for a guild's invite splash.\n\t *\n\t * @param guildId - The guild id that has the invite splash\n\t * @param splashHash - The hash provided by Discord for this splash\n\t * @param options - Optional options for the splash\n\t */\n\tpublic splash(guildId: string, splashHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/splashes/${guildId}/${splashHash}`, options);\n\t}\n\n\t/**\n\t * Generates a sticker URL.\n\t *\n\t * @param stickerId - The sticker id\n\t * @param extension - The extension of the sticker\n\t * @privateRemarks\n\t * Stickers cannot have a `.webp` extension, so we default to a `.png`\n\t */\n\tpublic sticker(stickerId: string, extension: StickerExtension = 'png'): string {\n\t\treturn this.makeURL(`/stickers/${stickerId}`, { allowedExtensions: ALLOWED_STICKER_EXTENSIONS, extension });\n\t}\n\n\t/**\n\t * Generates a sticker pack banner URL.\n\t *\n\t * @param bannerId - The banner id\n\t * @param options - Optional options for the banner\n\t */\n\tpublic stickerPackBanner(bannerId: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/app-assets/710982414301790216/store/${bannerId}`, options);\n\t}\n\n\t/**\n\t * Generates a team icon URL for a team's icon.\n\t *\n\t * @param teamId - The team id that has the icon\n\t * @param iconHash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the icon\n\t */\n\tpublic teamIcon(teamId: string, iconHash: string, options?: Readonly): string {\n\t\treturn this.makeURL(`/team-icons/${teamId}/${iconHash}`, options);\n\t}\n\n\t/**\n\t * Generates a cover image for a guild scheduled event.\n\t *\n\t * @param scheduledEventId - The scheduled event id\n\t * @param coverHash - The hash provided by discord for this cover image\n\t * @param options - Optional options for the cover image\n\t */\n\tpublic guildScheduledEventCover(\n\t\tscheduledEventId: string,\n\t\tcoverHash: string,\n\t\toptions?: Readonly,\n\t): string {\n\t\treturn this.makeURL(`/guild-events/${scheduledEventId}/${coverHash}`, options);\n\t}\n\n\t/**\n\t * Constructs the URL for the resource, checking whether or not `hash` starts with `a_` if `dynamic` is set to `true`.\n\t *\n\t * @param route - The base cdn route\n\t * @param hash - The hash provided by Discord for this icon\n\t * @param options - Optional options for the link\n\t */\n\tprivate dynamicMakeURL(\n\t\troute: string,\n\t\thash: string,\n\t\t{ forceStatic = false, ...options }: Readonly = {},\n\t): string {\n\t\treturn this.makeURL(route, !forceStatic && hash.startsWith('a_') ? { ...options, extension: 'gif' } : options);\n\t}\n\n\t/**\n\t * Constructs the URL for the resource\n\t *\n\t * @param route - The base cdn route\n\t * @param options - The extension/size options for the link\n\t */\n\tprivate makeURL(\n\t\troute: string,\n\t\t{ allowedExtensions = ALLOWED_EXTENSIONS, extension = 'webp', size }: Readonly = {},\n\t): string {\n\t\t// eslint-disable-next-line no-param-reassign\n\t\textension = String(extension).toLowerCase();\n\n\t\tif (!allowedExtensions.includes(extension)) {\n\t\t\tthrow new RangeError(`Invalid extension provided: ${extension}\\nMust be one of: ${allowedExtensions.join(', ')}`);\n\t\t}\n\n\t\tif (size && !ALLOWED_SIZES.includes(size)) {\n\t\t\tthrow new RangeError(`Invalid size provided: ${size}\\nMust be one of: ${ALLOWED_SIZES.join(', ')}`);\n\t\t}\n\n\t\tconst url = new URL(`${this.base}${route}.${extension}`);\n\n\t\tif (size) {\n\t\t\turl.searchParams.set('size', String(size));\n\t\t}\n\n\t\treturn url.toString();\n\t}\n}\n","import process from 'node:process';\nimport { APIVersion } from 'discord-api-types/v10';\nimport { Agent } from 'undici';\nimport type { RESTOptions } from '../REST.js';\n\nexport const DefaultUserAgent =\n\t`DiscordBot (https://discord.js.org, 1.7.1)` as `DiscordBot (https://discord.js.org, ${string})`;\n\n/**\n * The default string to append onto the user agent.\n */\nexport const DefaultUserAgentAppendix = process.release?.name === 'node' ? `Node.js/${process.version}` : '';\n\nexport const DefaultRestOptions = {\n\tget agent() {\n\t\treturn new Agent({\n\t\t\tconnect: {\n\t\t\t\ttimeout: 30_000,\n\t\t\t},\n\t\t});\n\t},\n\tapi: 'https://discord.com/api',\n\tauthPrefix: 'Bot',\n\tcdn: 'https://cdn.discordapp.com',\n\theaders: {},\n\tinvalidRequestWarningInterval: 0,\n\tglobalRequestsPerSecond: 50,\n\toffset: 50,\n\trejectOnRateLimit: null,\n\tretries: 3,\n\ttimeout: 15_000,\n\tuserAgentAppendix: DefaultUserAgentAppendix,\n\tversion: APIVersion,\n\thashSweepInterval: 14_400_000, // 4 Hours\n\thashLifetime: 86_400_000, // 24 Hours\n\thandlerSweepInterval: 3_600_000, // 1 Hour\n} as const satisfies Required;\n\n/**\n * The events that the REST manager emits\n */\nexport enum RESTEvents {\n\tDebug = 'restDebug',\n\tHandlerSweep = 'handlerSweep',\n\tHashSweep = 'hashSweep',\n\tInvalidRequestWarning = 'invalidRequestWarning',\n\tRateLimited = 'rateLimited',\n\tResponse = 'response',\n}\n\nexport const ALLOWED_EXTENSIONS = ['webp', 'png', 'jpg', 'jpeg', 'gif'] as const satisfies readonly string[];\nexport const ALLOWED_STICKER_EXTENSIONS = ['png', 'json', 'gif'] as const satisfies readonly string[];\nexport const ALLOWED_SIZES = [16, 32, 64, 128, 256, 512, 1_024, 2_048, 4_096] as const satisfies readonly number[];\n\nexport type ImageExtension = (typeof ALLOWED_EXTENSIONS)[number];\nexport type StickerExtension = (typeof ALLOWED_STICKER_EXTENSIONS)[number];\nexport type ImageSize = (typeof ALLOWED_SIZES)[number];\n\nexport const OverwrittenMimeTypes = {\n\t// https://github.com/discordjs/discord.js/issues/8557\n\t'image/apng': 'image/png',\n} as const satisfies Readonly>;\n\nexport const BurstHandlerMajorIdKey = 'burst';\n","import type { InternalRequest, RawFile } from '../RequestManager.js';\n\ninterface DiscordErrorFieldInformation {\n\tcode: string;\n\tmessage: string;\n}\n\ninterface DiscordErrorGroupWrapper {\n\t_errors: DiscordError[];\n}\n\ntype DiscordError = DiscordErrorFieldInformation | DiscordErrorGroupWrapper | string | { [k: string]: DiscordError };\n\nexport interface DiscordErrorData {\n\tcode: number;\n\terrors?: DiscordError;\n\tmessage: string;\n}\n\nexport interface OAuthErrorData {\n\terror: string;\n\terror_description?: string;\n}\n\nexport interface RequestBody {\n\tfiles: RawFile[] | undefined;\n\tjson: unknown | undefined;\n}\n\nfunction isErrorGroupWrapper(error: DiscordError): error is DiscordErrorGroupWrapper {\n\treturn Reflect.has(error as Record, '_errors');\n}\n\nfunction isErrorResponse(error: DiscordError): error is DiscordErrorFieldInformation {\n\treturn typeof Reflect.get(error as Record, 'message') === 'string';\n}\n\n/**\n * Represents an API error returned by Discord\n */\nexport class DiscordAPIError extends Error {\n\tpublic requestBody: RequestBody;\n\n\t/**\n\t * @param rawError - The error reported by Discord\n\t * @param code - The error code reported by Discord\n\t * @param status - The status code of the response\n\t * @param method - The method of the request that erred\n\t * @param url - The url of the request that erred\n\t * @param bodyData - The unparsed data for the request that errored\n\t */\n\tpublic constructor(\n\t\tpublic rawError: DiscordErrorData | OAuthErrorData,\n\t\tpublic code: number | string,\n\t\tpublic status: number,\n\t\tpublic method: string,\n\t\tpublic url: string,\n\t\tbodyData: Pick,\n\t) {\n\t\tsuper(DiscordAPIError.getMessage(rawError));\n\n\t\tthis.requestBody = { files: bodyData.files, json: bodyData.body };\n\t}\n\n\t/**\n\t * The name of the error\n\t */\n\tpublic override get name(): string {\n\t\treturn `${DiscordAPIError.name}[${this.code}]`;\n\t}\n\n\tprivate static getMessage(error: DiscordErrorData | OAuthErrorData) {\n\t\tlet flattened = '';\n\t\tif ('code' in error) {\n\t\t\tif (error.errors) {\n\t\t\t\tflattened = [...this.flattenDiscordError(error.errors)].join('\\n');\n\t\t\t}\n\n\t\t\treturn error.message && flattened\n\t\t\t\t? `${error.message}\\n${flattened}`\n\t\t\t\t: error.message || flattened || 'Unknown Error';\n\t\t}\n\n\t\treturn error.error_description ?? 'No Description';\n\t}\n\n\tprivate static *flattenDiscordError(obj: DiscordError, key = ''): IterableIterator {\n\t\tif (isErrorResponse(obj)) {\n\t\t\treturn yield `${key.length ? `${key}[${obj.code}]` : `${obj.code}`}: ${obj.message}`.trim();\n\t\t}\n\n\t\tfor (const [otherKey, val] of Object.entries(obj)) {\n\t\t\tconst nextKey = otherKey.startsWith('_')\n\t\t\t\t? key\n\t\t\t\t: key\n\t\t\t\t? Number.isNaN(Number(otherKey))\n\t\t\t\t\t? `${key}.${otherKey}`\n\t\t\t\t\t: `${key}[${otherKey}]`\n\t\t\t\t: otherKey;\n\n\t\t\tif (typeof val === 'string') {\n\t\t\t\tyield val;\n\t\t\t} else if (isErrorGroupWrapper(val)) {\n\t\t\t\tfor (const error of val._errors) {\n\t\t\t\t\tyield* this.flattenDiscordError(error, nextKey);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tyield* this.flattenDiscordError(val, nextKey);\n\t\t\t}\n\t\t}\n\t}\n}\n","import { STATUS_CODES } from 'node:http';\nimport type { InternalRequest } from '../RequestManager.js';\nimport type { RequestBody } from './DiscordAPIError.js';\n\n/**\n * Represents a HTTP error\n */\nexport class HTTPError extends Error {\n\tpublic requestBody: RequestBody;\n\n\tpublic override name = HTTPError.name;\n\n\t/**\n\t * @param status - The status code of the response\n\t * @param method - The method of the request that erred\n\t * @param url - The url of the request that erred\n\t * @param bodyData - The unparsed data for the request that errored\n\t */\n\tpublic constructor(\n\t\tpublic status: number,\n\t\tpublic method: string,\n\t\tpublic url: string,\n\t\tbodyData: Pick,\n\t) {\n\t\tsuper(STATUS_CODES[status]);\n\n\t\tthis.requestBody = { files: bodyData.files, json: bodyData.body };\n\t}\n}\n","import type { RateLimitData } from '../REST.js';\n\nexport class RateLimitError extends Error implements RateLimitData {\n\tpublic timeToReset: number;\n\n\tpublic limit: number;\n\n\tpublic method: string;\n\n\tpublic hash: string;\n\n\tpublic url: string;\n\n\tpublic route: string;\n\n\tpublic majorParameter: string;\n\n\tpublic global: boolean;\n\n\tpublic constructor({ timeToReset, limit, method, hash, url, route, majorParameter, global }: RateLimitData) {\n\t\tsuper();\n\t\tthis.timeToReset = timeToReset;\n\t\tthis.limit = limit;\n\t\tthis.method = method;\n\t\tthis.hash = hash;\n\t\tthis.url = url;\n\t\tthis.route = route;\n\t\tthis.majorParameter = majorParameter;\n\t\tthis.global = global;\n\t}\n\n\t/**\n\t * The name of the error\n\t */\n\tpublic override get name(): string {\n\t\treturn `${RateLimitError.name}[${this.route}]`;\n\t}\n}\n","import { Blob, Buffer } from 'node:buffer';\nimport { EventEmitter } from 'node:events';\nimport { setInterval, clearInterval } from 'node:timers';\nimport type { URLSearchParams } from 'node:url';\nimport { Collection } from '@discordjs/collection';\nimport { lazy } from '@discordjs/util';\nimport { DiscordSnowflake } from '@sapphire/snowflake';\nimport { FormData, type RequestInit, type BodyInit, type Dispatcher, type Agent } from 'undici';\nimport type { RESTOptions, RestEvents, RequestOptions } from './REST.js';\nimport { BurstHandler } from './handlers/BurstHandler.js';\nimport type { IHandler } from './handlers/IHandler.js';\nimport { SequentialHandler } from './handlers/SequentialHandler.js';\nimport {\n\tBurstHandlerMajorIdKey,\n\tDefaultRestOptions,\n\tDefaultUserAgent,\n\tOverwrittenMimeTypes,\n\tRESTEvents,\n} from './utils/constants.js';\nimport { resolveBody } from './utils/utils.js';\n\n// Make this a lazy dynamic import as file-type is a pure ESM package\nconst getFileType = lazy(async () => import('file-type'));\n\n/**\n * Represents a file to be added to the request\n */\nexport interface RawFile {\n\t/**\n\t * Content-Type of the file\n\t */\n\tcontentType?: string;\n\t/**\n\t * The actual data for the file\n\t */\n\tdata: Buffer | boolean | number | string;\n\t/**\n\t * An explicit key to use for key of the formdata field for this file.\n\t * When not provided, the index of the file in the files array is used in the form `files[${index}]`.\n\t * If you wish to alter the placeholder snowflake, you must provide this property in the same form (`files[${placeholder}]`)\n\t */\n\tkey?: string;\n\t/**\n\t * The name of the file\n\t */\n\tname: string;\n}\n\n/**\n * Represents possible data to be given to an endpoint\n */\nexport interface RequestData {\n\t/**\n\t * Whether to append JSON data to form data instead of `payload_json` when sending files\n\t */\n\tappendToFormData?: boolean;\n\t/**\n\t * If this request needs the `Authorization` header\n\t *\n\t * @defaultValue `true`\n\t */\n\tauth?: boolean;\n\t/**\n\t * The authorization prefix to use for this request, useful if you use this with bearer tokens\n\t *\n\t * @defaultValue `'Bot'`\n\t */\n\tauthPrefix?: 'Bearer' | 'Bot';\n\t/**\n\t * The body to send to this request.\n\t * If providing as BodyInit, set `passThroughBody: true`\n\t */\n\tbody?: BodyInit | unknown;\n\t/**\n\t * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} to use for the request.\n\t */\n\tdispatcher?: Agent;\n\t/**\n\t * Files to be attached to this request\n\t */\n\tfiles?: RawFile[] | undefined;\n\t/**\n\t * Additional headers to add to this request\n\t */\n\theaders?: Record;\n\t/**\n\t * Whether to pass-through the body property directly to `fetch()`.\n\t * This only applies when files is NOT present\n\t */\n\tpassThroughBody?: boolean;\n\t/**\n\t * Query string parameters to append to the called endpoint\n\t */\n\tquery?: URLSearchParams;\n\t/**\n\t * Reason to show in the audit logs\n\t */\n\treason?: string | undefined;\n\t/**\n\t * The signal to abort the queue entry or the REST call, where applicable\n\t */\n\tsignal?: AbortSignal | undefined;\n\t/**\n\t * If this request should be versioned\n\t *\n\t * @defaultValue `true`\n\t */\n\tversioned?: boolean;\n}\n\n/**\n * Possible headers for an API call\n */\nexport interface RequestHeaders {\n\tAuthorization?: string;\n\t'User-Agent': string;\n\t'X-Audit-Log-Reason'?: string;\n}\n\n/**\n * Possible API methods to be used when doing requests\n */\nexport enum RequestMethod {\n\tDelete = 'DELETE',\n\tGet = 'GET',\n\tPatch = 'PATCH',\n\tPost = 'POST',\n\tPut = 'PUT',\n}\n\nexport type RouteLike = `/${string}`;\n\n/**\n * Internal request options\n *\n * @internal\n */\nexport interface InternalRequest extends RequestData {\n\tfullRoute: RouteLike;\n\tmethod: RequestMethod;\n}\n\nexport type HandlerRequestData = Pick;\n\n/**\n * Parsed route data for an endpoint\n *\n * @internal\n */\nexport interface RouteData {\n\tbucketRoute: string;\n\tmajorParameter: string;\n\toriginal: RouteLike;\n}\n\n/**\n * Represents a hash and its associated fields\n *\n * @internal\n */\nexport interface HashData {\n\tlastAccess: number;\n\tvalue: string;\n}\n\nexport interface RequestManager {\n\temit: ((event: K, ...args: RestEvents[K]) => boolean) &\n\t\t((event: Exclude, ...args: any[]) => boolean);\n\n\toff: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\ton: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tonce: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tremoveAllListeners: ((event?: K) => this) &\n\t\t((event?: Exclude) => this);\n}\n\n/**\n * Represents the class that manages handlers for endpoints\n */\nexport class RequestManager extends EventEmitter {\n\t/**\n\t * The {@link https://undici.nodejs.org/#/docs/api/Agent | Agent} for all requests\n\t * performed by this manager.\n\t */\n\tpublic agent: Dispatcher | null = null;\n\n\t/**\n\t * The number of requests remaining in the global bucket\n\t */\n\tpublic globalRemaining: number;\n\n\t/**\n\t * The promise used to wait out the global rate limit\n\t */\n\tpublic globalDelay: Promise | null = null;\n\n\t/**\n\t * The timestamp at which the global bucket resets\n\t */\n\tpublic globalReset = -1;\n\n\t/**\n\t * API bucket hashes that are cached from provided routes\n\t */\n\tpublic readonly hashes = new Collection();\n\n\t/**\n\t * Request handlers created from the bucket hash and the major parameters\n\t */\n\tpublic readonly handlers = new Collection();\n\n\t#token: string | null = null;\n\n\tprivate hashTimer!: NodeJS.Timer;\n\n\tprivate handlerTimer!: NodeJS.Timer;\n\n\tpublic readonly options: RESTOptions;\n\n\tpublic constructor(options: Partial) {\n\t\tsuper();\n\t\tthis.options = { ...DefaultRestOptions, ...options };\n\t\tthis.options.offset = Math.max(0, this.options.offset);\n\t\tthis.globalRemaining = this.options.globalRequestsPerSecond;\n\t\tthis.agent = options.agent ?? null;\n\n\t\t// Start sweepers\n\t\tthis.setupSweepers();\n\t}\n\n\tprivate setupSweepers() {\n\t\t// eslint-disable-next-line unicorn/consistent-function-scoping\n\t\tconst validateMaxInterval = (interval: number) => {\n\t\t\tif (interval > 14_400_000) {\n\t\t\t\tthrow new Error('Cannot set an interval greater than 4 hours');\n\t\t\t}\n\t\t};\n\n\t\tif (this.options.hashSweepInterval !== 0 && this.options.hashSweepInterval !== Number.POSITIVE_INFINITY) {\n\t\t\tvalidateMaxInterval(this.options.hashSweepInterval);\n\t\t\tthis.hashTimer = setInterval(() => {\n\t\t\t\tconst sweptHashes = new Collection();\n\t\t\t\tconst currentDate = Date.now();\n\n\t\t\t\t// Begin sweeping hash based on lifetimes\n\t\t\t\tthis.hashes.sweep((val, key) => {\n\t\t\t\t\t// `-1` indicates a global hash\n\t\t\t\t\tif (val.lastAccess === -1) return false;\n\n\t\t\t\t\t// Check if lifetime has been exceeded\n\t\t\t\t\tconst shouldSweep = Math.floor(currentDate - val.lastAccess) > this.options.hashLifetime;\n\n\t\t\t\t\t// Add hash to collection of swept hashes\n\t\t\t\t\tif (shouldSweep) {\n\t\t\t\t\t\t// Add to swept hashes\n\t\t\t\t\t\tsweptHashes.set(key, val);\n\t\t\t\t\t}\n\n\t\t\t\t\t// Emit debug information\n\t\t\t\t\tthis.emit(RESTEvents.Debug, `Hash ${val.value} for ${key} swept due to lifetime being exceeded`);\n\n\t\t\t\t\treturn shouldSweep;\n\t\t\t\t});\n\n\t\t\t\t// Fire event\n\t\t\t\tthis.emit(RESTEvents.HashSweep, sweptHashes);\n\t\t\t}, this.options.hashSweepInterval).unref();\n\t\t}\n\n\t\tif (this.options.handlerSweepInterval !== 0 && this.options.handlerSweepInterval !== Number.POSITIVE_INFINITY) {\n\t\t\tvalidateMaxInterval(this.options.handlerSweepInterval);\n\t\t\tthis.handlerTimer = setInterval(() => {\n\t\t\t\tconst sweptHandlers = new Collection();\n\n\t\t\t\t// Begin sweeping handlers based on activity\n\t\t\t\tthis.handlers.sweep((val, key) => {\n\t\t\t\t\tconst { inactive } = val;\n\n\t\t\t\t\t// Collect inactive handlers\n\t\t\t\t\tif (inactive) {\n\t\t\t\t\t\tsweptHandlers.set(key, val);\n\t\t\t\t\t}\n\n\t\t\t\t\tthis.emit(RESTEvents.Debug, `Handler ${val.id} for ${key} swept due to being inactive`);\n\t\t\t\t\treturn inactive;\n\t\t\t\t});\n\n\t\t\t\t// Fire event\n\t\t\t\tthis.emit(RESTEvents.HandlerSweep, sweptHandlers);\n\t\t\t}, this.options.handlerSweepInterval).unref();\n\t\t}\n\t}\n\n\t/**\n\t * Sets the default agent to use for requests performed by this manager\n\t *\n\t * @param agent - The agent to use\n\t */\n\tpublic setAgent(agent: Dispatcher) {\n\t\tthis.agent = agent;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the authorization token that should be used for requests\n\t *\n\t * @param token - The authorization token to use\n\t */\n\tpublic setToken(token: string) {\n\t\tthis.#token = token;\n\t\treturn this;\n\t}\n\n\t/**\n\t * Queues a request to be sent\n\t *\n\t * @param request - All the information needed to make a request\n\t * @returns The response from the api request\n\t */\n\tpublic async queueRequest(request: InternalRequest): Promise {\n\t\t// Generalize the endpoint to its route data\n\t\tconst routeId = RequestManager.generateRouteData(request.fullRoute, request.method);\n\t\t// Get the bucket hash for the generic route, or point to a global route otherwise\n\t\tconst hash = this.hashes.get(`${request.method}:${routeId.bucketRoute}`) ?? {\n\t\t\tvalue: `Global(${request.method}:${routeId.bucketRoute})`,\n\t\t\tlastAccess: -1,\n\t\t};\n\n\t\t// Get the request handler for the obtained hash, with its major parameter\n\t\tconst handler =\n\t\t\tthis.handlers.get(`${hash.value}:${routeId.majorParameter}`) ??\n\t\t\tthis.createHandler(hash.value, routeId.majorParameter);\n\n\t\t// Resolve the request into usable fetch options\n\t\tconst { url, fetchOptions } = await this.resolveRequest(request);\n\n\t\t// Queue the request\n\t\treturn handler.queueRequest(routeId, url, fetchOptions, {\n\t\t\tbody: request.body,\n\t\t\tfiles: request.files,\n\t\t\tauth: request.auth !== false,\n\t\t\tsignal: request.signal,\n\t\t});\n\t}\n\n\t/**\n\t * Creates a new rate limit handler from a hash, based on the hash and the major parameter\n\t *\n\t * @param hash - The hash for the route\n\t * @param majorParameter - The major parameter for this handler\n\t * @internal\n\t */\n\tprivate createHandler(hash: string, majorParameter: string) {\n\t\t// Create the async request queue to handle requests\n\t\tconst queue =\n\t\t\tmajorParameter === BurstHandlerMajorIdKey\n\t\t\t\t? new BurstHandler(this, hash, majorParameter)\n\t\t\t\t: new SequentialHandler(this, hash, majorParameter);\n\t\t// Save the queue based on its id\n\t\tthis.handlers.set(queue.id, queue);\n\n\t\treturn queue;\n\t}\n\n\t/**\n\t * Formats the request data to a usable format for fetch\n\t *\n\t * @param request - The request data\n\t */\n\tprivate async resolveRequest(request: InternalRequest): Promise<{ fetchOptions: RequestOptions; url: string }> {\n\t\tconst { options } = this;\n\n\t\tlet query = '';\n\n\t\t// If a query option is passed, use it\n\t\tif (request.query) {\n\t\t\tconst resolvedQuery = request.query.toString();\n\t\t\tif (resolvedQuery !== '') {\n\t\t\t\tquery = `?${resolvedQuery}`;\n\t\t\t}\n\t\t}\n\n\t\t// Create the required headers\n\t\tconst headers: RequestHeaders = {\n\t\t\t...this.options.headers,\n\t\t\t'User-Agent': `${DefaultUserAgent} ${options.userAgentAppendix}`.trim(),\n\t\t};\n\n\t\t// If this request requires authorization (allowing non-\"authorized\" requests for webhooks)\n\t\tif (request.auth !== false) {\n\t\t\t// If we haven't received a token, throw an error\n\t\t\tif (!this.#token) {\n\t\t\t\tthrow new Error('Expected token to be set for this request, but none was present');\n\t\t\t}\n\n\t\t\theaders.Authorization = `${request.authPrefix ?? this.options.authPrefix} ${this.#token}`;\n\t\t}\n\n\t\t// If a reason was set, set it's appropriate header\n\t\tif (request.reason?.length) {\n\t\t\theaders['X-Audit-Log-Reason'] = encodeURIComponent(request.reason);\n\t\t}\n\n\t\t// Format the full request URL (api base, optional version, endpoint, optional querystring)\n\t\tconst url = `${options.api}${request.versioned === false ? '' : `/v${options.version}`}${\n\t\t\trequest.fullRoute\n\t\t}${query}`;\n\n\t\tlet finalBody: RequestInit['body'];\n\t\tlet additionalHeaders: Record = {};\n\n\t\tif (request.files?.length) {\n\t\t\tconst formData = new FormData();\n\n\t\t\t// Attach all files to the request\n\t\t\tfor (const [index, file] of request.files.entries()) {\n\t\t\t\tconst fileKey = file.key ?? `files[${index}]`;\n\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/FormData/append#parameters\n\t\t\t\t// FormData.append only accepts a string or Blob.\n\t\t\t\t// https://developer.mozilla.org/en-US/docs/Web/API/Blob/Blob#parameters\n\t\t\t\t// The Blob constructor accepts TypedArray/ArrayBuffer, strings, and Blobs.\n\t\t\t\tif (Buffer.isBuffer(file.data)) {\n\t\t\t\t\t// Try to infer the content type from the buffer if one isn't passed\n\t\t\t\t\tconst { fileTypeFromBuffer } = await getFileType();\n\t\t\t\t\tlet contentType = file.contentType;\n\t\t\t\t\tif (!contentType) {\n\t\t\t\t\t\tconst parsedType = (await fileTypeFromBuffer(file.data))?.mime;\n\t\t\t\t\t\tif (parsedType) {\n\t\t\t\t\t\t\tcontentType = OverwrittenMimeTypes[parsedType as keyof typeof OverwrittenMimeTypes] ?? parsedType;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\n\t\t\t\t\tformData.append(fileKey, new Blob([file.data], { type: contentType }), file.name);\n\t\t\t\t} else {\n\t\t\t\t\tformData.append(fileKey, new Blob([`${file.data}`], { type: file.contentType }), file.name);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// If a JSON body was added as well, attach it to the form data, using payload_json unless otherwise specified\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t\tif (request.body != null) {\n\t\t\t\tif (request.appendToFormData) {\n\t\t\t\t\tfor (const [key, value] of Object.entries(request.body as Record)) {\n\t\t\t\t\t\tformData.append(key, value);\n\t\t\t\t\t}\n\t\t\t\t} else {\n\t\t\t\t\tformData.append('payload_json', JSON.stringify(request.body));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Set the final body to the form data\n\t\t\tfinalBody = formData;\n\n\t\t\t// eslint-disable-next-line no-eq-null, eqeqeq\n\t\t} else if (request.body != null) {\n\t\t\tif (request.passThroughBody) {\n\t\t\t\tfinalBody = request.body as BodyInit;\n\t\t\t} else {\n\t\t\t\t// Stringify the JSON data\n\t\t\t\tfinalBody = JSON.stringify(request.body);\n\t\t\t\t// Set the additional headers to specify the content-type\n\t\t\t\tadditionalHeaders = { 'Content-Type': 'application/json' };\n\t\t\t}\n\t\t}\n\n\t\tfinalBody = await resolveBody(finalBody);\n\n\t\tconst fetchOptions: RequestOptions = {\n\t\t\theaders: { ...request.headers, ...additionalHeaders, ...headers } as Record,\n\t\t\tmethod: request.method.toUpperCase() as Dispatcher.HttpMethod,\n\t\t};\n\n\t\tif (finalBody !== undefined) {\n\t\t\tfetchOptions.body = finalBody as Exclude;\n\t\t}\n\n\t\t// Prioritize setting an agent per request, use the agent for this instance otherwise.\n\t\tfetchOptions.dispatcher = request.dispatcher ?? this.agent ?? undefined!;\n\n\t\treturn { url, fetchOptions };\n\t}\n\n\t/**\n\t * Stops the hash sweeping interval\n\t */\n\tpublic clearHashSweeper() {\n\t\tclearInterval(this.hashTimer);\n\t}\n\n\t/**\n\t * Stops the request handler sweeping interval\n\t */\n\tpublic clearHandlerSweeper() {\n\t\tclearInterval(this.handlerTimer);\n\t}\n\n\t/**\n\t * Generates route data for an endpoint:method\n\t *\n\t * @param endpoint - The raw endpoint to generalize\n\t * @param method - The HTTP method this endpoint is called without\n\t * @internal\n\t */\n\tprivate static generateRouteData(endpoint: RouteLike, method: RequestMethod): RouteData {\n\t\tif (endpoint.startsWith('/interactions/') && endpoint.endsWith('/callback')) {\n\t\t\treturn {\n\t\t\t\tmajorParameter: BurstHandlerMajorIdKey,\n\t\t\t\tbucketRoute: '/interactions/:id/:token/callback',\n\t\t\t\toriginal: endpoint,\n\t\t\t};\n\t\t}\n\n\t\tconst majorIdMatch = /^\\/(?:channels|guilds|webhooks)\\/(\\d{17,19})/.exec(endpoint);\n\n\t\t// Get the major id for this route - global otherwise\n\t\tconst majorId = majorIdMatch?.[1] ?? 'global';\n\n\t\tconst baseRoute = endpoint\n\t\t\t// Strip out all ids\n\t\t\t.replaceAll(/\\d{17,19}/g, ':id')\n\t\t\t// Strip out reaction as they fall under the same bucket\n\t\t\t.replace(/\\/reactions\\/(.*)/, '/reactions/:reaction');\n\n\t\tlet exceptions = '';\n\n\t\t// Hard-Code Old Message Deletion Exception (2 week+ old messages are a different bucket)\n\t\t// https://github.com/discord/discord-api-docs/issues/1295\n\t\tif (method === RequestMethod.Delete && baseRoute === '/channels/:id/messages/:id') {\n\t\t\tconst id = /\\d{17,19}$/.exec(endpoint)![0]!;\n\t\t\tconst timestamp = DiscordSnowflake.timestampFrom(id);\n\t\t\tif (Date.now() - timestamp > 1_000 * 60 * 60 * 24 * 14) {\n\t\t\t\texceptions += '/Delete Old Message';\n\t\t\t}\n\t\t}\n\n\t\treturn {\n\t\t\tmajorParameter: majorId,\n\t\t\tbucketRoute: baseRoute + exceptions,\n\t\t\toriginal: endpoint,\n\t\t};\n\t}\n}\n","import { setTimeout as sleep } from 'node:timers/promises';\nimport type { Dispatcher } from 'undici';\nimport type { RequestOptions } from '../REST.js';\nimport type { HandlerRequestData, RequestManager, RouteData } from '../RequestManager.js';\nimport { RESTEvents } from '../utils/constants.js';\nimport { onRateLimit, parseHeader } from '../utils/utils.js';\nimport type { IHandler } from './IHandler.js';\nimport { handleErrors, incrementInvalidCount, makeNetworkRequest } from './Shared.js';\n\n/**\n * The structure used to handle burst requests for a given bucket.\n * Burst requests have no ratelimit handling but allow for pre- and post-processing\n * of data in the same manner as sequentially queued requests.\n *\n * @remarks\n * This queue may still emit a rate limit error if an unexpected 429 is hit\n */\nexport class BurstHandler implements IHandler {\n\t/**\n\t * {@inheritdoc IHandler.id}\n\t */\n\tpublic readonly id: string;\n\n\t/**\n\t * {@inheritDoc IHandler.inactive}\n\t */\n\tpublic inactive = false;\n\n\t/**\n\t * @param manager - The request manager\n\t * @param hash - The hash that this RequestHandler handles\n\t * @param majorParameter - The major parameter for this handler\n\t */\n\tpublic constructor(\n\t\tprivate readonly manager: RequestManager,\n\t\tprivate readonly hash: string,\n\t\tprivate readonly majorParameter: string,\n\t) {\n\t\tthis.id = `${hash}:${majorParameter}`;\n\t}\n\n\t/**\n\t * Emits a debug message\n\t *\n\t * @param message - The message to debug\n\t */\n\tprivate debug(message: string) {\n\t\tthis.manager.emit(RESTEvents.Debug, `[REST ${this.id}] ${message}`);\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.queueRequest}\n\t */\n\tpublic async queueRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t): Promise {\n\t\treturn this.runRequest(routeId, url, options, requestData);\n\t}\n\n\t/**\n\t * The method that actually makes the request to the API, and updates info about the bucket accordingly\n\t *\n\t * @param routeId - The generalized API route with literal ids for major parameters\n\t * @param url - The fully resolved URL to make the request to\n\t * @param options - The fetch options needed to make the request\n\t * @param requestData - Extra data from the user's request needed for errors and additional processing\n\t * @param retries - The number of retries this request has already attempted (recursion)\n\t */\n\tprivate async runRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t\tretries = 0,\n\t): Promise {\n\t\tconst method = options.method ?? 'get';\n\n\t\tconst res = await makeNetworkRequest(this.manager, routeId, url, options, requestData, retries);\n\n\t\t// Retry requested\n\t\tif (res === null) {\n\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t}\n\n\t\tconst status = res.statusCode;\n\t\tlet retryAfter = 0;\n\t\tconst retry = parseHeader(res.headers['retry-after']);\n\n\t\t// Amount of time in milliseconds until we should retry if rate limited (globally or otherwise)\n\t\tif (retry) retryAfter = Number(retry) * 1_000 + this.manager.options.offset;\n\n\t\t// Count the invalid requests\n\t\tif (status === 401 || status === 403 || status === 429) {\n\t\t\tincrementInvalidCount(this.manager);\n\t\t}\n\n\t\tif (status >= 200 && status < 300) {\n\t\t\treturn res;\n\t\t} else if (status === 429) {\n\t\t\t// Unexpected ratelimit\n\t\t\tconst isGlobal = res.headers['x-ratelimit-global'] !== undefined;\n\t\t\tawait onRateLimit(this.manager, {\n\t\t\t\ttimeToReset: retryAfter,\n\t\t\t\tlimit: Number.POSITIVE_INFINITY,\n\t\t\t\tmethod,\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t});\n\t\t\tthis.debug(\n\t\t\t\t[\n\t\t\t\t\t'Encountered unexpected 429 rate limit',\n\t\t\t\t\t` Global : ${isGlobal}`,\n\t\t\t\t\t` Method : ${method}`,\n\t\t\t\t\t` URL : ${url}`,\n\t\t\t\t\t` Bucket : ${routeId.bucketRoute}`,\n\t\t\t\t\t` Major parameter: ${routeId.majorParameter}`,\n\t\t\t\t\t` Hash : ${this.hash}`,\n\t\t\t\t\t` Limit : ${Number.POSITIVE_INFINITY}`,\n\t\t\t\t\t` Retry After : ${retryAfter}ms`,\n\t\t\t\t\t` Sublimit : None`,\n\t\t\t\t].join('\\n'),\n\t\t\t);\n\n\t\t\t// We are bypassing all other limits, but an encountered limit should be respected (it's probably a non-punished rate limit anyways)\n\t\t\tawait sleep(retryAfter);\n\n\t\t\t// Since this is not a server side issue, the next request should pass, so we don't bump the retries counter\n\t\t\treturn this.runRequest(routeId, url, options, requestData, retries);\n\t\t} else {\n\t\t\tconst handled = await handleErrors(this.manager, res, method, url, requestData, retries);\n\t\t\tif (handled === null) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t\t}\n\n\t\t\treturn handled;\n\t\t}\n\t}\n}\n","import { Blob, Buffer } from 'node:buffer';\nimport { URLSearchParams } from 'node:url';\nimport { types } from 'node:util';\nimport type { RESTPatchAPIChannelJSONBody } from 'discord-api-types/v10';\nimport { FormData, type Dispatcher, type RequestInit } from 'undici';\nimport type { RateLimitData, RequestOptions } from '../REST.js';\nimport { type RequestManager, RequestMethod } from '../RequestManager.js';\nimport { RateLimitError } from '../errors/RateLimitError.js';\n\nexport function parseHeader(header: string[] | string | undefined): string | undefined {\n\tif (header === undefined || typeof header === 'string') {\n\t\treturn header;\n\t}\n\n\treturn header.join(';');\n}\n\nfunction serializeSearchParam(value: unknown): string | null {\n\tswitch (typeof value) {\n\t\tcase 'string':\n\t\t\treturn value;\n\t\tcase 'number':\n\t\tcase 'bigint':\n\t\tcase 'boolean':\n\t\t\treturn value.toString();\n\t\tcase 'object':\n\t\t\tif (value === null) return null;\n\t\t\tif (value instanceof Date) {\n\t\t\t\treturn Number.isNaN(value.getTime()) ? null : value.toISOString();\n\t\t\t}\n\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-base-to-string\n\t\t\tif (typeof value.toString === 'function' && value.toString !== Object.prototype.toString) return value.toString();\n\t\t\treturn null;\n\t\tdefault:\n\t\t\treturn null;\n\t}\n}\n\n/**\n * Creates and populates an URLSearchParams instance from an object, stripping\n * out null and undefined values, while also coercing non-strings to strings.\n *\n * @param options - The options to use\n * @returns A populated URLSearchParams instance\n */\nexport function makeURLSearchParams(options?: Readonly) {\n\tconst params = new URLSearchParams();\n\tif (!options) return params;\n\n\tfor (const [key, value] of Object.entries(options)) {\n\t\tconst serialized = serializeSearchParam(value);\n\t\tif (serialized !== null) params.append(key, serialized);\n\t}\n\n\treturn params;\n}\n\n/**\n * Converts the response to usable data\n *\n * @param res - The fetch response\n */\nexport async function parseResponse(res: Dispatcher.ResponseData): Promise {\n\tconst header = parseHeader(res.headers['content-type']);\n\tif (header?.startsWith('application/json')) {\n\t\treturn res.body.json();\n\t}\n\n\treturn res.body.arrayBuffer();\n}\n\n/**\n * Check whether a request falls under a sublimit\n *\n * @param bucketRoute - The buckets route identifier\n * @param body - The options provided as JSON data\n * @param method - The HTTP method that will be used to make the request\n * @returns Whether the request falls under a sublimit\n */\nexport function hasSublimit(bucketRoute: string, body?: unknown, method?: string): boolean {\n\t// TODO: Update for new sublimits\n\t// Currently known sublimits:\n\t// Editing channel `name` or `topic`\n\tif (bucketRoute === '/channels/:id') {\n\t\tif (typeof body !== 'object' || body === null) return false;\n\t\t// This should never be a POST body, but just in case\n\t\tif (method !== RequestMethod.Patch) return false;\n\t\tconst castedBody = body as RESTPatchAPIChannelJSONBody;\n\t\treturn ['name', 'topic'].some((key) => Reflect.has(castedBody, key));\n\t}\n\n\t// If we are checking if a request has a sublimit on a route not checked above, sublimit all requests to avoid a flood of 429s\n\treturn true;\n}\n\nexport async function resolveBody(body: RequestInit['body']): Promise {\n\t// eslint-disable-next-line no-eq-null, eqeqeq\n\tif (body == null) {\n\t\treturn null;\n\t} else if (typeof body === 'string') {\n\t\treturn body;\n\t} else if (types.isUint8Array(body)) {\n\t\treturn body;\n\t} else if (types.isArrayBuffer(body)) {\n\t\treturn new Uint8Array(body);\n\t} else if (body instanceof URLSearchParams) {\n\t\treturn body.toString();\n\t} else if (body instanceof DataView) {\n\t\treturn new Uint8Array(body.buffer);\n\t} else if (body instanceof Blob) {\n\t\treturn new Uint8Array(await body.arrayBuffer());\n\t} else if (body instanceof FormData) {\n\t\treturn body;\n\t} else if ((body as Iterable)[Symbol.iterator]) {\n\t\tconst chunks = [...(body as Iterable)];\n\t\tconst length = chunks.reduce((a, b) => a + b.length, 0);\n\n\t\tconst uint8 = new Uint8Array(length);\n\t\tlet lengthUsed = 0;\n\n\t\treturn chunks.reduce((a, b) => {\n\t\t\ta.set(b, lengthUsed);\n\t\t\tlengthUsed += b.length;\n\t\t\treturn a;\n\t\t}, uint8);\n\t} else if ((body as AsyncIterable)[Symbol.asyncIterator]) {\n\t\tconst chunks: Uint8Array[] = [];\n\n\t\tfor await (const chunk of body as AsyncIterable) {\n\t\t\tchunks.push(chunk);\n\t\t}\n\n\t\treturn Buffer.concat(chunks);\n\t}\n\n\tthrow new TypeError(`Unable to resolve body.`);\n}\n\n/**\n * Check whether an error indicates that a retry can be attempted\n *\n * @param error - The error thrown by the network request\n * @returns Whether the error indicates a retry should be attempted\n */\nexport function shouldRetry(error: Error | NodeJS.ErrnoException) {\n\t// Retry for possible timed out requests\n\tif (error.name === 'AbortError') return true;\n\t// Downlevel ECONNRESET to retry as it may be recoverable\n\treturn ('code' in error && error.code === 'ECONNRESET') || error.message.includes('ECONNRESET');\n}\n\n/**\n * Determines whether the request should be queued or whether a RateLimitError should be thrown\n *\n * @internal\n */\nexport async function onRateLimit(manager: RequestManager, rateLimitData: RateLimitData) {\n\tconst { options } = manager;\n\tif (!options.rejectOnRateLimit) return;\n\n\tconst shouldThrow =\n\t\ttypeof options.rejectOnRateLimit === 'function'\n\t\t\t? await options.rejectOnRateLimit(rateLimitData)\n\t\t\t: options.rejectOnRateLimit.some((route) => rateLimitData.route.startsWith(route.toLowerCase()));\n\tif (shouldThrow) {\n\t\tthrow new RateLimitError(rateLimitData);\n\t}\n}\n","import { setTimeout, clearTimeout } from 'node:timers';\nimport { request, type Dispatcher } from 'undici';\nimport type { RequestOptions } from '../REST.js';\nimport type { HandlerRequestData, RequestManager, RouteData } from '../RequestManager.js';\nimport type { DiscordErrorData, OAuthErrorData } from '../errors/DiscordAPIError.js';\nimport { DiscordAPIError } from '../errors/DiscordAPIError.js';\nimport { HTTPError } from '../errors/HTTPError.js';\nimport { RESTEvents } from '../utils/constants.js';\nimport { parseResponse, shouldRetry } from '../utils/utils.js';\nimport type { PolyFillAbortSignal } from './IHandler.js';\n\n/**\n * Invalid request limiting is done on a per-IP basis, not a per-token basis.\n * The best we can do is track invalid counts process-wide (on the theory that\n * users could have multiple bots run from one process) rather than per-bot.\n * Therefore, store these at file scope here rather than in the client's\n * RESTManager object.\n */\nlet invalidCount = 0;\nlet invalidCountResetTime: number | null = null;\n\n/**\n * Increment the invalid request count and emit warning if necessary\n *\n * @internal\n */\nexport function incrementInvalidCount(manager: RequestManager) {\n\tif (!invalidCountResetTime || invalidCountResetTime < Date.now()) {\n\t\tinvalidCountResetTime = Date.now() + 1_000 * 60 * 10;\n\t\tinvalidCount = 0;\n\t}\n\n\tinvalidCount++;\n\n\tconst emitInvalid =\n\t\tmanager.options.invalidRequestWarningInterval > 0 &&\n\t\tinvalidCount % manager.options.invalidRequestWarningInterval === 0;\n\tif (emitInvalid) {\n\t\t// Let library users know periodically about invalid requests\n\t\tmanager.emit(RESTEvents.InvalidRequestWarning, {\n\t\t\tcount: invalidCount,\n\t\t\tremainingTime: invalidCountResetTime - Date.now(),\n\t\t});\n\t}\n}\n\n/**\n * Performs the actual network request for a request handler\n *\n * @param manager - The manager that holds options and emits informational events\n * @param routeId - The generalized api route with literal ids for major parameters\n * @param url - The fully resolved url to make the request to\n * @param options - The fetch options needed to make the request\n * @param requestData - Extra data from the user's request needed for errors and additional processing\n * @param retries - The number of retries this request has already attempted (recursion occurs on the handler)\n * @returns The respond from the network or `null` when the request should be retried\n * @internal\n */\nexport async function makeNetworkRequest(\n\tmanager: RequestManager,\n\trouteId: RouteData,\n\turl: string,\n\toptions: RequestOptions,\n\trequestData: HandlerRequestData,\n\tretries: number,\n) {\n\tconst controller = new AbortController();\n\tconst timeout = setTimeout(() => controller.abort(), manager.options.timeout).unref();\n\tif (requestData.signal) {\n\t\t// The type polyfill is required because Node.js's types are incomplete.\n\t\tconst signal = requestData.signal as unknown as PolyFillAbortSignal;\n\t\t// If the user signal was aborted, abort the controller, else abort the local signal.\n\t\t// The reason why we don't re-use the user's signal, is because users may use the same signal for multiple\n\t\t// requests, and we do not want to cause unexpected side-effects.\n\t\tif (signal.aborted) controller.abort();\n\t\telse signal.addEventListener('abort', () => controller.abort());\n\t}\n\n\tlet res: Dispatcher.ResponseData;\n\ttry {\n\t\tres = await request(url, { ...options, signal: controller.signal });\n\t} catch (error: unknown) {\n\t\tif (!(error instanceof Error)) throw error;\n\t\t// Retry the specified number of times if needed\n\t\tif (shouldRetry(error) && retries !== manager.options.retries) {\n\t\t\t// Retry is handled by the handler upon receiving null\n\t\t\treturn null;\n\t\t}\n\n\t\tthrow error;\n\t} finally {\n\t\tclearTimeout(timeout);\n\t}\n\n\tif (manager.listenerCount(RESTEvents.Response)) {\n\t\tmanager.emit(\n\t\t\tRESTEvents.Response,\n\t\t\t{\n\t\t\t\tmethod: options.method ?? 'get',\n\t\t\t\tpath: routeId.original,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\toptions,\n\t\t\t\tdata: requestData,\n\t\t\t\tretries,\n\t\t\t},\n\t\t\t{ ...res },\n\t\t);\n\t}\n\n\treturn res;\n}\n\n/**\n * Handles 5xx and 4xx errors (not 429's) conventionally. 429's should be handled before calling this function\n *\n * @param manager - The manager that holds options and emits informational events\n * @param res - The response received from {@link makeNetworkRequest}\n * @param method - The method used to make the request\n * @param url - The fully resolved url to make the request to\n * @param requestData - Extra data from the user's request needed for errors and additional processing\n * @param retries - The number of retries this request has already attempted (recursion occurs on the handler)\n * @returns - The response if the status code is not handled or null to request a retry\n */\nexport async function handleErrors(\n\tmanager: RequestManager,\n\tres: Dispatcher.ResponseData,\n\tmethod: string,\n\turl: string,\n\trequestData: HandlerRequestData,\n\tretries: number,\n) {\n\tconst status = res.statusCode;\n\tif (status >= 500 && status < 600) {\n\t\t// Retry the specified number of times for possible server side issues\n\t\tif (retries !== manager.options.retries) {\n\t\t\treturn null;\n\t\t}\n\n\t\t// We are out of retries, throw an error\n\t\tthrow new HTTPError(status, method, url, requestData);\n\t} else {\n\t\t// Handle possible malformed requests\n\t\tif (status >= 400 && status < 500) {\n\t\t\t// If we receive this status code, it means the token we had is no longer valid.\n\t\t\tif (status === 401 && requestData.auth) {\n\t\t\t\tmanager.setToken(null!);\n\t\t\t}\n\n\t\t\t// The request will not succeed for some reason, parse the error returned from the api\n\t\t\tconst data = (await parseResponse(res)) as DiscordErrorData | OAuthErrorData;\n\t\t\t// throw the API error\n\t\t\tthrow new DiscordAPIError(data, 'code' in data ? data.code : data.error, status, method, url, requestData);\n\t\t}\n\n\t\treturn res;\n\t}\n}\n","import { setTimeout as sleep } from 'node:timers/promises';\nimport { AsyncQueue } from '@sapphire/async-queue';\nimport type { Dispatcher } from 'undici';\nimport type { RateLimitData, RequestOptions } from '../REST.js';\nimport type { HandlerRequestData, RequestManager, RouteData } from '../RequestManager.js';\nimport { RESTEvents } from '../utils/constants.js';\nimport { hasSublimit, onRateLimit, parseHeader } from '../utils/utils.js';\nimport type { IHandler } from './IHandler.js';\nimport { handleErrors, incrementInvalidCount, makeNetworkRequest } from './Shared.js';\n\nconst enum QueueType {\n\tStandard,\n\tSublimit,\n}\n\n/**\n * The structure used to handle sequential requests for a given bucket\n */\nexport class SequentialHandler implements IHandler {\n\t/**\n\t * {@inheritDoc IHandler.id}\n\t */\n\tpublic readonly id: string;\n\n\t/**\n\t * The time this rate limit bucket will reset\n\t */\n\tprivate reset = -1;\n\n\t/**\n\t * The remaining requests that can be made before we are rate limited\n\t */\n\tprivate remaining = 1;\n\n\t/**\n\t * The total number of requests that can be made before we are rate limited\n\t */\n\tprivate limit = Number.POSITIVE_INFINITY;\n\n\t/**\n\t * The interface used to sequence async requests sequentially\n\t */\n\t#asyncQueue = new AsyncQueue();\n\n\t/**\n\t * The interface used to sequence sublimited async requests sequentially\n\t */\n\t#sublimitedQueue: AsyncQueue | null = null;\n\n\t/**\n\t * A promise wrapper for when the sublimited queue is finished being processed or null when not being processed\n\t */\n\t#sublimitPromise: { promise: Promise; resolve(): void } | null = null;\n\n\t/**\n\t * Whether the sublimit queue needs to be shifted in the finally block\n\t */\n\t#shiftSublimit = false;\n\n\t/**\n\t * @param manager - The request manager\n\t * @param hash - The hash that this RequestHandler handles\n\t * @param majorParameter - The major parameter for this handler\n\t */\n\tpublic constructor(\n\t\tprivate readonly manager: RequestManager,\n\t\tprivate readonly hash: string,\n\t\tprivate readonly majorParameter: string,\n\t) {\n\t\tthis.id = `${hash}:${majorParameter}`;\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.inactive}\n\t */\n\tpublic get inactive(): boolean {\n\t\treturn (\n\t\t\tthis.#asyncQueue.remaining === 0 &&\n\t\t\t(this.#sublimitedQueue === null || this.#sublimitedQueue.remaining === 0) &&\n\t\t\t!this.limited\n\t\t);\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited by the global limit\n\t */\n\tprivate get globalLimited(): boolean {\n\t\treturn this.manager.globalRemaining <= 0 && Date.now() < this.manager.globalReset;\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited by its limit\n\t */\n\tprivate get localLimited(): boolean {\n\t\treturn this.remaining <= 0 && Date.now() < this.reset;\n\t}\n\n\t/**\n\t * If the rate limit bucket is currently limited\n\t */\n\tprivate get limited(): boolean {\n\t\treturn this.globalLimited || this.localLimited;\n\t}\n\n\t/**\n\t * The time until queued requests can continue\n\t */\n\tprivate get timeToReset(): number {\n\t\treturn this.reset + this.manager.options.offset - Date.now();\n\t}\n\n\t/**\n\t * Emits a debug message\n\t *\n\t * @param message - The message to debug\n\t */\n\tprivate debug(message: string) {\n\t\tthis.manager.emit(RESTEvents.Debug, `[REST ${this.id}] ${message}`);\n\t}\n\n\t/**\n\t * Delay all requests for the specified amount of time, handling global rate limits\n\t *\n\t * @param time - The amount of time to delay all requests for\n\t */\n\tprivate async globalDelayFor(time: number): Promise {\n\t\tawait sleep(time);\n\t\tthis.manager.globalDelay = null;\n\t}\n\n\t/**\n\t * {@inheritDoc IHandler.queueRequest}\n\t */\n\tpublic async queueRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t): Promise {\n\t\tlet queue = this.#asyncQueue;\n\t\tlet queueType = QueueType.Standard;\n\t\t// Separate sublimited requests when already sublimited\n\t\tif (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) {\n\t\t\tqueue = this.#sublimitedQueue!;\n\t\t\tqueueType = QueueType.Sublimit;\n\t\t}\n\n\t\t// Wait for any previous requests to be completed before this one is run\n\t\tawait queue.wait({ signal: requestData.signal });\n\t\t// This set handles retroactively sublimiting requests\n\t\tif (queueType === QueueType.Standard) {\n\t\t\tif (this.#sublimitedQueue && hasSublimit(routeId.bucketRoute, requestData.body, options.method)) {\n\t\t\t\t/**\n\t\t\t\t * Remove the request from the standard queue, it should never be possible to get here while processing the\n\t\t\t\t * sublimit queue so there is no need to worry about shifting the wrong request\n\t\t\t\t */\n\t\t\t\tqueue = this.#sublimitedQueue!;\n\t\t\t\tconst wait = queue.wait();\n\t\t\t\tthis.#asyncQueue.shift();\n\t\t\t\tawait wait;\n\t\t\t} else if (this.#sublimitPromise) {\n\t\t\t\t// Stall requests while the sublimit queue gets processed\n\t\t\t\tawait this.#sublimitPromise.promise;\n\t\t\t}\n\t\t}\n\n\t\ttry {\n\t\t\t// Make the request, and return the results\n\t\t\treturn await this.runRequest(routeId, url, options, requestData);\n\t\t} finally {\n\t\t\t// Allow the next request to fire\n\t\t\tqueue.shift();\n\t\t\tif (this.#shiftSublimit) {\n\t\t\t\tthis.#shiftSublimit = false;\n\t\t\t\tthis.#sublimitedQueue?.shift();\n\t\t\t}\n\n\t\t\t// If this request is the last request in a sublimit\n\t\t\tif (this.#sublimitedQueue?.remaining === 0) {\n\t\t\t\tthis.#sublimitPromise?.resolve();\n\t\t\t\tthis.#sublimitedQueue = null;\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * The method that actually makes the request to the api, and updates info about the bucket accordingly\n\t *\n\t * @param routeId - The generalized api route with literal ids for major parameters\n\t * @param url - The fully resolved url to make the request to\n\t * @param options - The fetch options needed to make the request\n\t * @param requestData - Extra data from the user's request needed for errors and additional processing\n\t * @param retries - The number of retries this request has already attempted (recursion)\n\t */\n\tprivate async runRequest(\n\t\trouteId: RouteData,\n\t\turl: string,\n\t\toptions: RequestOptions,\n\t\trequestData: HandlerRequestData,\n\t\tretries = 0,\n\t): Promise {\n\t\t/*\n\t\t * After calculations have been done, pre-emptively stop further requests\n\t\t * Potentially loop until this task can run if e.g. the global rate limit is hit twice\n\t\t */\n\t\twhile (this.limited) {\n\t\t\tconst isGlobal = this.globalLimited;\n\t\t\tlet limit: number;\n\t\t\tlet timeout: number;\n\t\t\tlet delay: Promise;\n\n\t\t\tif (isGlobal) {\n\t\t\t\t// Set RateLimitData based on the global limit\n\t\t\t\tlimit = this.manager.options.globalRequestsPerSecond;\n\t\t\t\ttimeout = this.manager.globalReset + this.manager.options.offset - Date.now();\n\t\t\t\t// If this is the first task to reach the global timeout, set the global delay\n\t\t\t\tif (!this.manager.globalDelay) {\n\t\t\t\t\t// The global delay function clears the global delay state when it is resolved\n\t\t\t\t\tthis.manager.globalDelay = this.globalDelayFor(timeout);\n\t\t\t\t}\n\n\t\t\t\tdelay = this.manager.globalDelay;\n\t\t\t} else {\n\t\t\t\t// Set RateLimitData based on the route-specific limit\n\t\t\t\tlimit = this.limit;\n\t\t\t\ttimeout = this.timeToReset;\n\t\t\t\tdelay = sleep(timeout);\n\t\t\t}\n\n\t\t\tconst rateLimitData: RateLimitData = {\n\t\t\t\ttimeToReset: timeout,\n\t\t\t\tlimit,\n\t\t\t\tmethod: options.method ?? 'get',\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t};\n\t\t\t// Let library users know they have hit a rate limit\n\t\t\tthis.manager.emit(RESTEvents.RateLimited, rateLimitData);\n\t\t\t// Determine whether a RateLimitError should be thrown\n\t\t\tawait onRateLimit(this.manager, rateLimitData);\n\t\t\t// When not erroring, emit debug for what is happening\n\t\t\tif (isGlobal) {\n\t\t\t\tthis.debug(`Global rate limit hit, blocking all requests for ${timeout}ms`);\n\t\t\t} else {\n\t\t\t\tthis.debug(`Waiting ${timeout}ms for rate limit to pass`);\n\t\t\t}\n\n\t\t\t// Wait the remaining time left before the rate limit resets\n\t\t\tawait delay;\n\t\t}\n\n\t\t// As the request goes out, update the global usage information\n\t\tif (!this.manager.globalReset || this.manager.globalReset < Date.now()) {\n\t\t\tthis.manager.globalReset = Date.now() + 1_000;\n\t\t\tthis.manager.globalRemaining = this.manager.options.globalRequestsPerSecond;\n\t\t}\n\n\t\tthis.manager.globalRemaining--;\n\n\t\tconst method = options.method ?? 'get';\n\n\t\tconst res = await makeNetworkRequest(this.manager, routeId, url, options, requestData, retries);\n\n\t\t// Retry requested\n\t\tif (res === null) {\n\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t}\n\n\t\tconst status = res.statusCode;\n\t\tlet retryAfter = 0;\n\n\t\tconst limit = parseHeader(res.headers['x-ratelimit-limit']);\n\t\tconst remaining = parseHeader(res.headers['x-ratelimit-remaining']);\n\t\tconst reset = parseHeader(res.headers['x-ratelimit-reset-after']);\n\t\tconst hash = parseHeader(res.headers['x-ratelimit-bucket']);\n\t\tconst retry = parseHeader(res.headers['retry-after']);\n\n\t\t// Update the total number of requests that can be made before the rate limit resets\n\t\tthis.limit = limit ? Number(limit) : Number.POSITIVE_INFINITY;\n\t\t// Update the number of remaining requests that can be made before the rate limit resets\n\t\tthis.remaining = remaining ? Number(remaining) : 1;\n\t\t// Update the time when this rate limit resets (reset-after is in seconds)\n\t\tthis.reset = reset ? Number(reset) * 1_000 + Date.now() + this.manager.options.offset : Date.now();\n\n\t\t// Amount of time in milliseconds until we should retry if rate limited (globally or otherwise)\n\t\tif (retry) retryAfter = Number(retry) * 1_000 + this.manager.options.offset;\n\n\t\t// Handle buckets via the hash header retroactively\n\t\tif (hash && hash !== this.hash) {\n\t\t\t// Let library users know when rate limit buckets have been updated\n\t\t\tthis.debug(['Received bucket hash update', ` Old Hash : ${this.hash}`, ` New Hash : ${hash}`].join('\\n'));\n\t\t\t// This queue will eventually be eliminated via attrition\n\t\t\tthis.manager.hashes.set(`${method}:${routeId.bucketRoute}`, { value: hash, lastAccess: Date.now() });\n\t\t} else if (hash) {\n\t\t\t// Handle the case where hash value doesn't change\n\t\t\t// Fetch the hash data from the manager\n\t\t\tconst hashData = this.manager.hashes.get(`${method}:${routeId.bucketRoute}`);\n\n\t\t\t// When fetched, update the last access of the hash\n\t\t\tif (hashData) {\n\t\t\t\thashData.lastAccess = Date.now();\n\t\t\t}\n\t\t}\n\n\t\t// Handle retryAfter, which means we have actually hit a rate limit\n\t\tlet sublimitTimeout: number | null = null;\n\t\tif (retryAfter > 0) {\n\t\t\tif (res.headers['x-ratelimit-global'] !== undefined) {\n\t\t\t\tthis.manager.globalRemaining = 0;\n\t\t\t\tthis.manager.globalReset = Date.now() + retryAfter;\n\t\t\t} else if (!this.localLimited) {\n\t\t\t\t/*\n\t\t\t\t * This is a sublimit (e.g. 2 channel name changes/10 minutes) since the headers don't indicate a\n\t\t\t\t * route-wide rate limit. Don't update remaining or reset to avoid rate limiting the whole\n\t\t\t\t * endpoint, just set a reset time on the request itself to avoid retrying too soon.\n\t\t\t\t */\n\t\t\t\tsublimitTimeout = retryAfter;\n\t\t\t}\n\t\t}\n\n\t\t// Count the invalid requests\n\t\tif (status === 401 || status === 403 || status === 429) {\n\t\t\tincrementInvalidCount(this.manager);\n\t\t}\n\n\t\tif (status >= 200 && status < 300) {\n\t\t\treturn res;\n\t\t} else if (status === 429) {\n\t\t\t// A rate limit was hit - this may happen if the route isn't associated with an official bucket hash yet, or when first globally rate limited\n\t\t\tconst isGlobal = this.globalLimited;\n\t\t\tlet limit: number;\n\t\t\tlet timeout: number;\n\n\t\t\tif (isGlobal) {\n\t\t\t\t// Set RateLimitData based on the global limit\n\t\t\t\tlimit = this.manager.options.globalRequestsPerSecond;\n\t\t\t\ttimeout = this.manager.globalReset + this.manager.options.offset - Date.now();\n\t\t\t} else {\n\t\t\t\t// Set RateLimitData based on the route-specific limit\n\t\t\t\tlimit = this.limit;\n\t\t\t\ttimeout = this.timeToReset;\n\t\t\t}\n\n\t\t\tawait onRateLimit(this.manager, {\n\t\t\t\ttimeToReset: timeout,\n\t\t\t\tlimit,\n\t\t\t\tmethod,\n\t\t\t\thash: this.hash,\n\t\t\t\turl,\n\t\t\t\troute: routeId.bucketRoute,\n\t\t\t\tmajorParameter: this.majorParameter,\n\t\t\t\tglobal: isGlobal,\n\t\t\t});\n\t\t\tthis.debug(\n\t\t\t\t[\n\t\t\t\t\t'Encountered unexpected 429 rate limit',\n\t\t\t\t\t` Global : ${isGlobal.toString()}`,\n\t\t\t\t\t` Method : ${method}`,\n\t\t\t\t\t` URL : ${url}`,\n\t\t\t\t\t` Bucket : ${routeId.bucketRoute}`,\n\t\t\t\t\t` Major parameter: ${routeId.majorParameter}`,\n\t\t\t\t\t` Hash : ${this.hash}`,\n\t\t\t\t\t` Limit : ${limit}`,\n\t\t\t\t\t` Retry After : ${retryAfter}ms`,\n\t\t\t\t\t` Sublimit : ${sublimitTimeout ? `${sublimitTimeout}ms` : 'None'}`,\n\t\t\t\t].join('\\n'),\n\t\t\t);\n\t\t\t// If caused by a sublimit, wait it out here so other requests on the route can be handled\n\t\t\tif (sublimitTimeout) {\n\t\t\t\t// Normally the sublimit queue will not exist, however, if a sublimit is hit while in the sublimit queue, it will\n\t\t\t\tconst firstSublimit = !this.#sublimitedQueue;\n\t\t\t\tif (firstSublimit) {\n\t\t\t\t\tthis.#sublimitedQueue = new AsyncQueue();\n\t\t\t\t\tvoid this.#sublimitedQueue.wait();\n\t\t\t\t\tthis.#asyncQueue.shift();\n\t\t\t\t}\n\n\t\t\t\tthis.#sublimitPromise?.resolve();\n\t\t\t\tthis.#sublimitPromise = null;\n\t\t\t\tawait sleep(sublimitTimeout);\n\t\t\t\tlet resolve: () => void;\n\t\t\t\t// eslint-disable-next-line promise/param-names, no-promise-executor-return\n\t\t\t\tconst promise = new Promise((res) => (resolve = res));\n\t\t\t\tthis.#sublimitPromise = { promise, resolve: resolve! };\n\t\t\t\tif (firstSublimit) {\n\t\t\t\t\t// Re-queue this request so it can be shifted by the finally\n\t\t\t\t\tawait this.#asyncQueue.wait();\n\t\t\t\t\tthis.#shiftSublimit = true;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\t// Since this is not a server side issue, the next request should pass, so we don't bump the retries counter\n\t\t\treturn this.runRequest(routeId, url, options, requestData, retries);\n\t\t} else {\n\t\t\tconst handled = await handleErrors(this.manager, res, method, url, requestData, retries);\n\t\t\tif (handled === null) {\n\t\t\t\t// eslint-disable-next-line no-param-reassign\n\t\t\t\treturn this.runRequest(routeId, url, options, requestData, ++retries);\n\t\t\t}\n\n\t\t\treturn handled;\n\t\t}\n\t}\n}\n","import { EventEmitter } from 'node:events';\nimport type { Collection } from '@discordjs/collection';\nimport type { request, Dispatcher } from 'undici';\nimport { CDN } from './CDN.js';\nimport {\n\tRequestManager,\n\tRequestMethod,\n\ttype HashData,\n\ttype HandlerRequestData,\n\ttype InternalRequest,\n\ttype RequestData,\n\ttype RouteLike,\n} from './RequestManager.js';\nimport type { IHandler } from './handlers/IHandler.js';\nimport { DefaultRestOptions, RESTEvents } from './utils/constants.js';\nimport { parseResponse } from './utils/utils.js';\n\n/**\n * Options to be passed when creating the REST instance\n */\nexport interface RESTOptions {\n\t/**\n\t * The agent to set globally\n\t */\n\tagent: Dispatcher;\n\t/**\n\t * The base api path, without version\n\t *\n\t * @defaultValue `'https://discord.com/api'`\n\t */\n\tapi: string;\n\t/**\n\t * The authorization prefix to use for requests, useful if you want to use\n\t * bearer tokens\n\t *\n\t * @defaultValue `'Bot'`\n\t */\n\tauthPrefix: 'Bearer' | 'Bot';\n\t/**\n\t * The cdn path\n\t *\n\t * @defaultValue 'https://cdn.discordapp.com'\n\t */\n\tcdn: string;\n\t/**\n\t * How many requests to allow sending per second (Infinity for unlimited, 50 for the standard global limit used by Discord)\n\t *\n\t * @defaultValue `50`\n\t */\n\tglobalRequestsPerSecond: number;\n\t/**\n\t * The amount of time in milliseconds that passes between each hash sweep. (defaults to 1h)\n\t *\n\t * @defaultValue `3_600_000`\n\t */\n\thandlerSweepInterval: number;\n\t/**\n\t * The maximum amount of time a hash can exist in milliseconds without being hit with a request (defaults to 24h)\n\t *\n\t * @defaultValue `86_400_000`\n\t */\n\thashLifetime: number;\n\t/**\n\t * The amount of time in milliseconds that passes between each hash sweep. (defaults to 4h)\n\t *\n\t * @defaultValue `14_400_000`\n\t */\n\thashSweepInterval: number;\n\t/**\n\t * Additional headers to send for all API requests\n\t *\n\t * @defaultValue `{}`\n\t */\n\theaders: Record;\n\t/**\n\t * The number of invalid REST requests (those that return 401, 403, or 429) in a 10 minute window between emitted warnings (0 for no warnings).\n\t * That is, if set to 500, warnings will be emitted at invalid request number 500, 1000, 1500, and so on.\n\t *\n\t * @defaultValue `0`\n\t */\n\tinvalidRequestWarningInterval: number;\n\t/**\n\t * The extra offset to add to rate limits in milliseconds\n\t *\n\t * @defaultValue `50`\n\t */\n\toffset: number;\n\t/**\n\t * Determines how rate limiting and pre-emptive throttling should be handled.\n\t * When an array of strings, each element is treated as a prefix for the request route\n\t * (e.g. `/channels` to match any route starting with `/channels` such as `/channels/:id/messages`)\n\t * for which to throw {@link RateLimitError}s. All other request routes will be queued normally\n\t *\n\t * @defaultValue `null`\n\t */\n\trejectOnRateLimit: RateLimitQueueFilter | string[] | null;\n\t/**\n\t * The number of retries for errors with the 500 code, or errors\n\t * that timeout\n\t *\n\t * @defaultValue `3`\n\t */\n\tretries: number;\n\t/**\n\t * The time to wait in milliseconds before a request is aborted\n\t *\n\t * @defaultValue `15_000`\n\t */\n\ttimeout: number;\n\t/**\n\t * Extra information to add to the user agent\n\t *\n\t * @defaultValue DefaultUserAgentAppendix\n\t */\n\tuserAgentAppendix: string;\n\t/**\n\t * The version of the API to use\n\t *\n\t * @defaultValue `'10'`\n\t */\n\tversion: string;\n}\n\n/**\n * Data emitted on `RESTEvents.RateLimited`\n */\nexport interface RateLimitData {\n\t/**\n\t * Whether the rate limit that was reached was the global limit\n\t */\n\tglobal: boolean;\n\t/**\n\t * The bucket hash for this request\n\t */\n\thash: string;\n\t/**\n\t * The amount of requests we can perform before locking requests\n\t */\n\tlimit: number;\n\t/**\n\t * The major parameter of the route\n\t *\n\t * For example, in `/channels/x`, this will be `x`.\n\t * If there is no major parameter (e.g: `/bot/gateway`) this will be `global`.\n\t */\n\tmajorParameter: string;\n\t/**\n\t * The HTTP method being performed\n\t */\n\tmethod: string;\n\t/**\n\t * The route being hit in this request\n\t */\n\troute: string;\n\t/**\n\t * The time, in milliseconds, until the request-lock is reset\n\t */\n\ttimeToReset: number;\n\t/**\n\t * The full URL for this request\n\t */\n\turl: string;\n}\n\n/**\n * A function that determines whether the rate limit hit should throw an Error\n */\nexport type RateLimitQueueFilter = (rateLimitData: RateLimitData) => Promise | boolean;\n\nexport interface APIRequest {\n\t/**\n\t * The data that was used to form the body of this request\n\t */\n\tdata: HandlerRequestData;\n\t/**\n\t * The HTTP method used in this request\n\t */\n\tmethod: string;\n\t/**\n\t * Additional HTTP options for this request\n\t */\n\toptions: RequestOptions;\n\t/**\n\t * The full path used to make the request\n\t */\n\tpath: RouteLike;\n\t/**\n\t * The number of times this request has been attempted\n\t */\n\tretries: number;\n\t/**\n\t * The API route identifying the ratelimit for this request\n\t */\n\troute: string;\n}\n\nexport interface InvalidRequestWarningData {\n\t/**\n\t * Number of invalid requests that have been made in the window\n\t */\n\tcount: number;\n\t/**\n\t * Time in milliseconds remaining before the count resets\n\t */\n\tremainingTime: number;\n}\n\nexport interface RestEvents {\n\thandlerSweep: [sweptHandlers: Collection];\n\thashSweep: [sweptHashes: Collection];\n\tinvalidRequestWarning: [invalidRequestInfo: InvalidRequestWarningData];\n\tnewListener: [name: string, listener: (...args: any) => void];\n\trateLimited: [rateLimitInfo: RateLimitData];\n\tremoveListener: [name: string, listener: (...args: any) => void];\n\tresponse: [request: APIRequest, response: Dispatcher.ResponseData];\n\trestDebug: [info: string];\n}\n\nexport interface REST {\n\temit: ((event: K, ...args: RestEvents[K]) => boolean) &\n\t\t((event: Exclude, ...args: any[]) => boolean);\n\n\toff: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\ton: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tonce: ((event: K, listener: (...args: RestEvents[K]) => void) => this) &\n\t\t((event: Exclude, listener: (...args: any[]) => void) => this);\n\n\tremoveAllListeners: ((event?: K) => this) &\n\t\t((event?: Exclude) => this);\n}\n\nexport type RequestOptions = Exclude[1], undefined>;\n\nexport class REST extends EventEmitter {\n\tpublic readonly cdn: CDN;\n\n\tpublic readonly requestManager: RequestManager;\n\n\tpublic constructor(options: Partial = {}) {\n\t\tsuper();\n\t\tthis.cdn = new CDN(options.cdn ?? DefaultRestOptions.cdn);\n\t\tthis.requestManager = new RequestManager(options)\n\t\t\t.on(RESTEvents.Debug, this.emit.bind(this, RESTEvents.Debug))\n\t\t\t.on(RESTEvents.RateLimited, this.emit.bind(this, RESTEvents.RateLimited))\n\t\t\t.on(RESTEvents.InvalidRequestWarning, this.emit.bind(this, RESTEvents.InvalidRequestWarning))\n\t\t\t.on(RESTEvents.HashSweep, this.emit.bind(this, RESTEvents.HashSweep));\n\n\t\tthis.on('newListener', (name, listener) => {\n\t\t\tif (name === RESTEvents.Response) this.requestManager.on(name, listener);\n\t\t});\n\t\tthis.on('removeListener', (name, listener) => {\n\t\t\tif (name === RESTEvents.Response) this.requestManager.off(name, listener);\n\t\t});\n\t}\n\n\t/**\n\t * Gets the agent set for this instance\n\t */\n\tpublic getAgent() {\n\t\treturn this.requestManager.agent;\n\t}\n\n\t/**\n\t * Sets the default agent to use for requests performed by this instance\n\t *\n\t * @param agent - Sets the agent to use\n\t */\n\tpublic setAgent(agent: Dispatcher) {\n\t\tthis.requestManager.setAgent(agent);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Sets the authorization token that should be used for requests\n\t *\n\t * @param token - The authorization token to use\n\t */\n\tpublic setToken(token: string) {\n\t\tthis.requestManager.setToken(token);\n\t\treturn this;\n\t}\n\n\t/**\n\t * Runs a get request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async get(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Get });\n\t}\n\n\t/**\n\t * Runs a delete request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async delete(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Delete });\n\t}\n\n\t/**\n\t * Runs a post request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async post(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Post });\n\t}\n\n\t/**\n\t * Runs a put request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async put(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Put });\n\t}\n\n\t/**\n\t * Runs a patch request from the api\n\t *\n\t * @param fullRoute - The full route to query\n\t * @param options - Optional request options\n\t */\n\tpublic async patch(fullRoute: RouteLike, options: RequestData = {}) {\n\t\treturn this.request({ ...options, fullRoute, method: RequestMethod.Patch });\n\t}\n\n\t/**\n\t * Runs a request from the api\n\t *\n\t * @param options - Request options\n\t */\n\tpublic async request(options: InternalRequest) {\n\t\tconst response = await this.raw(options);\n\t\treturn parseResponse(response);\n\t}\n\n\t/**\n\t * Runs a request from the API, yielding the raw Response object\n\t *\n\t * @param options - Request options\n\t */\n\tpublic async raw(options: InternalRequest) {\n\t\treturn this.requestManager.queueRequest(options);\n\t}\n}\n","export * from './lib/CDN.js';\nexport * from './lib/errors/DiscordAPIError.js';\nexport * from './lib/errors/HTTPError.js';\nexport * from './lib/errors/RateLimitError.js';\nexport * from './lib/RequestManager.js';\nexport * from './lib/REST.js';\nexport * from './lib/utils/constants.js';\nexport { makeURLSearchParams, parseResponse } from './lib/utils/utils.js';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/rest/#readme | @discordjs/rest} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\nexport const version = '1.7.1' as string;\n"],"mappings":";;;;AACA,SAAS,WAAW;;;ACDpB,OAAO,aAAa;AACpB,SAAS,kBAAkB;AAC3B,SAAS,aAAa;AAGf,IAAM,mBACZ;AAKM,IAAM,2BAA2B,QAAQ,SAAS,SAAS,SAAS,WAAW,QAAQ,YAAY;AAEnG,IAAM,qBAAqB;AAAA,EACjC,IAAI,QAAQ;AACX,WAAO,IAAI,MAAM;AAAA,MAChB,SAAS;AAAA,QACR,SAAS;AAAA,MAC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A;AAAA;AAAA;AAAA;AAAA;AAAA,EAOA,MAAa,IAAI,SAA0B;AAC1C,WAAO,KAAK,eAAe,aAAa,OAAO;AAAA,EAChD;AACD;AArHa;;;AC/NN,IAAM,UAAU;","names":["RESTEvents","Blob","Buffer","FormData","Buffer","Buffer","sleep","sleep","limit","res","RequestMethod","request","FormData","Buffer","Blob","EventEmitter","EventEmitter"]} \ No newline at end of file diff --git a/node_modules/@discordjs/rest/package.json b/node_modules/@discordjs/rest/package.json index 6c29560..6f668ae 100644 --- a/node_modules/@discordjs/rest/package.json +++ b/node_modules/@discordjs/rest/package.json @@ -1,97 +1,42 @@ { - "_from": "@discordjs/rest@^1.4.0", - "_id": "@discordjs/rest@1.5.0", - "_inBundle": false, - "_integrity": "sha512-lXgNFqHnbmzp5u81W0+frdXN6Etf4EUi8FAPcWpSykKd8hmlWh1xy6BmE0bsJypU1pxohaA8lQCgp70NUI3uzA==", - "_location": "/@discordjs/rest", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@discordjs/rest@^1.4.0", - "name": "@discordjs/rest", - "escapedName": "@discordjs%2frest", - "scope": "@discordjs", - "rawSpec": "^1.4.0", - "saveSpec": null, - "fetchSpec": "^1.4.0" - }, - "_requiredBy": [ - "/discord.js" - ], - "_resolved": "https://registry.npmjs.org/@discordjs/rest/-/rest-1.5.0.tgz", - "_shasum": "dc15474ab98cf6f31291bf61bbc72bcf4f30cea2", - "_spec": "@discordjs/rest@^1.4.0", - "_where": "D:\\programmen\\Discord bot\\CAROLINE\\node_modules\\discord.js", - "bugs": { - "url": "https://github.com/discordjs/discord.js/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Crawl", - "email": "icrawltogo@gmail.com" - }, - { - "name": "Amish Shah", - "email": "amishshah.2k@gmail.com" - }, - { - "name": "SpaceEEC", - "email": "spaceeec@yahoo.com" - }, - { - "name": "Vlad Frangu", - "email": "kingdgrizzle@gmail.com" - }, - { - "name": "Aura RomΓ‘n", - "email": "kyradiscord@gmail.com" - } - ], - "dependencies": { - "@discordjs/collection": "^1.3.0", - "@discordjs/util": "^0.1.0", - "@sapphire/async-queue": "^1.5.0", - "@sapphire/snowflake": "^3.2.2", - "discord-api-types": "^0.37.23", - "file-type": "^18.0.0", - "tslib": "^2.4.1", - "undici": "^5.13.0" - }, - "deprecated": false, + "name": "@discordjs/rest", + "version": "1.7.1", "description": "The REST API for discord.js", - "devDependencies": { - "@favware/cliff-jumper": "^1.9.0", - "@microsoft/api-extractor": "^7.33.6", - "@types/node": "16.18.4", - "@vitest/coverage-c8": "^0.25.3", - "cross-env": "^7.0.3", - "esbuild-plugin-version-injector": "^1.0.2", - "eslint": "^8.28.0", - "eslint-config-neon": "^0.1.40", - "eslint-formatter-pretty": "^4.1.0", - "prettier": "^2.8.0", - "tsup": "^6.5.0", - "typescript": "^4.9.3", - "vitest": "^0.25.3" + "scripts": { + "test": "vitest run", + "build": "tsup", + "build:docs": "tsc -p tsconfig.docs.json", + "lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty", + "format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty", + "fmt": "yarn format", + "docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json", + "prepack": "yarn lint && yarn test && yarn build", + "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/rest/*'", + "release": "cliff-jumper" + }, + "main": "./dist/index.js", + "module": "./dist/index.mjs", + "typings": "./dist/index.d.ts", + "exports": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" }, "directories": { "lib": "src", "test": "__tests__" }, - "engines": { - "node": ">=16.9.0" - }, - "exports": { - "import": "./dist/index.mjs", - "require": "./dist/index.js", - "types": "./dist/index.d.ts" - }, "files": [ "dist" ], - "homepage": "https://discord.js.org", + "contributors": [ + "Crawl ", + "Amish Shah ", + "SpaceEEC ", + "Vlad Frangu ", + "Aura RomΓ‘n " + ], + "license": "Apache-2.0", "keywords": [ "discord", "api", @@ -99,28 +44,44 @@ "discordapp", "discordjs" ], - "license": "Apache-2.0", - "main": "./dist/index.js", - "module": "./dist/index.mjs", - "name": "@discordjs/rest", - "publishConfig": { - "access": "public" - }, "repository": { "type": "git", - "url": "git+https://github.com/discordjs/discord.js.git" + "url": "https://github.com/discordjs/discord.js.git", + "directory": "packages/rest" }, - "scripts": { - "build": "tsup", - "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/rest/*'", - "docs": "api-extractor run --local", - "fmt": "yarn format", - "format": "prettier --write . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --fix --format=pretty", - "lint": "prettier --check . && cross-env TIMING=1 eslint src __tests__ --ext .mjs,.js,.ts --format=pretty", - "prepack": "yarn lint && yarn test && yarn build", - "release": "cliff-jumper", - "test": "vitest run" + "bugs": { + "url": "https://github.com/discordjs/discord.js/issues" }, - "typings": "./dist/index.d.ts", - "version": "1.5.0" -} + "homepage": "https://discord.js.org", + "dependencies": { + "@discordjs/collection": "^1.5.1", + "@discordjs/util": "^0.3.0", + "@sapphire/async-queue": "^1.5.0", + "@sapphire/snowflake": "^3.4.2", + "discord-api-types": "^0.37.41", + "file-type": "^18.3.0", + "tslib": "^2.5.0", + "undici": "^5.22.0" + }, + "devDependencies": { + "@favware/cliff-jumper": "^2.0.0", + "@microsoft/api-extractor": "^7.34.6", + "@types/node": "16.18.25", + "@vitest/coverage-c8": "^0.30.1", + "cross-env": "^7.0.3", + "esbuild-plugin-version-injector": "^1.1.0", + "eslint": "^8.39.0", + "eslint-config-neon": "^0.1.42", + "eslint-formatter-pretty": "^5.0.0", + "prettier": "^2.8.8", + "tsup": "^6.7.0", + "typescript": "^5.0.4", + "vitest": "^0.29.8" + }, + "engines": { + "node": ">=16.9.0" + }, + "publishConfig": { + "access": "public" + } +} \ No newline at end of file diff --git a/node_modules/@discordjs/util/CHANGELOG.md b/node_modules/@discordjs/util/CHANGELOG.md index ff1b8f5..1f7cb97 100644 --- a/node_modules/@discordjs/util/CHANGELOG.md +++ b/node_modules/@discordjs/util/CHANGELOG.md @@ -2,6 +2,54 @@ All notable changes to this project will be documented in this file. +# [@discordjs/util@0.3.1](https://github.com/discordjs/discord.js/compare/@discordjs/util@0.3.0...@discordjs/util@0.3.1) - (2023-05-01) + +## Refactor + +- **ShardClientUtil:** Logic de-duplication (#9491) ([a9f2bff](https://github.com/discordjs/discord.js/commit/a9f2bff82a18c6a3afdee99e5830e1d7b4da65dc)) + +# [@discordjs/util@0.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/util@0.2.0...@discordjs/util@0.3.0) - (2023-05-01) + +## Bug Fixes + +- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2)) +- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b)) + +## Documentation + +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) + +## Features + +- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b)) + +# [@discordjs/util@0.3.0](https://github.com/discordjs/discord.js/compare/@discordjs/util@0.2.0...@discordjs/util@0.3.0) - (2023-05-01) + +## Bug Fixes + +- Fix external links (#9313) ([a7425c2](https://github.com/discordjs/discord.js/commit/a7425c29c4f23f1b31f4c6a463107ca9eb7fd7e2)) +- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b)) + +## Documentation + +- Generate static imports for types with api-extractor ([98a76db](https://github.com/discordjs/discord.js/commit/98a76db482879f79d6bb2fb2e5fc65ac2c34e2d9)) + +## Features + +- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b)) + +# [@discordjs/util@0.2.0](https://github.com/discordjs/discord.js/compare/@discordjs/util@0.1.0...@discordjs/util@0.2.0) - (2023-03-12) + +## Bug Fixes + +- Pin @types/node version ([9d8179c](https://github.com/discordjs/discord.js/commit/9d8179c6a78e1c7f9976f852804055964d5385d4)) + +## Features + +- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38)) +- **core:** Implement some ws send events (#8941) ([816aed4](https://github.com/discordjs/discord.js/commit/816aed478e3035060697092d52ad2b58106be0ee)) +- Web-components (#8715) ([0ac3e76](https://github.com/discordjs/discord.js/commit/0ac3e766bd9dbdeb106483fa4bb085d74de346a2)) + # [@discordjs/util@0.1.0](https://github.com/discordjs/discord.js/tree/@discordjs/util@0.1.0) - (2022-10-03) ## Features diff --git a/node_modules/@discordjs/util/README.md b/node_modules/@discordjs/util/README.md index 543c22a..edd628d 100644 --- a/node_modules/@discordjs/util/README.md +++ b/node_modules/@discordjs/util/README.md @@ -13,22 +13,51 @@

+## About + +`@discordjs/util` is a collection of utility functions for use with discord.js. + +## Installation + +**Node.js 16.9.0 or newer is required.** + +```sh +npm install @discordjs/util +yarn add @discordjs/util +pnpm add @discordjs/util +``` + ## Links -- [Website](https://discord.js.org/) ([source](https://github.com/discordjs/discord.js/tree/main/packages/website)) -- [Documentation](https://discord.js.org/#/docs) -- [Guide](https://discordjs.guide/) ([source](https://github.com/discordjs/guide)) - See also the [Update Guide](https://discordjs.guide/additional-info/changes-in-v14.html), including updated and removed items in the library. -- [discord.js Discord server](https://discord.gg/djs) -- [Discord API Discord server](https://discord.gg/discord-api) -- [GitHub](https://github.com/discordjs/discord.js/tree/main/packages/scripts) -- [Related libraries](https://discord.com/developers/docs/topics/community-resources#libraries) +- [Website][website] ([source][website-source]) +- [Documentation][documentation] +- [Guide][guide] ([source][guide-source]) + Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library. +- [discord.js Discord server][discord] +- [Discord API Discord server][discord-api] +- [GitHub][source] +- [npm][npm] +- [Related libraries][related-libs] ## Contributing -See [the contribution guide](https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md) if you'd like to submit a PR. +Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the +[documentation][documentation]. +See [the contribution guide][contributing] if you'd like to submit a PR. ## Help -If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle -nudge in the right direction, please don't hesitate to join our official [discord.js Server](https://discord.gg/djs). +If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. + +[website]: https://discord.js.org +[website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website +[documentation]: https://discord.js.org/docs/packages/util/stable +[guide]: https://discordjs.guide/ +[guide-source]: https://github.com/discordjs/guide +[guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html +[discord]: https://discord.gg/djs +[discord-api]: https://discord.gg/discord-api +[source]: https://github.com/discordjs/discord.js/tree/main/packages/util +[npm]: https://www.npmjs.com/package/@discordjs/util +[related-libs]: https://discord.com/developers/docs/topics/community-resources#libraries +[contributing]: https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md diff --git a/node_modules/@discordjs/util/dist/index.d.ts b/node_modules/@discordjs/util/dist/index.d.ts index e12a3ec..13459b5 100644 --- a/node_modules/@discordjs/util/dist/index.d.ts +++ b/node_modules/@discordjs/util/dist/index.d.ts @@ -1,7 +1,7 @@ /** * Represents a type that may or may not be a promise */ -declare type Awaitable = PromiseLike | T; +type Awaitable = PromiseLike | T; /** * Lazy is a wrapper around a value that is computed lazily. It is useful for @@ -18,23 +18,57 @@ declare type Awaitable = PromiseLike | T; declare function lazy(cb: () => T): () => T; /** - * Yields the numbers in the given range as an array + * Options for creating a range + */ +interface RangeOptions { + /** + * The end of the range (exclusive) + */ + end: number; + /** + * The start of the range (inclusive) + */ + start: number; + /** + * The amount to increment by + * + * @defaultValue `1` + */ + step?: number; +} +/** + * A generator to yield numbers in a given range * - * @param start - The start of the range - * @param end - The end of the range (inclusive) - * @param step - The amount to increment between each number + * @remarks + * This method is end-exclusive, for example the last number yielded by `range(5)` is 4. If you + * prefer for the end to be included add 1 to the range or `end` option. + * @param range - A number representing the the range to yield (exclusive) or an object with start, end and step * @example * Basic range * ```ts - * range(3, 5); // [3, 4, 5] + * for (const number of range(5)) { + * console.log(number); + * } + * // Prints 0, 1, 2, 3, 4 * ``` * @example * Range with a step * ```ts - * range(3, 10, 2); // [3, 5, 7, 9] + * for (const number of range({ start: 3, end: 10, step: 2 })) { + * console.log(number); + * } + * // Prints 3, 5, 7, 9 * ``` */ -declare function range(start: number, end: number, step?: number): number[]; +declare function range(range: RangeOptions | number): Generator; + +/** + * Calculates the shard id for a given guild id. + * + * @param guildId - The guild id to calculate the shard id for + * @param shardCount - The total number of shards + */ +declare function calculateShardId(guildId: string, shardCount: number): number; /** * Represents an object capable of representing itself as a JSON object @@ -73,4 +107,4 @@ interface Equatable { */ declare function isEquatable(maybeEquatable: unknown): maybeEquatable is Equatable; -export { Awaitable, Equatable, JSONEncodable, isEquatable, isJSONEncodable, lazy, range }; +export { Awaitable, Equatable, JSONEncodable, RangeOptions, calculateShardId, isEquatable, isJSONEncodable, lazy, range }; diff --git a/node_modules/@discordjs/util/dist/index.js b/node_modules/@discordjs/util/dist/index.js index 9078bfd..d4859a1 100644 --- a/node_modules/@discordjs/util/dist/index.js +++ b/node_modules/@discordjs/util/dist/index.js @@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru // src/index.ts var src_exports = {}; __export(src_exports, { + calculateShardId: () => calculateShardId, isEquatable: () => isEquatable, isJSONEncodable: () => isJSONEncodable, lazy: () => lazy, @@ -36,11 +37,29 @@ function lazy(cb) { __name(lazy, "lazy"); // src/functions/range.ts -function range(start, end, step = 1) { - return Array.from({ length: (end - start) / step + 1 }, (_, index) => start + index * step); +function* range(range2) { + let rangeEnd; + let start = 0; + let step = 1; + if (typeof range2 === "number") { + rangeEnd = range2; + } else { + start = range2.start; + rangeEnd = range2.end; + step = range2.step ?? 1; + } + for (let index = start; index < rangeEnd; index += step) { + yield index; + } } __name(range, "range"); +// src/functions/calculateShardId.ts +function calculateShardId(guildId, shardCount) { + return Number(BigInt(guildId) >> 22n) % shardCount; +} +__name(calculateShardId, "calculateShardId"); + // src/JSONEncodable.ts function isJSONEncodable(maybeEncodable) { return maybeEncodable !== null && typeof maybeEncodable === "object" && "toJSON" in maybeEncodable; @@ -54,6 +73,7 @@ function isEquatable(maybeEquatable) { __name(isEquatable, "isEquatable"); // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { + calculateShardId, isEquatable, isJSONEncodable, lazy, diff --git a/node_modules/@discordjs/util/dist/index.js.map b/node_modules/@discordjs/util/dist/index.js.map index f059cfe..60cab93 100644 --- a/node_modules/@discordjs/util/dist/index.js.map +++ b/node_modules/@discordjs/util/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.ts","../src/functions/lazy.ts","../src/functions/range.ts","../src/JSONEncodable.ts","../src/Equatable.ts"],"sourcesContent":["export * from './types.js';\nexport * from './functions/index.js';\nexport * from './JSONEncodable.js';\nexport * from './Equatable.js';\n","/**\n * Lazy is a wrapper around a value that is computed lazily. It is useful for\n * cases where the value is expensive to compute and the computation may not\n * be needed at all.\n *\n * @param cb - The callback to lazily evaluate\n * @typeParam T - The type of the value\n * @example\n * ```ts\n * const value = lazy(() => computeExpensiveValue());\n * ```\n */\n// eslint-disable-next-line promise/prefer-await-to-callbacks\nexport function lazy(cb: () => T): () => T {\n\tlet defaultValue: T;\n\t// eslint-disable-next-line promise/prefer-await-to-callbacks\n\treturn () => (defaultValue ??= cb());\n}\n","/**\n * Yields the numbers in the given range as an array\n *\n * @param start - The start of the range\n * @param end - The end of the range (inclusive)\n * @param step - The amount to increment between each number\n * @example\n * Basic range\n * ```ts\n * range(3, 5); // [3, 4, 5]\n * ```\n * @example\n * Range with a step\n * ```ts\n * range(3, 10, 2); // [3, 5, 7, 9]\n * ```\n */\nexport function range(start: number, end: number, step = 1): number[] {\n\treturn Array.from({ length: (end - start) / step + 1 }, (_, index) => start + index * step);\n}\n","/**\n * Represents an object capable of representing itself as a JSON object\n *\n * @typeParam T - The JSON type corresponding to {@link JSONEncodable.toJSON} outputs.\n */\nexport interface JSONEncodable {\n\t/**\n\t * Transforms this object to its JSON format\n\t */\n\ttoJSON(): T;\n}\n\n/**\n * Indicates if an object is encodable or not.\n *\n * @param maybeEncodable - The object to check against\n */\nexport function isJSONEncodable(maybeEncodable: unknown): maybeEncodable is JSONEncodable {\n\treturn maybeEncodable !== null && typeof maybeEncodable === 'object' && 'toJSON' in maybeEncodable;\n}\n","/**\n * Represents a structure that can be checked against another\n * given structure for equality\n *\n * @typeParam T - The type of object to compare the current object to\n */\nexport interface Equatable {\n\t/**\n\t * Whether or not this is equal to another structure\n\t */\n\tequals(other: T): boolean;\n}\n\n/**\n * Indicates if an object is equatable or not.\n *\n * @param maybeEquatable - The object to check against\n */\nexport function isEquatable(maybeEquatable: unknown): maybeEquatable is Equatable {\n\treturn maybeEquatable !== null && typeof maybeEquatable === 'object' && 'equals' in maybeEquatable;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,SAAS,KAAQ,IAAsB;AAC7C,MAAI;AAEJ,SAAO,MAAO,iBAAiB,GAAG;AACnC;AAJgB;;;ACIT,SAAS,MAAM,OAAe,KAAa,OAAO,GAAa;AACrE,SAAO,MAAM,KAAK,EAAE,SAAS,MAAM,SAAS,OAAO,EAAE,GAAG,CAAC,GAAG,UAAU,QAAQ,QAAQ,IAAI;AAC3F;AAFgB;;;ACAT,SAAS,gBAAgB,gBAAmE;AAClG,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;;;ACCT,SAAS,YAAY,gBAA+D;AAC1F,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;","names":[]} \ No newline at end of file +{"version":3,"sources":["../src/index.ts","../src/functions/lazy.ts","../src/functions/range.ts","../src/functions/calculateShardId.ts","../src/JSONEncodable.ts","../src/Equatable.ts"],"sourcesContent":["export * from './types.js';\nexport * from './functions/index.js';\nexport * from './JSONEncodable.js';\nexport * from './Equatable.js';\n","/**\n * Lazy is a wrapper around a value that is computed lazily. It is useful for\n * cases where the value is expensive to compute and the computation may not\n * be needed at all.\n *\n * @param cb - The callback to lazily evaluate\n * @typeParam T - The type of the value\n * @example\n * ```ts\n * const value = lazy(() => computeExpensiveValue());\n * ```\n */\n// eslint-disable-next-line promise/prefer-await-to-callbacks\nexport function lazy(cb: () => T): () => T {\n\tlet defaultValue: T;\n\t// eslint-disable-next-line promise/prefer-await-to-callbacks\n\treturn () => (defaultValue ??= cb());\n}\n","/**\n * Options for creating a range\n */\nexport interface RangeOptions {\n\t/**\n\t * The end of the range (exclusive)\n\t */\n\tend: number;\n\t/**\n\t * The start of the range (inclusive)\n\t */\n\tstart: number;\n\t/**\n\t * The amount to increment by\n\t *\n\t * @defaultValue `1`\n\t */\n\tstep?: number;\n}\n\n/**\n * A generator to yield numbers in a given range\n *\n * @remarks\n * This method is end-exclusive, for example the last number yielded by `range(5)` is 4. If you\n * prefer for the end to be included add 1 to the range or `end` option.\n * @param range - A number representing the the range to yield (exclusive) or an object with start, end and step\n * @example\n * Basic range\n * ```ts\n * for (const number of range(5)) {\n * console.log(number);\n * }\n * // Prints 0, 1, 2, 3, 4\n * ```\n * @example\n * Range with a step\n * ```ts\n * for (const number of range({ start: 3, end: 10, step: 2 })) {\n * \tconsole.log(number);\n * }\n * // Prints 3, 5, 7, 9\n * ```\n */\nexport function* range(range: RangeOptions | number) {\n\tlet rangeEnd: number;\n\tlet start = 0;\n\tlet step = 1;\n\n\tif (typeof range === 'number') {\n\t\trangeEnd = range;\n\t} else {\n\t\tstart = range.start;\n\t\trangeEnd = range.end;\n\t\tstep = range.step ?? 1;\n\t}\n\n\tfor (let index = start; index < rangeEnd; index += step) {\n\t\tyield index;\n\t}\n}\n","/**\n * Calculates the shard id for a given guild id.\n *\n * @param guildId - The guild id to calculate the shard id for\n * @param shardCount - The total number of shards\n */\nexport function calculateShardId(guildId: string, shardCount: number) {\n\treturn Number(BigInt(guildId) >> 22n) % shardCount;\n}\n","/**\n * Represents an object capable of representing itself as a JSON object\n *\n * @typeParam T - The JSON type corresponding to {@link JSONEncodable.toJSON} outputs.\n */\nexport interface JSONEncodable {\n\t/**\n\t * Transforms this object to its JSON format\n\t */\n\ttoJSON(): T;\n}\n\n/**\n * Indicates if an object is encodable or not.\n *\n * @param maybeEncodable - The object to check against\n */\nexport function isJSONEncodable(maybeEncodable: unknown): maybeEncodable is JSONEncodable {\n\treturn maybeEncodable !== null && typeof maybeEncodable === 'object' && 'toJSON' in maybeEncodable;\n}\n","/**\n * Represents a structure that can be checked against another\n * given structure for equality\n *\n * @typeParam T - The type of object to compare the current object to\n */\nexport interface Equatable {\n\t/**\n\t * Whether or not this is equal to another structure\n\t */\n\tequals(other: T): boolean;\n}\n\n/**\n * Indicates if an object is equatable or not.\n *\n * @param maybeEquatable - The object to check against\n */\nexport function isEquatable(maybeEquatable: unknown): maybeEquatable is Equatable {\n\treturn maybeEquatable !== null && typeof maybeEquatable === 'object' && 'equals' in maybeEquatable;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaO,SAAS,KAAQ,IAAsB;AAC7C,MAAI;AAEJ,SAAO,MAAO,iBAAiB,GAAG;AACnC;AAJgB;;;AC+BT,UAAU,MAAMA,QAA8B;AACpD,MAAI;AACJ,MAAI,QAAQ;AACZ,MAAI,OAAO;AAEX,MAAI,OAAOA,WAAU,UAAU;AAC9B,eAAWA;AAAA,EACZ,OAAO;AACN,YAAQA,OAAM;AACd,eAAWA,OAAM;AACjB,WAAOA,OAAM,QAAQ;AAAA,EACtB;AAEA,WAAS,QAAQ,OAAO,QAAQ,UAAU,SAAS,MAAM;AACxD,UAAM;AAAA,EACP;AACD;AAhBiB;;;ACtCV,SAAS,iBAAiB,SAAiB,YAAoB;AACrE,SAAO,OAAO,OAAO,OAAO,KAAK,GAAG,IAAI;AACzC;AAFgB;;;ACWT,SAAS,gBAAgB,gBAAmE;AAClG,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;;;ACCT,SAAS,YAAY,gBAA+D;AAC1F,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;","names":["range"]} \ No newline at end of file diff --git a/node_modules/@discordjs/util/dist/index.mjs b/node_modules/@discordjs/util/dist/index.mjs index 4b56502..2b50e8f 100644 --- a/node_modules/@discordjs/util/dist/index.mjs +++ b/node_modules/@discordjs/util/dist/index.mjs @@ -9,11 +9,29 @@ function lazy(cb) { __name(lazy, "lazy"); // src/functions/range.ts -function range(start, end, step = 1) { - return Array.from({ length: (end - start) / step + 1 }, (_, index) => start + index * step); +function* range(range2) { + let rangeEnd; + let start = 0; + let step = 1; + if (typeof range2 === "number") { + rangeEnd = range2; + } else { + start = range2.start; + rangeEnd = range2.end; + step = range2.step ?? 1; + } + for (let index = start; index < rangeEnd; index += step) { + yield index; + } } __name(range, "range"); +// src/functions/calculateShardId.ts +function calculateShardId(guildId, shardCount) { + return Number(BigInt(guildId) >> 22n) % shardCount; +} +__name(calculateShardId, "calculateShardId"); + // src/JSONEncodable.ts function isJSONEncodable(maybeEncodable) { return maybeEncodable !== null && typeof maybeEncodable === "object" && "toJSON" in maybeEncodable; @@ -26,6 +44,7 @@ function isEquatable(maybeEquatable) { } __name(isEquatable, "isEquatable"); export { + calculateShardId, isEquatable, isJSONEncodable, lazy, diff --git a/node_modules/@discordjs/util/dist/index.mjs.map b/node_modules/@discordjs/util/dist/index.mjs.map index b9081f6..6d73425 100644 --- a/node_modules/@discordjs/util/dist/index.mjs.map +++ b/node_modules/@discordjs/util/dist/index.mjs.map @@ -1 +1 @@ -{"version":3,"sources":["../src/functions/lazy.ts","../src/functions/range.ts","../src/JSONEncodable.ts","../src/Equatable.ts"],"sourcesContent":["/**\n * Lazy is a wrapper around a value that is computed lazily. It is useful for\n * cases where the value is expensive to compute and the computation may not\n * be needed at all.\n *\n * @param cb - The callback to lazily evaluate\n * @typeParam T - The type of the value\n * @example\n * ```ts\n * const value = lazy(() => computeExpensiveValue());\n * ```\n */\n// eslint-disable-next-line promise/prefer-await-to-callbacks\nexport function lazy(cb: () => T): () => T {\n\tlet defaultValue: T;\n\t// eslint-disable-next-line promise/prefer-await-to-callbacks\n\treturn () => (defaultValue ??= cb());\n}\n","/**\n * Yields the numbers in the given range as an array\n *\n * @param start - The start of the range\n * @param end - The end of the range (inclusive)\n * @param step - The amount to increment between each number\n * @example\n * Basic range\n * ```ts\n * range(3, 5); // [3, 4, 5]\n * ```\n * @example\n * Range with a step\n * ```ts\n * range(3, 10, 2); // [3, 5, 7, 9]\n * ```\n */\nexport function range(start: number, end: number, step = 1): number[] {\n\treturn Array.from({ length: (end - start) / step + 1 }, (_, index) => start + index * step);\n}\n","/**\n * Represents an object capable of representing itself as a JSON object\n *\n * @typeParam T - The JSON type corresponding to {@link JSONEncodable.toJSON} outputs.\n */\nexport interface JSONEncodable {\n\t/**\n\t * Transforms this object to its JSON format\n\t */\n\ttoJSON(): T;\n}\n\n/**\n * Indicates if an object is encodable or not.\n *\n * @param maybeEncodable - The object to check against\n */\nexport function isJSONEncodable(maybeEncodable: unknown): maybeEncodable is JSONEncodable {\n\treturn maybeEncodable !== null && typeof maybeEncodable === 'object' && 'toJSON' in maybeEncodable;\n}\n","/**\n * Represents a structure that can be checked against another\n * given structure for equality\n *\n * @typeParam T - The type of object to compare the current object to\n */\nexport interface Equatable {\n\t/**\n\t * Whether or not this is equal to another structure\n\t */\n\tequals(other: T): boolean;\n}\n\n/**\n * Indicates if an object is equatable or not.\n *\n * @param maybeEquatable - The object to check against\n */\nexport function isEquatable(maybeEquatable: unknown): maybeEquatable is Equatable {\n\treturn maybeEquatable !== null && typeof maybeEquatable === 'object' && 'equals' in maybeEquatable;\n}\n"],"mappings":";;;;AAaO,SAAS,KAAQ,IAAsB;AAC7C,MAAI;AAEJ,SAAO,MAAO,iBAAiB,GAAG;AACnC;AAJgB;;;ACIT,SAAS,MAAM,OAAe,KAAa,OAAO,GAAa;AACrE,SAAO,MAAM,KAAK,EAAE,SAAS,MAAM,SAAS,OAAO,EAAE,GAAG,CAAC,GAAG,UAAU,QAAQ,QAAQ,IAAI;AAC3F;AAFgB;;;ACAT,SAAS,gBAAgB,gBAAmE;AAClG,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;;;ACCT,SAAS,YAAY,gBAA+D;AAC1F,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;","names":[]} \ No newline at end of file +{"version":3,"sources":["../src/functions/lazy.ts","../src/functions/range.ts","../src/functions/calculateShardId.ts","../src/JSONEncodable.ts","../src/Equatable.ts"],"sourcesContent":["/**\n * Lazy is a wrapper around a value that is computed lazily. It is useful for\n * cases where the value is expensive to compute and the computation may not\n * be needed at all.\n *\n * @param cb - The callback to lazily evaluate\n * @typeParam T - The type of the value\n * @example\n * ```ts\n * const value = lazy(() => computeExpensiveValue());\n * ```\n */\n// eslint-disable-next-line promise/prefer-await-to-callbacks\nexport function lazy(cb: () => T): () => T {\n\tlet defaultValue: T;\n\t// eslint-disable-next-line promise/prefer-await-to-callbacks\n\treturn () => (defaultValue ??= cb());\n}\n","/**\n * Options for creating a range\n */\nexport interface RangeOptions {\n\t/**\n\t * The end of the range (exclusive)\n\t */\n\tend: number;\n\t/**\n\t * The start of the range (inclusive)\n\t */\n\tstart: number;\n\t/**\n\t * The amount to increment by\n\t *\n\t * @defaultValue `1`\n\t */\n\tstep?: number;\n}\n\n/**\n * A generator to yield numbers in a given range\n *\n * @remarks\n * This method is end-exclusive, for example the last number yielded by `range(5)` is 4. If you\n * prefer for the end to be included add 1 to the range or `end` option.\n * @param range - A number representing the the range to yield (exclusive) or an object with start, end and step\n * @example\n * Basic range\n * ```ts\n * for (const number of range(5)) {\n * console.log(number);\n * }\n * // Prints 0, 1, 2, 3, 4\n * ```\n * @example\n * Range with a step\n * ```ts\n * for (const number of range({ start: 3, end: 10, step: 2 })) {\n * \tconsole.log(number);\n * }\n * // Prints 3, 5, 7, 9\n * ```\n */\nexport function* range(range: RangeOptions | number) {\n\tlet rangeEnd: number;\n\tlet start = 0;\n\tlet step = 1;\n\n\tif (typeof range === 'number') {\n\t\trangeEnd = range;\n\t} else {\n\t\tstart = range.start;\n\t\trangeEnd = range.end;\n\t\tstep = range.step ?? 1;\n\t}\n\n\tfor (let index = start; index < rangeEnd; index += step) {\n\t\tyield index;\n\t}\n}\n","/**\n * Calculates the shard id for a given guild id.\n *\n * @param guildId - The guild id to calculate the shard id for\n * @param shardCount - The total number of shards\n */\nexport function calculateShardId(guildId: string, shardCount: number) {\n\treturn Number(BigInt(guildId) >> 22n) % shardCount;\n}\n","/**\n * Represents an object capable of representing itself as a JSON object\n *\n * @typeParam T - The JSON type corresponding to {@link JSONEncodable.toJSON} outputs.\n */\nexport interface JSONEncodable {\n\t/**\n\t * Transforms this object to its JSON format\n\t */\n\ttoJSON(): T;\n}\n\n/**\n * Indicates if an object is encodable or not.\n *\n * @param maybeEncodable - The object to check against\n */\nexport function isJSONEncodable(maybeEncodable: unknown): maybeEncodable is JSONEncodable {\n\treturn maybeEncodable !== null && typeof maybeEncodable === 'object' && 'toJSON' in maybeEncodable;\n}\n","/**\n * Represents a structure that can be checked against another\n * given structure for equality\n *\n * @typeParam T - The type of object to compare the current object to\n */\nexport interface Equatable {\n\t/**\n\t * Whether or not this is equal to another structure\n\t */\n\tequals(other: T): boolean;\n}\n\n/**\n * Indicates if an object is equatable or not.\n *\n * @param maybeEquatable - The object to check against\n */\nexport function isEquatable(maybeEquatable: unknown): maybeEquatable is Equatable {\n\treturn maybeEquatable !== null && typeof maybeEquatable === 'object' && 'equals' in maybeEquatable;\n}\n"],"mappings":";;;;AAaO,SAAS,KAAQ,IAAsB;AAC7C,MAAI;AAEJ,SAAO,MAAO,iBAAiB,GAAG;AACnC;AAJgB;;;AC+BT,UAAU,MAAMA,QAA8B;AACpD,MAAI;AACJ,MAAI,QAAQ;AACZ,MAAI,OAAO;AAEX,MAAI,OAAOA,WAAU,UAAU;AAC9B,eAAWA;AAAA,EACZ,OAAO;AACN,YAAQA,OAAM;AACd,eAAWA,OAAM;AACjB,WAAOA,OAAM,QAAQ;AAAA,EACtB;AAEA,WAAS,QAAQ,OAAO,QAAQ,UAAU,SAAS,MAAM;AACxD,UAAM;AAAA,EACP;AACD;AAhBiB;;;ACtCV,SAAS,iBAAiB,SAAiB,YAAoB;AACrE,SAAO,OAAO,OAAO,OAAO,KAAK,GAAG,IAAI;AACzC;AAFgB;;;ACWT,SAAS,gBAAgB,gBAAmE;AAClG,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;;;ACCT,SAAS,YAAY,gBAA+D;AAC1F,SAAO,mBAAmB,QAAQ,OAAO,mBAAmB,YAAY,YAAY;AACrF;AAFgB;","names":["range"]} \ No newline at end of file diff --git a/node_modules/@discordjs/util/package.json b/node_modules/@discordjs/util/package.json index 2a8031a..aae4201 100644 --- a/node_modules/@discordjs/util/package.json +++ b/node_modules/@discordjs/util/package.json @@ -1,88 +1,41 @@ { - "_from": "@discordjs/util@^0.1.0", - "_id": "@discordjs/util@0.1.0", - "_inBundle": false, - "_integrity": "sha512-e7d+PaTLVQav6rOc2tojh2y6FE8S7REkqLldq1XF4soCx74XB/DIjbVbVLtBemf0nLW77ntz0v+o5DytKwFNLQ==", - "_location": "/@discordjs/util", - "_phantomChildren": {}, - "_requested": { - "type": "range", - "registry": true, - "raw": "@discordjs/util@^0.1.0", - "name": "@discordjs/util", - "escapedName": "@discordjs%2futil", - "scope": "@discordjs", - "rawSpec": "^0.1.0", - "saveSpec": null, - "fetchSpec": "^0.1.0" - }, - "_requiredBy": [ - "/@discordjs/builders", - "/@discordjs/rest", - "/discord.js" - ], - "_resolved": "https://registry.npmjs.org/@discordjs/util/-/util-0.1.0.tgz", - "_shasum": "e42ca1bf407bc6d9adf252877d1b206e32ba369a", - "_spec": "@discordjs/util@^0.1.0", - "_where": "D:\\programmen\\Discord bot\\CAROLINE\\node_modules\\discord.js", - "bugs": { - "url": "https://github.com/discordjs/discord.js/issues" - }, - "bundleDependencies": false, - "contributors": [ - { - "name": "Crawl", - "email": "icrawltogo@gmail.com" - }, - { - "name": "Amish Shah", - "email": "amishshah.2k@gmail.com" - }, - { - "name": "Vlad Frangu", - "email": "kingdgrizzle@gmail.com" - }, - { - "name": "SpaceEEC", - "email": "spaceeec@yahoo.com" - }, - { - "name": "Aura RomΓ‘n", - "email": "kyradiscord@gmail.com" - } - ], - "deprecated": false, + "name": "@discordjs/util", + "version": "0.3.1", "description": "Utilities shared across Discord.js packages", - "devDependencies": { - "@favware/cliff-jumper": "^1.8.8", - "@microsoft/api-extractor": "^7.32.0", - "@types/node": "^16.11.56", - "@vitest/coverage-c8": "^0.22.1", - "cross-env": "^7.0.3", - "downlevel-dts": "^0.10.1", - "eslint": "^8.23.0", - "eslint-config-neon": "^0.1.31", - "prettier": "^2.7.1", - "tsd": "^0.23.0", - "tsup": "^6.2.3", - "typescript": "^4.8.2", - "vitest": "^0.22.1" - }, - "directories": { - "lib": "src" - }, - "engines": { - "node": ">=16.9.0" + "scripts": { + "build": "tsup", + "build:docs": "tsc -p tsconfig.docs.json", + "test": "vitest run && tsd", + "lint": "prettier --check . && TIMING=1 eslint src --ext .mjs,.js,.ts --format=pretty", + "format": "prettier --write . && TIMING=1 eslint src --ext .mjs,.js,.ts --fix --format=pretty", + "fmt": "yarn format", + "docs": "yarn build:docs && api-extractor run --local && api-extractor run --local --config ./api-extractor-docs.json", + "prepack": "yarn lint && yarn test && yarn build", + "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/util/*'", + "release": "cliff-jumper" }, + "main": "./dist/index.js", + "module": "./dist/index.mjs", + "types": "./dist/index.d.ts", "exports": { + "types": "./dist/index.d.ts", "import": "./dist/index.mjs", - "require": "./dist/index.js", - "types": "./dist/index.d.ts" + "require": "./dist/index.js" + }, + "directories": { + "lib": "src" }, "files": [ "dist" ], - "homepage": "https://discord.js.org", + "contributors": [ + "Crawl ", + "Amish Shah ", + "Vlad Frangu ", + "SpaceEEC ", + "Aura RomΓ‘n " + ], + "license": "Apache-2.0", "keywords": [ "api", "bot", @@ -90,31 +43,37 @@ "node", "discordjs" ], - "license": "Apache-2.0", - "main": "./dist/index.js", - "module": "./dist/index.mjs", - "name": "@discordjs/util", - "publishConfig": { - "access": "public" - }, "repository": { "type": "git", - "url": "git+https://github.com/discordjs/discord.js.git" + "url": "https://github.com/discordjs/discord.js.git", + "directory": "packages/util" }, - "scripts": { - "build": "tsup", - "changelog": "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/util/*'", - "docs": "downlevel-dts dist docs/dist --to=3.7 && api-extractor run --local", - "fmt": "yarn format", - "format": "prettier --write . && TIMING=1 eslint src --ext mjs,js,ts --fix", - "lint": "prettier --check . && TIMING=1 eslint src --ext mjs,js,ts", - "prepack": "yarn lint && yarn test && yarn build", - "release": "cliff-jumper", - "test": "vitest run && tsd" + "bugs": { + "url": "https://github.com/discordjs/discord.js/issues" + }, + "homepage": "https://discord.js.org", + "devDependencies": { + "@favware/cliff-jumper": "^2.0.0", + "@microsoft/api-extractor": "^7.34.6", + "@types/node": "16.18.25", + "@vitest/coverage-c8": "^0.30.1", + "cross-env": "^7.0.3", + "eslint": "^8.39.0", + "eslint-config-neon": "^0.1.42", + "eslint-formatter-pretty": "^5.0.0", + "prettier": "^2.8.8", + "tsd": "^0.28.1", + "tsup": "^6.7.0", + "typescript": "^5.0.4", + "vitest": "^0.29.8" + }, + "engines": { + "node": ">=16.9.0" + }, + "publishConfig": { + "access": "public" }, "tsd": { "directory": "__tests__/types" - }, - "types": "./dist/index.d.ts", - "version": "0.1.0" -} + } +} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/CHANGELOG.md b/node_modules/@discordjs/voice/CHANGELOG.md index 0940112..7b6dcff 100644 --- a/node_modules/@discordjs/voice/CHANGELOG.md +++ b/node_modules/@discordjs/voice/CHANGELOG.md @@ -2,6 +2,67 @@ All notable changes to this project will be documented in this file. +# [@discordjs/voice@0.16.0](https://github.com/discordjs/discord.js/compare/@discordjs/voice@0.15.0...@discordjs/voice@0.16.0) - (2023-04-01) + +## Bug Fixes + +- **scripts:** Accessing tsComment ([d8d5f31](https://github.com/discordjs/discord.js/commit/d8d5f31d3927fd1de62f1fa3a1a6e454243ad87b)) + +## Features + +- **website:** Render syntax and mdx on the server (#9086) ([ee5169e](https://github.com/discordjs/discord.js/commit/ee5169e0aadd7bbfcd752aae614ec0f69602b68b)) + +## Refactor + +- Compare with `undefined` directly (#9191) ([869153c](https://github.com/discordjs/discord.js/commit/869153c3fdf155783e7c0ecebd3627b087c3a026)) + +# [@discordjs/voice@0.15.0](https://github.com/discordjs/discord.js/compare/@discordjs/voice@0.14.0...@discordjs/voice@0.15.0) - (2023-03-12) + +## Bug Fixes + +- **Voice:** Send keep alives without awaiting a response (#9202) ([c6d98fa](https://github.com/discordjs/discord.js/commit/c6d98fa0c55a482cd4a81abd6f08290c29839b1b)) + +## Documentation + +- Fix version export (#9049) ([8b70f49](https://github.com/discordjs/discord.js/commit/8b70f497a1207e30edebdecd12b926c981c13d28)) + +## Features + +- **website:** Add support for source file links (#9048) ([f6506e9](https://github.com/discordjs/discord.js/commit/f6506e99c496683ee0ab67db0726b105b929af38)) + +# [@discordjs/voice@0.14.0](https://github.com/discordjs/discord.js/compare/@discordjs/voice@0.13.0...@discordjs/voice@0.14.0) - (2022-11-28) + +## Bug Fixes + +- Voice postbuild script (#8741) ([5ffabb1](https://github.com/discordjs/discord.js/commit/5ffabb119fa3a35266ab31545a4a4b9a049eacce)) +- Pin @types/node version ([9d8179c](https://github.com/discordjs/discord.js/commit/9d8179c6a78e1c7f9976f852804055964d5385d4)) + +## Features + +- New select menus (#8793) ([5152abf](https://github.com/discordjs/discord.js/commit/5152abf7285581abf7689e9050fdc56c4abb1e2b)) + +# [@discordjs/voice@0.13.0](https://github.com/discordjs/discord.js/compare/@discordjs/voice@0.11.0...@discordjs/voice@0.13.0) - (2022-10-08) + +## Bug Fixes + +- Footer / sidebar / deprecation alert ([ba3e0ed](https://github.com/discordjs/discord.js/commit/ba3e0ed348258fe8e51eefb4aa7379a1230616a9)) + +## Documentation + +- Change name (#8604) ([dd5a089](https://github.com/discordjs/discord.js/commit/dd5a08944c258a847fc4377f1d5e953264ab47d0)) + +## Features + +- Web-components (#8715) ([0ac3e76](https://github.com/discordjs/discord.js/commit/0ac3e766bd9dbdeb106483fa4bb085d74de346a2)) +- **website:** Show `constructor` information (#8540) ([e42fd16](https://github.com/discordjs/discord.js/commit/e42fd1636973b10dd7ed6fb4280ee1a4a8f82007)) +- **WebSocketShard:** Support new resume url (#8480) ([bc06cc6](https://github.com/discordjs/discord.js/commit/bc06cc638d2f57ab5c600e8cdb6afc8eb2180166)) + +## Refactor + +- Website components (#8600) ([c334157](https://github.com/discordjs/discord.js/commit/c3341570d983aea9ecc419979d5a01de658c9d67)) +- Use `eslint-config-neon` for packages. (#8579) ([edadb9f](https://github.com/discordjs/discord.js/commit/edadb9fe5dfd9ff51a3cfc9b25cb242d3f9f5241)) +- Docs design (#8487) ([4ab1d09](https://github.com/discordjs/discord.js/commit/4ab1d09997a18879a9eb9bda39df6f15aa22557e)) + # [@discordjs/voice@0.11.0](https://github.com/discordjs/discord.js/compare/@discordjs/voice@0.10.0...@discordjs/voice@0.11.0) - (2022-07-17) ## Bug Fixes @@ -36,19 +97,7 @@ All notable changes to this project will be documented in this file. - **voice:** Bring back typed events (#8109) ([70b42bb](https://github.com/discordjs/discord.js/commit/70b42bb64a4f83da0da242569b9c7921c8d1e26f)) -# [@discordjs/voice@0.10.0](https://github.com/discordjs/discord.js/compare/@discordjs/voice@0.9.0...@discordjs/voice@0.10.0) - (2022-06-04) - -## Styling - -- Cleanup tests and tsup configs ([6b8ef20](https://github.com/discordjs/discord.js/commit/6b8ef20cb3af5b5cfd176dd0aa0a1a1e98551629)) - -# [@discordjs/voice@0.10.0](https://github.com/discordjs/discord.js/compare/@discordjs/voice@0.9.0...@discordjs/voice@0.10.0) - (2022-06-04) - -## Styling - -- Cleanup tests and tsup configs ([6b8ef20](https://github.com/discordjs/discord.js/commit/6b8ef20cb3af5b5cfd176dd0aa0a1a1e98551629)) - -# [@discordjs/voice@0.9.0](https://github.com/discordjs/discord.js/compare/@discordjs/voice@0.8.0...@discordjs/voice@0.9.0) - (2022-04-17) +# [@discordjs/voice@0.10.0](https://github.com/discordjs/discord.js/compare/@discordjs/voice@0.8.0...@discordjs/voice@0.10.0) - (2022-06-04) ## Bug Fixes @@ -76,39 +125,3 @@ All notable changes to this project will be documented in this file. - **voice:** Fix tests ([62c74b8](https://github.com/discordjs/discord.js/commit/62c74b8333066465e5bd295b8b102b35a506751d)) - Fix voice secretbox tests ([4a2dbd6](https://github.com/discordjs/discord.js/commit/4a2dbd62382f904d596b34da0116d50e724b81c4)) - Fix voice tests ([b593bd3](https://github.com/discordjs/discord.js/commit/b593bd32a98282a92fa28f2fb0a8ef239866622c)) - -# [0.7.5](https://github.com/discordjs/voice/compare/v0.7.4...v0.7.5) (2021-11-12) - -## Bug Fixes - -- postbuild script ([644af95](https://github.com/discordjs/voice/commit/644af9579f02724c489514f482640b8413d2c305)) - -# [0.7.4](https://github.com/discordjs/voice/compare/v0.7.3...v0.7.4) (2021-11-12) - -## Bug Fixes - -- conditionally apply banner only to esm build ([8c4e8c4](https://github.com/discordjs/voice/commit/8c4e8c4ba5b9013a90de0238a7f2771e9113a62d)) - -# [0.7.3](https://github.com/discordjs/voice/compare/v0.7.2...v0.7.3) (2021-11-11) - -## Bug Fixes - -- **esm:** resolve esm imports ([#229](https://github.com/discordjs/voice/issues/229)) ([616f2bc](https://github.com/discordjs/voice/commit/616f2bcfde47e55ac7b09f4faaa07f15d78c11a5)) - -# [0.7.2](https://github.com/discordjs/voice/compare/v0.7.1...v0.7.2) (2021-10-30) - -## Bug Fixes - -- prism imports for ems ([0bfd6d5](https://github.com/discordjs/voice/commit/0bfd6d5247f89cfc125e7645e9fb7ebfed94bb2f)) - -# [0.7.1](https://github.com/discordjs/voice/compare/v0.7.0...v0.7.1) (2021-10-30) - -## Bug Fixes - -- prism imports for esm ([9222dbf](https://github.com/discordjs/voice/commit/9222dbfedd8bfaeb679133dfa41330ea75a03a70)) - -# [0.7.0](https://github.com/discordjs/voice/compare/v0.6.0...v0.7.0) (2021-10-30) - -## Features - -- export some types so they render in docs ([#211](https://github.com/discordjs/voice/issues/211)) ([a6dad47](https://github.com/discordjs/voice/commit/a6dad4781fb479d22d7bff99888e42368d6d6411)) diff --git a/node_modules/@discordjs/voice/README.md b/node_modules/@discordjs/voice/README.md index 22b005b..05d57f8 100644 --- a/node_modules/@discordjs/voice/README.md +++ b/node_modules/@discordjs/voice/README.md @@ -4,18 +4,21 @@ discord.js


-

+

Discord server npm version npm downloads Build status Code coverage

+

+ Vercel +

## About -An implementation of the Discord Voice API for Node.js, written in TypeScript. +`@discordjs/voice` is a TypeScript implementation of the Discord Voice API for Node.js. **Features:** @@ -30,7 +33,7 @@ An implementation of the Discord Voice API for Node.js, written in TypeScript. **Node.js 16.9.0 or newer is required.** -```sh-session +```sh npm install @discordjs/voice yarn add @discordjs/voice pnpm add @discordjs/voice @@ -61,26 +64,42 @@ try installing another. - [`FFmpeg`](https://ffmpeg.org/) (installed and added to environment) - `ffmpeg-static`: ^4.2.7 (npm install) +## Examples + +The [voice-examples][voice-examples] repository contains examples on how to use this package. Feel free to check them out if you need a nudge in the right direction. + ## Links -- [Website](https://discord.js.org/) ([source](https://github.com/discordjs/discord.js/tree/main/packages/website)) -- [Documentation](https://discord.js.org/#/docs/voice) -- [Guide](https://discordjs.guide/) ([source](https://github.com/discordjs/guide)) - See also the [Update Guide](https://discordjs.guide/additional-info/changes-in-v13.html), including updated and removed items in the library. -- [discord.js Discord server](https://discord.gg/djs) -- [Discord API Discord server](https://discord.gg/discord-api) -- [GitHub](https://github.com/discordjs/discord.js/tree/main/packages/voice) -- [npm](https://www.npmjs.com/package/@discordjs/voice) -- [Related libraries](https://discord.com/developers/docs/topics/community-resources#libraries) -- [Examples](https://github.com/discordjs/discord.js/tree/main/packages/voice/examples) +- [Website][website] ([source][website-source]) +- [Documentation][documentation] +- [Guide][guide] ([source][guide-source]) + Also see the v13 to v14 [Update Guide][guide-update], which includes updated and removed items from the library. +- [discord.js Discord server][discord] +- [Discord API Discord server][discord-api] +- [GitHub][source] +- [npm][npm] +- [Related libraries][related-libs] ## Contributing Before creating an issue, please ensure that it hasn't already been reported/suggested, and double-check the -[documentation](https://discord.js.org/#/docs/voice). -See [the contribution guide](https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md) if you'd like to submit a PR. +[documentation][documentation]. +See [the contribution guide][contributing] if you'd like to submit a PR. ## Help -If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle -nudge in the right direction, please don't hesitate to join our official [discord.js Server](https://discord.gg/djs). +If you don't understand something in the documentation, you are experiencing problems, or you just need a gentle nudge in the right direction, please don't hesitate to join our official [discord.js Server][discord]. + +[website]: https://discord.js.org +[website-source]: https://github.com/discordjs/discord.js/tree/main/apps/website +[documentation]: https://discord.js.org/docs/packages/voice/stable +[guide]: https://discordjs.guide/ +[guide-source]: https://github.com/discordjs/guide +[guide-update]: https://discordjs.guide/additional-info/changes-in-v14.html +[discord]: https://discord.gg/djs +[discord-api]: https://discord.gg/discord-api +[source]: https://github.com/discordjs/discord.js/tree/main/packages/voice +[npm]: https://www.npmjs.com/package/@discordjs/voice +[related-libs]: https://discord.com/developers/docs/topics/community-resources#libraries +[contributing]: https://github.com/discordjs/discord.js/blob/main/.github/CONTRIBUTING.md +[voice-examples]: https://github.com/discordjs/voice-examples diff --git a/node_modules/@discordjs/voice/dist/index.d.ts b/node_modules/@discordjs/voice/dist/index.d.ts index 35c818a..7b1cdbd 100644 --- a/node_modules/@discordjs/voice/dist/index.d.ts +++ b/node_modules/@discordjs/voice/dist/index.d.ts @@ -1,4 +1,5 @@ -import EventEmitter, { EventEmitter as EventEmitter$1 } from 'node:events'; +import { Buffer } from 'node:buffer'; +import { EventEmitter } from 'node:events'; import { Readable, ReadableOptions } from 'node:stream'; import prism from 'prism-media'; import WebSocket, { MessageEvent } from 'ws'; @@ -16,31 +17,31 @@ import { GatewayVoiceServerUpdateDispatchData, GatewayVoiceStateUpdateDispatchDa */ declare enum StreamType { Arbitrary = "arbitrary", - Raw = "raw", OggOpus = "ogg/opus", - WebmOpus = "webm/opus", - Opus = "opus" + Opus = "opus", + Raw = "raw", + WebmOpus = "webm/opus" } /** * The different types of transformers that can exist within the pipeline. */ declare enum TransformerType { - FFmpegPCM = "ffmpeg pcm", FFmpegOgg = "ffmpeg ogg", - OpusEncoder = "opus encoder", - OpusDecoder = "opus decoder", + FFmpegPCM = "ffmpeg pcm", + InlineVolume = "volume transformer", OggOpusDemuxer = "ogg/opus demuxer", - WebmOpusDemuxer = "webm/opus demuxer", - InlineVolume = "volume transformer" + OpusDecoder = "opus decoder", + OpusEncoder = "opus encoder", + WebmOpusDemuxer = "webm/opus demuxer" } /** * Represents a pathway from one stream type to another using a transformer. */ interface Edge { + cost: number; from: Node; to: Node; - cost: number; - transformer: (input: string | Readable) => Readable; + transformer(input: Readable | string): Readable; type: TransformerType; } /** @@ -67,9 +68,14 @@ declare class Node { /** * Options that are set when creating a new audio resource. * - * @template T - the type for the metadata (if any) of the audio resource + * @typeParam T - the type for the metadata (if any) of the audio resource */ interface CreateAudioResourceOptions { + /** + * Whether or not inline volume should be enabled. If enabled, you will be able to change the volume + * of the stream on-the-fly. However, this also increases the performance cost of playback. Defaults to `false`. + */ + inlineVolume?: boolean; /** * The type of the input stream. Defaults to `StreamType.Arbitrary`. */ @@ -80,11 +86,6 @@ interface CreateAudioResourceOptions { * See {@link AudioResource.metadata} */ metadata?: T; - /** - * Whether or not inline volume should be enabled. If enabled, you will be able to change the volume - * of the stream on-the-fly. However, this also increases the performance cost of playback. Defaults to `false`. - */ - inlineVolume?: boolean; /** * The number of silence frames to append to the end of the resource's audio stream, to prevent interpolation glitches. * Defaults to 5. @@ -94,7 +95,7 @@ interface CreateAudioResourceOptions { /** * Represents an audio resource that can be played by an audio player. * - * @template T - the type for the metadata (if any) of the audio resource + * @typeParam T - the type for the metadata (if any) of the audio resource */ declare class AudioResource { /** @@ -124,7 +125,7 @@ declare class AudioResource { /** * The audio player that the resource is subscribed to, if any. */ - audioPlayer?: AudioPlayer; + audioPlayer?: AudioPlayer | undefined; /** * The playback duration of this audio resource, given in milliseconds. */ @@ -159,7 +160,6 @@ declare class AudioResource { * It is advisable to check that the playStream is readable before calling this method. While no runtime * errors will be thrown, you should check that the resource is still available before attempting to * read from it. - * * @internal */ read(): Buffer | null; @@ -173,13 +173,11 @@ declare class AudioResource { * If the input is not in the correct format, then a pipeline of transcoders and transformers will be created * to ensure that the resultant stream is in the correct format for playback. This could involve using FFmpeg, * Opus transcoders, and Ogg/WebM demuxers. - * * @param input - The resource to play * @param options - Configurable options for creating the resource - * - * @template T - the type for the metadata (if any) of the audio resource + * @typeParam T - the type for the metadata (if any) of the audio resource */ -declare function createAudioResource(input: string | Readable, options: CreateAudioResourceOptions & Pick : Required>, 'metadata'>): AudioResource; +declare function createAudioResource(input: Readable | string, options: CreateAudioResourceOptions & Pick : Required>, 'metadata'>): AudioResource; /** * Creates an audio resource that can be played by audio players. * @@ -189,13 +187,11 @@ declare function createAudioResource(input: string | Readable, options: Creat * If the input is not in the correct format, then a pipeline of transcoders and transformers will be created * to ensure that the resultant stream is in the correct format for playback. This could involve using FFmpeg, * Opus transcoders, and Ogg/WebM demuxers. - * * @param input - The resource to play * @param options - Configurable options for creating the resource - * - * @template T - the type for the metadata (if any) of the audio resource + * @typeParam T - the type for the metadata (if any) of the audio resource */ -declare function createAudioResource(input: string | Readable, options?: Omit, 'metadata'>): AudioResource; +declare function createAudioResource(input: Readable | string, options?: Omit, 'metadata'>): AudioResource; /** * An error emitted by an AudioPlayer. Contains an attached resource to aid with @@ -250,13 +246,17 @@ declare enum NoSubscriberBehavior { } declare enum AudioPlayerStatus { /** - * When there is currently no resource for the player to be playing. + * When the player has paused itself. Only possible with the "pause" no subscriber behavior. */ - Idle = "idle", + AutoPaused = "autopaused", /** * When the player is waiting for an audio resource to become readable before transitioning to Playing. */ Buffering = "buffering", + /** + * When there is currently no resource for the player to be playing. + */ + Idle = "idle", /** * When the player has been manually paused. */ @@ -264,21 +264,17 @@ declare enum AudioPlayerStatus { /** * When the player is actively playing an audio resource. */ - Playing = "playing", - /** - * When the player has paused itself. Only possible with the "pause" no subscriber behavior. - */ - AutoPaused = "autopaused" + Playing = "playing" } /** * Options that can be passed when creating an audio player, used to specify its behavior. */ interface CreateAudioPlayerOptions { - debug?: boolean; behaviors?: { - noSubscriber?: NoSubscriberBehavior; maxMissedFrames?: number; + noSubscriber?: NoSubscriberBehavior; }; + debug?: boolean; } /** * The state that an AudioPlayer is in when it has no resource to play. This is the starting state. @@ -292,25 +288,25 @@ interface AudioPlayerIdleState { * it will re-enter the Idle state. */ interface AudioPlayerBufferingState { - status: AudioPlayerStatus.Buffering; + onFailureCallback: () => void; + onReadableCallback: () => void; + onStreamError: (error: Error) => void; /** * The resource that the AudioPlayer is waiting for */ resource: AudioResource; - onReadableCallback: () => void; - onFailureCallback: () => void; - onStreamError: (error: Error) => void; + status: AudioPlayerStatus.Buffering; } /** * The state that an AudioPlayer is in when it is actively playing an AudioResource. When playback ends, * it will enter the Idle state. */ interface AudioPlayerPlayingState { - status: AudioPlayerStatus.Playing; /** * The number of consecutive times that the audio resource has been unable to provide an Opus frame. */ missedFrames: number; + onStreamError: (error: Error) => void; /** * The playback duration in milliseconds of the current audio resource. This includes filler silence packets * that have been played when the resource was buffering. @@ -320,18 +316,14 @@ interface AudioPlayerPlayingState { * The resource that is being played. */ resource: AudioResource; - onStreamError: (error: Error) => void; + status: AudioPlayerStatus.Playing; } /** * The state that an AudioPlayer is in when it has either been explicitly paused by the user, or done * automatically by the AudioPlayer itself if there are no available subscribers. */ interface AudioPlayerPausedState { - status: AudioPlayerStatus.Paused | AudioPlayerStatus.AutoPaused; - /** - * How many silence packets still need to be played to avoid audio interpolation due to the stream suddenly pausing. - */ - silencePacketsRemaining: number; + onStreamError: (error: Error) => void; /** * The playback duration in milliseconds of the current audio resource. This includes filler silence packets * that have been played when the resource was buffering. @@ -341,36 +333,45 @@ interface AudioPlayerPausedState { * The current resource of the audio player. */ resource: AudioResource; - onStreamError: (error: Error) => void; + /** + * How many silence packets still need to be played to avoid audio interpolation due to the stream suddenly pausing. + */ + silencePacketsRemaining: number; + status: AudioPlayerStatus.AutoPaused | AudioPlayerStatus.Paused; } /** * The various states that the player can be in. */ -declare type AudioPlayerState = AudioPlayerIdleState | AudioPlayerBufferingState | AudioPlayerPlayingState | AudioPlayerPausedState; +type AudioPlayerState = AudioPlayerBufferingState | AudioPlayerIdleState | AudioPlayerPausedState | AudioPlayerPlayingState; interface AudioPlayer extends EventEmitter { /** * Emitted when there is an error emitted from the audio resource played by the audio player - * @event + * + * @eventProperty */ on(event: 'error', listener: (error: AudioPlayerError) => void): this; /** * Emitted debugging information about the audio player - * @event + * + * @eventProperty */ on(event: 'debug', listener: (message: string) => void): this; /** * Emitted when the state of the audio player changes - * @event + * + * @eventProperty */ on(event: 'stateChange', listener: (oldState: AudioPlayerState, newState: AudioPlayerState) => void): this; /** * Emitted when the audio player is subscribed to a voice connection - * @event + * + * @eventProperty */ on(event: 'subscribe' | 'unsubscribe', listener: (subscription: PlayerSubscription) => void): this; /** * Emitted when the status of state changes to a specific status - * @event + * + * @eventProperty */ on(event: T, listener: (oldState: AudioPlayerState, newState: AudioPlayerState & { status: T; @@ -418,9 +419,7 @@ declare class AudioPlayer extends EventEmitter { * * @remarks * This method should not be directly called. Instead, use VoiceConnection#subscribe. - * * @param connection - The connection to subscribe - * * @returns The new subscription if the voice connection is not yet subscribed, otherwise the existing subscription */ private subscribe; @@ -429,9 +428,7 @@ declare class AudioPlayer extends EventEmitter { * * @remarks * This method should not be directly called. Instead, use PlayerSubscription#unsubscribe. - * * @param subscription - The subscription to remove - * * @returns Whether or not the subscription existed on the player and was removed */ private unsubscribe; @@ -453,9 +450,7 @@ declare class AudioPlayer extends EventEmitter { * * If the player was previously playing a resource and this method is called, the player will not transition to the * Idle state during the swap over. - * * @param resource - The resource to play - * * @throws Will throw if attempting to play an audio resource that has already ended, or is being played by another player */ play(resource: AudioResource): void; @@ -463,7 +458,6 @@ declare class AudioPlayer extends EventEmitter { * Pauses playback of the current resource, if any. * * @param interpolateSilence - If true, the player will play 5 packets of silence after pausing to prevent audio glitches - * * @returns `true` if the player was successfully paused, otherwise `false` */ pause(interpolateSilence?: boolean): boolean; @@ -478,7 +472,6 @@ declare class AudioPlayer extends EventEmitter { * or remain in its current state until the silence padding frames of the resource have been played. * * @param force - If true, will force the player to enter the Idle state even if the resource has silence padding frames - * * @returns `true` if the player will come to a stop, otherwise `false` */ stop(force?: boolean): boolean; @@ -519,11 +512,11 @@ declare class AudioPlayer extends EventEmitter { declare function createAudioPlayer(options?: CreateAudioPlayerOptions): AudioPlayer; interface JoinConfig { - guildId: string; channelId: string | null; + group: string; + guildId: string; selfDeaf: boolean; selfMute: boolean; - group: string; } /** * Retrieves the map of group names to maps of voice connections. By default, all voice connections @@ -536,7 +529,6 @@ declare function getGroups(): Map>; * Retrieves all the voice connections under the 'default' group. * * @param group - The group to look up - * * @returns The map of voice connections */ declare function getVoiceConnections(group?: 'default'): Map; @@ -544,7 +536,6 @@ declare function getVoiceConnections(group?: 'default'): Map | undefined; @@ -553,7 +544,6 @@ declare function getVoiceConnections(group: string): Map void): this; on(event: 'close', listener: () => void): this; on(event: 'debug', listener: (message: string) => void): this; @@ -575,7 +565,7 @@ interface VoiceUDPSocket extends EventEmitter$1 { /** * Manages the UDP networking for a voice connection. */ -declare class VoiceUDPSocket extends EventEmitter$1 { +declare class VoiceUDPSocket extends EventEmitter { /** * The underlying network Socket for the VoiceUDPSocket. */ @@ -584,10 +574,6 @@ declare class VoiceUDPSocket extends EventEmitter$1 { * The socket details for Discord (remote) */ private readonly remote; - /** - * A list of keep alives that are waiting to be acknowledged. - */ - private readonly keepAlives; /** * The counter used in the keep alive mechanism. */ @@ -602,18 +588,16 @@ declare class VoiceUDPSocket extends EventEmitter$1 { private readonly keepAliveInterval; /** * The time taken to receive a response to keep alive messages. + * + * @deprecated This field is no longer updated as keep alive messages are no longer tracked. */ ping?: number; - /** - * The debug logger function, if debugging is enabled. - */ - private readonly debug; /** * Creates a new VoiceUDPSocket. * * @param remote - Details of the remote socket */ - constructor(remote: SocketConfig, debug?: boolean); + constructor(remote: SocketConfig); /** * Called when a message is received on the UDP socket. * @@ -642,20 +626,20 @@ declare class VoiceUDPSocket extends EventEmitter$1 { performIPDiscovery(ssrc: number): Promise; } -interface VoiceWebSocket extends EventEmitter$1 { +interface VoiceWebSocket extends EventEmitter { on(event: 'error', listener: (error: Error) => void): this; on(event: 'open', listener: (event: WebSocket.Event) => void): this; on(event: 'close', listener: (event: WebSocket.CloseEvent) => void): this; /** * Debug event for VoiceWebSocket. * - * @event + * @eventProperty */ on(event: 'debug', listener: (message: string) => void): this; /** * Packet event. * - * @event + * @eventProperty */ on(event: 'packet', listener: (packet: any) => void): this; } @@ -663,7 +647,7 @@ interface VoiceWebSocket extends EventEmitter$1 { * An extension of the WebSocket class to provide helper functionality when interacting * with the Discord Voice gateway. */ -declare class VoiceWebSocket extends EventEmitter$1 { +declare class VoiceWebSocket extends EventEmitter { /** * The current heartbeat interval, if any. */ @@ -749,16 +733,16 @@ declare enum NetworkingStatusCode { */ interface NetworkingOpeningWsState { code: NetworkingStatusCode.OpeningWs; - ws: VoiceWebSocket; connectionOptions: ConnectionOptions; + ws: VoiceWebSocket; } /** * The state that a Networking instance will be in when it is attempting to authorize itself. */ interface NetworkingIdentifyingState { code: NetworkingStatusCode.Identifying; - ws: VoiceWebSocket; connectionOptions: ConnectionOptions; + ws: VoiceWebSocket; } /** * The state that a Networking instance will be in when opening a UDP connection to the IP and port provided @@ -766,20 +750,20 @@ interface NetworkingIdentifyingState { */ interface NetworkingUdpHandshakingState { code: NetworkingStatusCode.UdpHandshaking; - ws: VoiceWebSocket; - udp: VoiceUDPSocket; - connectionOptions: ConnectionOptions; connectionData: Pick; + connectionOptions: ConnectionOptions; + udp: VoiceUDPSocket; + ws: VoiceWebSocket; } /** * The state that a Networking instance will be in when selecting an encryption protocol for audio packets. */ interface NetworkingSelectingProtocolState { code: NetworkingStatusCode.SelectingProtocol; - ws: VoiceWebSocket; - udp: VoiceUDPSocket; - connectionOptions: ConnectionOptions; connectionData: Pick; + connectionOptions: ConnectionOptions; + udp: VoiceUDPSocket; + ws: VoiceWebSocket; } /** * The state that a Networking instance will be in when it has a fully established connection to a Discord @@ -787,11 +771,11 @@ interface NetworkingSelectingProtocolState { */ interface NetworkingReadyState { code: NetworkingStatusCode.Ready; - ws: VoiceWebSocket; - udp: VoiceUDPSocket; - connectionOptions: ConnectionOptions; connectionData: ConnectionData; - preparedPacket?: Buffer; + connectionOptions: ConnectionOptions; + preparedPacket?: Buffer | undefined; + udp: VoiceUDPSocket; + ws: VoiceWebSocket; } /** * The state that a Networking instance will be in when its connection has been dropped unexpectedly, and it @@ -799,11 +783,11 @@ interface NetworkingReadyState { */ interface NetworkingResumingState { code: NetworkingStatusCode.Resuming; - ws: VoiceWebSocket; - udp: VoiceUDPSocket; - connectionOptions: ConnectionOptions; connectionData: ConnectionData; - preparedPacket?: Buffer; + connectionOptions: ConnectionOptions; + preparedPacket?: Buffer | undefined; + udp: VoiceUDPSocket; + ws: VoiceWebSocket; } /** * The state that a Networking instance will be in when it has been destroyed. It cannot be recovered from this @@ -815,39 +799,39 @@ interface NetworkingClosedState { /** * The various states that a networking instance can be in. */ -declare type NetworkingState = NetworkingOpeningWsState | NetworkingIdentifyingState | NetworkingUdpHandshakingState | NetworkingSelectingProtocolState | NetworkingReadyState | NetworkingResumingState | NetworkingClosedState; +type NetworkingState = NetworkingClosedState | NetworkingIdentifyingState | NetworkingOpeningWsState | NetworkingReadyState | NetworkingResumingState | NetworkingSelectingProtocolState | NetworkingUdpHandshakingState; /** * Details required to connect to the Discord voice gateway. These details * are first received on the main bot gateway, in the form of VOICE_SERVER_UPDATE * and VOICE_STATE_UPDATE packets. */ interface ConnectionOptions { + endpoint: string; serverId: string; - userId: string; sessionId: string; token: string; - endpoint: string; + userId: string; } /** * Information about the current connection, e.g. which encryption mode is to be used on * the connection, timing information for playback of streams. */ interface ConnectionData { - ssrc: number; encryptionMode: string; - secretKey: Uint8Array; - sequence: number; - timestamp: number; - packetsPlayed: number; nonce: number; nonceBuffer: Buffer; + packetsPlayed: number; + secretKey: Uint8Array; + sequence: number; speaking: boolean; + ssrc: number; + timestamp: number; } -interface Networking extends EventEmitter$1 { +interface Networking extends EventEmitter { /** * Debug event for Networking. * - * @event + * @eventProperty */ on(event: 'debug', listener: (message: string) => void): this; on(event: 'error', listener: (error: Error) => void): this; @@ -857,7 +841,7 @@ interface Networking extends EventEmitter$1 { /** * Manages the networking required to maintain a voice connection and dispatch audio packets */ -declare class Networking extends EventEmitter$1 { +declare class Networking extends EventEmitter { private _state; /** * The debug logger function, if debugging is enabled. @@ -883,7 +867,6 @@ declare class Networking extends EventEmitter$1 { * Creates a new WebSocket to a Discord Voice gateway. * * @param endpoint - The endpoint to connect to - * @param debug - Whether to enable debug logging */ private createWebSocket; /** @@ -934,9 +917,7 @@ declare class Networking extends EventEmitter$1 { * @remarks * Calling this method while there is already a prepared audio packet that has not yet been dispatched * will overwrite the existing audio packet. This should be avoided. - * * @param opusPacket - The Opus packet to encrypt - * * @returns The audio packet that was prepared */ prepareAudioPacket(opusPacket: Buffer): Buffer | undefined; @@ -992,11 +973,11 @@ declare enum EndBehaviorType { */ AfterInactivity = 2 } -declare type EndBehavior = { - behavior: EndBehaviorType.Manual; -} | { - behavior: EndBehaviorType.AfterSilence | EndBehaviorType.AfterInactivity; +type EndBehavior = { + behavior: EndBehaviorType.AfterInactivity | EndBehaviorType.AfterSilence; duration: number; +} | { + behavior: EndBehaviorType.Manual; }; interface AudioReceiveStreamOptions extends ReadableOptions { end: EndBehavior; @@ -1026,17 +1007,17 @@ interface VoiceUserData { * The SSRC of the user's audio stream. */ audioSSRC: number; + /** + * The Discord user id of the user. + */ + userId: string; /** * The SSRC of the user's video stream (if one exists) * Cannot be 0. If undefined, the user has no video stream. */ videoSSRC?: number; - /** - * The Discord user id of the user. - */ - userId: string; } -interface SSRCMap extends EventEmitter$1 { +interface SSRCMap extends EventEmitter { on(event: 'create', listener: (newData: VoiceUserData) => void): this; on(event: 'update', listener: (oldData: VoiceUserData | undefined, newData: VoiceUserData) => void): this; on(event: 'delete', listener: (deletedData: VoiceUserData) => void): this; @@ -1044,7 +1025,7 @@ interface SSRCMap extends EventEmitter$1 { /** * Maps audio SSRCs to data of users in voice connections. */ -declare class SSRCMap extends EventEmitter$1 { +declare class SSRCMap extends EventEmitter { /** * The underlying map. */ @@ -1066,28 +1047,29 @@ declare class SSRCMap extends EventEmitter$1 { * Deletes the stored voice data about a user. * * @param target - The target of the delete operation, either their audio SSRC or user id - * * @returns The data that was deleted, if any */ delete(target: number | string): VoiceUserData | undefined; } -interface SpeakingMap extends EventEmitter$1 { +interface SpeakingMap extends EventEmitter { /** * Emitted when a user starts speaking. - * @event + * + * @eventProperty */ on(event: 'start', listener: (userId: string) => void): this; /** * Emitted when a user ends speaking. - * @event + * + * @eventProperty */ on(event: 'end', listener: (userId: string) => void): this; } /** * Tracks the speaking states of users in a voice channel. */ -declare class SpeakingMap extends EventEmitter$1 { +declare class SpeakingMap extends EventEmitter { /** * The delay after a packet is received from a user until they're marked as not speaking anymore. */ @@ -1136,7 +1118,6 @@ declare class VoiceReceiver { * Called when a packet is received on the attached connection's WebSocket. * * @param packet - The received packet - * * @internal */ onWsPacket(packet: any): void; @@ -1148,7 +1129,6 @@ declare class VoiceReceiver { * @param mode - The encryption mode * @param nonce - The nonce buffer used by the connection for encryption * @param secretKey - The secret key used by the connection for encryption - * * @returns The parsed Opus packet */ private parsePacket; @@ -1156,7 +1136,6 @@ declare class VoiceReceiver { * Called when the UDP socket of the attached connection receives a message. * * @param msg - The received message - * * @internal */ onUdpMessage(msg: Buffer): void; @@ -1164,7 +1143,6 @@ declare class VoiceReceiver { * Creates a subscription for the given user id. * * @param target - The id of the user to subscribe to - * * @returns A readable stream of Opus packets received from the target */ subscribe(userId: string, options?: Partial): AudioReceiveStream; @@ -1175,40 +1153,39 @@ declare class VoiceReceiver { * Discord gateway DiscordGatewayAdapters. */ interface DiscordGatewayAdapterLibraryMethods { + /** + * Call this when the adapter can no longer be used (e.g. due to a disconnect from the main gateway) + */ + destroy(): void; /** * Call this when you receive a VOICE_SERVER_UPDATE payload that is relevant to the adapter. * * @param data - The inner data of the VOICE_SERVER_UPDATE payload */ - onVoiceServerUpdate: (data: GatewayVoiceServerUpdateDispatchData) => void; + onVoiceServerUpdate(data: GatewayVoiceServerUpdateDispatchData): void; /** * Call this when you receive a VOICE_STATE_UPDATE payload that is relevant to the adapter. * * @param data - The inner data of the VOICE_STATE_UPDATE payload */ - onVoiceStateUpdate: (data: GatewayVoiceStateUpdateDispatchData) => void; - /** - * Call this when the adapter can no longer be used (e.g. due to a disconnect from the main gateway) - */ - destroy: () => void; + onVoiceStateUpdate(data: GatewayVoiceStateUpdateDispatchData): void; } /** * Methods that are provided by the implementer of a Discord gateway DiscordGatewayAdapter. */ interface DiscordGatewayAdapterImplementerMethods { + /** + * This will be called by \@discordjs/voice when the adapter can safely be destroyed as it will no + * longer be used. + */ + destroy(): void; /** * Implement this method such that the given payload is sent to the main Discord gateway connection. * * @param payload - The payload to send to the main Discord gateway connection - * * @returns `false` if the payload definitely failed to send - in this case, the voice connection disconnects */ - sendPayload: (payload: any) => boolean; - /** - * This will be called by \@discordjs/voice when the adapter can safely be destroyed as it will no - * longer be used. - */ - destroy: () => void; + sendPayload(payload: any): boolean; } /** * A function used to build adapters. It accepts a methods parameter that contains functions that @@ -1216,41 +1193,41 @@ interface DiscordGatewayAdapterImplementerMethods { * the implementer will return some methods that the library can call - e.g. to send messages on * the gateway, or to signal that the adapter can be removed. */ -declare type DiscordGatewayAdapterCreator = (methods: DiscordGatewayAdapterLibraryMethods) => DiscordGatewayAdapterImplementerMethods; +type DiscordGatewayAdapterCreator = (methods: DiscordGatewayAdapterLibraryMethods) => DiscordGatewayAdapterImplementerMethods; /** * The various status codes a voice connection can hold at any one time. */ declare enum VoiceConnectionStatus { - /** - * Sending a packet to the main Discord gateway to indicate we want to change our voice state. - */ - Signalling = "signalling", /** * The `VOICE_SERVER_UPDATE` and `VOICE_STATE_UPDATE` packets have been received, now attempting to establish a voice connection. */ Connecting = "connecting", /** - * A voice connection has been established, and is ready to be used. + * The voice connection has been destroyed and untracked, it cannot be reused. */ - Ready = "ready", + Destroyed = "destroyed", /** * The voice connection has either been severed or not established. */ Disconnected = "disconnected", /** - * The voice connection has been destroyed and untracked, it cannot be reused. + * A voice connection has been established, and is ready to be used. */ - Destroyed = "destroyed" + Ready = "ready", + /** + * Sending a packet to the main Discord gateway to indicate we want to change our voice state. + */ + Signalling = "signalling" } /** * The state that a VoiceConnection will be in when it is waiting to receive a VOICE_SERVER_UPDATE and * VOICE_STATE_UPDATE packet from Discord, provided by the adapter. */ interface VoiceConnectionSignallingState { - status: VoiceConnectionStatus.Signalling; - subscription?: PlayerSubscription; adapter: DiscordGatewayAdapterImplementerMethods; + status: VoiceConnectionStatus.Signalling; + subscription?: PlayerSubscription | undefined; } /** * The reasons a voice connection can be in the disconnected state. @@ -1278,9 +1255,9 @@ declare enum VoiceConnectionDisconnectReason { * it attempting to connect. You can manually attempt to reconnect using VoiceConnection#reconnect. */ interface VoiceConnectionDisconnectedBaseState { - status: VoiceConnectionStatus.Disconnected; - subscription?: PlayerSubscription; adapter: DiscordGatewayAdapterImplementerMethods; + status: VoiceConnectionStatus.Disconnected; + subscription?: PlayerSubscription | undefined; } /** * The state that a VoiceConnection will be in when it is not connected to a Discord voice server nor is @@ -1294,36 +1271,36 @@ interface VoiceConnectionDisconnectedOtherState extends VoiceConnectionDisconnec * You can manually attempt to reconnect using VoiceConnection#reconnect. */ interface VoiceConnectionDisconnectedWebSocketState extends VoiceConnectionDisconnectedBaseState { - reason: VoiceConnectionDisconnectReason.WebSocketClose; /** * The close code of the WebSocket connection to the Discord voice server. */ closeCode: number; + reason: VoiceConnectionDisconnectReason.WebSocketClose; } /** * The states that a VoiceConnection can be in when it is not connected to a Discord voice server nor is * it attempting to connect. You can manually attempt to connect using VoiceConnection#reconnect. */ -declare type VoiceConnectionDisconnectedState = VoiceConnectionDisconnectedOtherState | VoiceConnectionDisconnectedWebSocketState; +type VoiceConnectionDisconnectedState = VoiceConnectionDisconnectedOtherState | VoiceConnectionDisconnectedWebSocketState; /** * The state that a VoiceConnection will be in when it is establishing a connection to a Discord * voice server. */ interface VoiceConnectionConnectingState { - status: VoiceConnectionStatus.Connecting; - networking: Networking; - subscription?: PlayerSubscription; adapter: DiscordGatewayAdapterImplementerMethods; + networking: Networking; + status: VoiceConnectionStatus.Connecting; + subscription?: PlayerSubscription | undefined; } /** * The state that a VoiceConnection will be in when it has an active connection to a Discord * voice server. */ interface VoiceConnectionReadyState { - status: VoiceConnectionStatus.Ready; - networking: Networking; - subscription?: PlayerSubscription; adapter: DiscordGatewayAdapterImplementerMethods; + networking: Networking; + status: VoiceConnectionStatus.Ready; + subscription?: PlayerSubscription | undefined; } /** * The state that a VoiceConnection will be in when it has been permanently been destroyed by the @@ -1336,26 +1313,30 @@ interface VoiceConnectionDestroyedState { /** * The various states that a voice connection can be in. */ -declare type VoiceConnectionState = VoiceConnectionSignallingState | VoiceConnectionDisconnectedState | VoiceConnectionConnectingState | VoiceConnectionReadyState | VoiceConnectionDestroyedState; -interface VoiceConnection extends EventEmitter$1 { +type VoiceConnectionState = VoiceConnectionConnectingState | VoiceConnectionDestroyedState | VoiceConnectionDisconnectedState | VoiceConnectionReadyState | VoiceConnectionSignallingState; +interface VoiceConnection extends EventEmitter { /** * Emitted when there is an error emitted from the voice connection - * @event + * + * @eventProperty */ on(event: 'error', listener: (error: Error) => void): this; /** * Emitted debugging information about the voice connection - * @event + * + * @eventProperty */ on(event: 'debug', listener: (message: string) => void): this; /** * Emitted when the state of the voice connection changes - * @event + * + * @eventProperty */ on(event: 'stateChange', listener: (oldState: VoiceConnectionState, newState: VoiceConnectionState) => void): this; /** * Emitted when the state of the voice connection changes to a specific status - * @event + * + * @eventProperty */ on(event: T, listener: (oldState: VoiceConnectionState, newState: VoiceConnectionState & { status: T; @@ -1364,7 +1345,7 @@ interface VoiceConnection extends EventEmitter$1 { /** * A connection to the voice server of a Guild, can be used to play audio in voice channels. */ -declare class VoiceConnection extends EventEmitter$1 { +declare class VoiceConnection extends EventEmitter { /** * The number of consecutive rejoin attempts. Initially 0, and increments for each rejoin. * When a connection is successfully established, it resets to 0. @@ -1400,7 +1381,7 @@ declare class VoiceConnection extends EventEmitter$1 { * @param joinConfig - The data required to establish the voice connection * @param options - The options used to create this voice connection */ - constructor(joinConfig: JoinConfig, { debug, adapterCreator }: CreateVoiceConnectionOptions); + constructor(joinConfig: JoinConfig, options: CreateVoiceConnectionOptions); /** * The current state of the voice connection. */ @@ -1426,6 +1407,7 @@ declare class VoiceConnection extends EventEmitter$1 { /** * Called when the networking state changes, and the new ws/udp packet/message handlers need to be rebound * to the new instances. + * * @param newState - The new networking state * @param oldState - The old networking state, if there is one */ @@ -1451,7 +1433,6 @@ declare class VoiceConnection extends EventEmitter$1 { * If the close code was anything other than 4014, it is likely that the closing was not intended, and so the * VoiceConnection will signal to Discord that it would like to rejoin the channel. This automatically attempts * to re-establish the connection. This would be seen as a transition from the Ready state to the Signalling state. - * * @param code - The close code */ private onNetworkingClose; @@ -1514,7 +1495,7 @@ declare class VoiceConnection extends EventEmitter$1 { * * A state transition from Disconnected to Signalling will be observed when this is called. */ - rejoin(joinConfig?: Omit): boolean; + rejoin(joinConfig?: Omit): boolean; /** * Updates the speaking status of the voice connection. This is used when audio players are done playing audio, * and need to signal that the connection is no longer playing audio. @@ -1526,7 +1507,6 @@ declare class VoiceConnection extends EventEmitter$1 { * Subscribes to an audio player, allowing the player to play audio on this voice connection. * * @param player - The audio player to subscribe to - * * @returns The created subscription */ subscribe(player: AudioPlayer): PlayerSubscription | undefined; @@ -1547,19 +1527,19 @@ declare class VoiceConnection extends EventEmitter$1 { * * @param subscription - The removed subscription */ - private onSubscriptionRemoved; + protected onSubscriptionRemoved(subscription: PlayerSubscription): void; } /** * The options that can be given when creating a voice connection. */ interface CreateVoiceConnectionOptions { + adapterCreator: DiscordGatewayAdapterCreator; /** * If true, debug messages will be enabled for the voice connection and its * related components. Defaults to false. */ - debug?: boolean; - adapterCreator: DiscordGatewayAdapterCreator; + debug?: boolean | undefined; } /** * The options that can be given when joining a voice channel. @@ -1569,6 +1549,10 @@ interface JoinVoiceChannelOptions { * The id of the Discord voice channel to join. */ channelId: string; + /** + * An optional group identifier for the voice connection. + */ + group?: string; /** * The id of the guild that the voice channel belongs to. */ @@ -1581,18 +1565,13 @@ interface JoinVoiceChannelOptions { * Whether to join the channel muted (defaults to true) */ selfMute?: boolean; - /** - * An optional group identifier for the voice connection. - */ - group?: string; } /** * Creates a VoiceConnection to a Discord voice channel. * - * @param voiceChannel - the voice channel to connect to * @param options - the options for joining the voice channel */ -declare function joinVoiceChannel(options: JoinVoiceChannelOptions & CreateVoiceConnectionOptions): VoiceConnection; +declare function joinVoiceChannel(options: CreateVoiceConnectionOptions & JoinVoiceChannelOptions): VoiceConnection; /** * Generates a report of the dependencies used by the \@discordjs/voice module. @@ -1607,7 +1586,7 @@ declare function generateDependencyReport(): string; * @param status - The status that the voice connection should be in * @param timeoutOrSignal - The maximum time we are allowing for this to occur, or a signal that will abort the operation */ -declare function entersState(target: VoiceConnection, status: VoiceConnectionStatus, timeoutOrSignal: number | AbortSignal): Promise; +declare function entersState(target: VoiceConnection, status: VoiceConnectionStatus, timeoutOrSignal: AbortSignal | number): Promise; /** * Allows an audio player a specified amount of time to enter a given state, otherwise rejects with an error. * @@ -1615,13 +1594,12 @@ declare function entersState(target: VoiceConnection, status: VoiceConnectionSta * @param status - The status that the audio player should be in * @param timeoutOrSignal - The maximum time we are allowing for this to occur, or a signal that will abort the operation */ -declare function entersState(target: AudioPlayer, status: AudioPlayerStatus, timeoutOrSignal: number | AbortSignal): Promise; +declare function entersState(target: AudioPlayer, status: AudioPlayerStatus, timeoutOrSignal: AbortSignal | number): Promise; /** * Takes an Opus Head, and verifies whether the associated Opus audio is suitable to play in a Discord voice channel. * * @param opusHead - The Opus Head to validate - * * @returns `true` if suitable to play in a Discord voice channel, otherwise `false` */ declare function validateDiscordOpusHead(opusHead: Buffer): boolean; @@ -1645,9 +1623,14 @@ interface ProbeInfo { * @param stream - The readable stream to probe * @param probeSize - The number of bytes to attempt to read before giving up on the probe * @param validator - The Opus Head validator function - * * @experimental */ declare function demuxProbe(stream: Readable, probeSize?: number, validator?: typeof validateDiscordOpusHead): Promise; -export { AudioPlayer, AudioPlayerBufferingState, AudioPlayerError, AudioPlayerIdleState, AudioPlayerPausedState, AudioPlayerPlayingState, AudioPlayerState, AudioPlayerStatus, AudioReceiveStream, AudioReceiveStreamOptions, AudioResource, CreateAudioPlayerOptions, CreateAudioResourceOptions, CreateVoiceConnectionOptions, DiscordGatewayAdapterCreator, DiscordGatewayAdapterImplementerMethods, DiscordGatewayAdapterLibraryMethods, EndBehavior, EndBehaviorType, JoinConfig, JoinVoiceChannelOptions, NoSubscriberBehavior, PlayerSubscription, ProbeInfo, SSRCMap, SpeakingMap, StreamType, VoiceConnection, VoiceConnectionConnectingState, VoiceConnectionDestroyedState, VoiceConnectionDisconnectReason, VoiceConnectionDisconnectedBaseState, VoiceConnectionDisconnectedOtherState, VoiceConnectionDisconnectedState, VoiceConnectionDisconnectedWebSocketState, VoiceConnectionReadyState, VoiceConnectionSignallingState, VoiceConnectionState, VoiceConnectionStatus, VoiceReceiver, VoiceUserData, createAudioPlayer, createAudioResource, createDefaultAudioReceiveStreamOptions, demuxProbe, entersState, generateDependencyReport, getGroups, getVoiceConnection, getVoiceConnections, joinVoiceChannel, validateDiscordOpusHead }; +/** + * The {@link https://github.com/discordjs/discord.js/blob/main/packages/voice/#readme | @discordjs/voice} version + * that you are currently using. + */ +declare const version: string; + +export { AudioPlayer, AudioPlayerBufferingState, AudioPlayerError, AudioPlayerIdleState, AudioPlayerPausedState, AudioPlayerPlayingState, AudioPlayerState, AudioPlayerStatus, AudioReceiveStream, AudioReceiveStreamOptions, AudioResource, CreateAudioPlayerOptions, CreateAudioResourceOptions, CreateVoiceConnectionOptions, DiscordGatewayAdapterCreator, DiscordGatewayAdapterImplementerMethods, DiscordGatewayAdapterLibraryMethods, EndBehavior, EndBehaviorType, JoinConfig, JoinVoiceChannelOptions, NoSubscriberBehavior, PlayerSubscription, ProbeInfo, SSRCMap, SpeakingMap, StreamType, VoiceConnection, VoiceConnectionConnectingState, VoiceConnectionDestroyedState, VoiceConnectionDisconnectReason, VoiceConnectionDisconnectedBaseState, VoiceConnectionDisconnectedOtherState, VoiceConnectionDisconnectedState, VoiceConnectionDisconnectedWebSocketState, VoiceConnectionReadyState, VoiceConnectionSignallingState, VoiceConnectionState, VoiceConnectionStatus, VoiceReceiver, VoiceUserData, createAudioPlayer, createAudioResource, createDefaultAudioReceiveStreamOptions, demuxProbe, entersState, generateDependencyReport, getGroups, getVoiceConnection, getVoiceConnections, joinVoiceChannel, validateDiscordOpusHead, version }; diff --git a/node_modules/@discordjs/voice/dist/index.js b/node_modules/@discordjs/voice/dist/index.js index 2f2e420..6274205 100644 --- a/node_modules/@discordjs/voice/dist/index.js +++ b/node_modules/@discordjs/voice/dist/index.js @@ -1,5 +1,4 @@ "use strict"; -"use strict"; var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; @@ -8,9 +7,6 @@ var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); -var __commonJS = (cb, mod) => function __require() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); @@ -23,104 +19,20 @@ var __copyProps = (to, from, except, desc) => { } return to; }; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, mod)); +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; -// package.json -var require_package = __commonJS({ - "package.json"(exports, module2) { - module2.exports = { - name: "@discordjs/voice", - version: "0.11.0", - description: "Implementation of the Discord Voice API for node.js", - scripts: { - build: "tsup && node scripts/postbuild.mjs", - test: "jest --coverage", - lint: "prettier --check . && eslint src __tests__ --ext mjs,js,ts", - format: "prettier --write . && eslint src __tests__ --ext mjs,js,ts --fix", - docs: "docgen -i src/index.ts -c docs/index.json -o docs/docs.json --typescript && api-extractor run --local", - prepack: "yarn build && yarn lint && yarn test", - changelog: "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/voice/*'", - release: "cliff-jumper" - }, - main: "./dist/index.js", - module: "./dist/index.mjs", - typings: "./dist/index.d.ts", - exports: { - import: "./dist/index.mjs", - require: "./dist/index.js", - types: "./dist/index.d.ts" - }, - directories: { - lib: "src", - test: "__tests__" - }, - files: [ - "dist" - ], - contributors: [ - "Crawl ", - "Amish Shah ", - "SpaceEEC ", - "Vlad Frangu ", - "Antonio Roman " - ], - license: "Apache-2.0", - keywords: [ - "discord", - "discord.js", - "audio", - "voice", - "streaming" - ], - repository: { - type: "git", - url: "git+https://github.com/discordjs/discord.js.git" - }, - bugs: { - url: "https://github.com/discordjs/discord.js/issues" - }, - homepage: "https://discord.js.org", - dependencies: { - "@types/ws": "^8.5.3", - "discord-api-types": "^0.36.2", - "prism-media": "^1.3.4", - tslib: "^2.4.0", - ws: "^8.8.1" - }, - devDependencies: { - "@babel/core": "^7.18.6", - "@babel/preset-env": "^7.18.6", - "@babel/preset-typescript": "^7.18.6", - "@discordjs/docgen": "workspace:^", - "@discordjs/scripts": "workspace:^", - "@favware/cliff-jumper": "^1.8.5", - "@microsoft/api-extractor": "^7.28.4", - "@types/jest": "^28.1.6", - "@types/node": "^16.11.45", - eslint: "^8.20.0", - jest: "^28.1.3", - "jest-websocket-mock": "^2.3.0", - "mock-socket": "^9.1.5", - prettier: "^2.7.1", - tsup: "^6.1.3", - tweetnacl: "^1.0.3", - typescript: "^4.7.4" - }, - engines: { - node: ">=16.9.0" - }, - publishConfig: { - access: "public" - } - }; - } -}); - // src/index.ts var src_exports = {}; __export(src_exports, { @@ -135,7 +47,7 @@ __export(src_exports, { SSRCMap: () => SSRCMap, SpeakingMap: () => SpeakingMap, StreamType: () => StreamType, - VoiceConnection: () => VoiceConnection2, + VoiceConnection: () => VoiceConnection, VoiceConnectionDisconnectReason: () => VoiceConnectionDisconnectReason, VoiceConnectionStatus: () => VoiceConnectionStatus, VoiceReceiver: () => VoiceReceiver, @@ -149,7 +61,8 @@ __export(src_exports, { getVoiceConnection: () => getVoiceConnection, getVoiceConnections: () => getVoiceConnections, joinVoiceChannel: () => joinVoiceChannel, - validateDiscordOpusHead: () => validateDiscordOpusHead + validateDiscordOpusHead: () => validateDiscordOpusHead, + version: () => version2 }); module.exports = __toCommonJS(src_exports); @@ -161,6 +74,7 @@ var import_v10 = require("discord-api-types/v10"); function createJoinVoiceChannelPayload(config) { return { op: import_v10.GatewayOpcodes.VoiceStateUpdate, + // eslint-disable-next-line id-length d: { guild_id: config.guildId, channel_id: config.channelId, @@ -210,7 +124,9 @@ function audioCycleStep() { return; nextTime += FRAME_LENGTH; const available = audioPlayers.filter((player) => player.checkPlayable()); - available.forEach((player) => player["_stepDispatch"]()); + for (const player of available) { + player["_stepDispatch"](); + } prepareNextAudioFrame(available); } __name(audioCycleStep, "audioCycleStep"); @@ -248,23 +164,96 @@ function deleteAudioPlayer(player) { audioPlayers.splice(index, 1); if (audioPlayers.length === 0) { nextTime = -1; - if (typeof audioCycleInterval !== "undefined") + if (audioCycleInterval !== void 0) clearTimeout(audioCycleInterval); } } __name(deleteAudioPlayer, "deleteAudioPlayer"); // src/networking/Networking.ts +var import_node_buffer3 = require("buffer"); var import_node_events3 = require("events"); var import_v42 = require("discord-api-types/voice/v4"); +// src/util/Secretbox.ts +var import_node_buffer = require("buffer"); +var libs = { + "sodium-native": (sodium) => ({ + open: (buffer, nonce2, secretKey) => { + if (buffer) { + const output = import_node_buffer.Buffer.allocUnsafe(buffer.length - sodium.crypto_box_MACBYTES); + if (sodium.crypto_secretbox_open_easy(output, buffer, nonce2, secretKey)) + return output; + } + return null; + }, + close: (opusPacket, nonce2, secretKey) => { + const output = import_node_buffer.Buffer.allocUnsafe(opusPacket.length + sodium.crypto_box_MACBYTES); + sodium.crypto_secretbox_easy(output, opusPacket, nonce2, secretKey); + return output; + }, + random: (num, buffer = import_node_buffer.Buffer.allocUnsafe(num)) => { + sodium.randombytes_buf(buffer); + return buffer; + } + }), + sodium: (sodium) => ({ + open: sodium.api.crypto_secretbox_open_easy, + close: sodium.api.crypto_secretbox_easy, + random: (num, buffer = import_node_buffer.Buffer.allocUnsafe(num)) => { + sodium.api.randombytes_buf(buffer); + return buffer; + } + }), + "libsodium-wrappers": (sodium) => ({ + open: sodium.crypto_secretbox_open_easy, + close: sodium.crypto_secretbox_easy, + random: sodium.randombytes_buf + }), + tweetnacl: (tweetnacl) => ({ + open: tweetnacl.secretbox.open, + close: tweetnacl.secretbox, + random: tweetnacl.randomBytes + }) +}; +var fallbackError = /* @__PURE__ */ __name(() => { + throw new Error( + `Cannot play audio as no valid encryption package is installed. +- Install sodium, libsodium-wrappers, or tweetnacl. +- Use the generateDependencyReport() function for more information. +` + ); +}, "fallbackError"); +var methods = { + open: fallbackError, + close: fallbackError, + random: fallbackError +}; +void (async () => { + for (const libName of Object.keys(libs)) { + try { + const lib = require(libName); + if (libName === "libsodium-wrappers" && lib.ready) + await lib.ready; + Object.assign(methods, libs[libName](lib)); + break; + } catch { + } + } +})(); + +// src/util/util.ts +var noop = /* @__PURE__ */ __name(() => { +}, "noop"); + // src/networking/VoiceUDPSocket.ts +var import_node_buffer2 = require("buffer"); var import_node_dgram = require("dgram"); var import_node_events = require("events"); var import_node_net = require("net"); function parseLocalPacket(message) { - const packet = Buffer.from(message); - const ip = packet.slice(8, packet.indexOf(0, 8)).toString("utf-8"); + const packet = import_node_buffer2.Buffer.from(message); + const ip = packet.slice(8, packet.indexOf(0, 8)).toString("utf8"); if (!(0, import_node_net.isIPv4)(ip)) { throw new Error("Malformed IP address"); } @@ -273,61 +262,80 @@ function parseLocalPacket(message) { } __name(parseLocalPacket, "parseLocalPacket"); var KEEP_ALIVE_INTERVAL = 5e3; -var KEEP_ALIVE_LIMIT = 12; var MAX_COUNTER_VALUE = 2 ** 32 - 1; var VoiceUDPSocket = class extends import_node_events.EventEmitter { - constructor(remote, debug = false) { + /** + * The underlying network Socket for the VoiceUDPSocket. + */ + socket; + /** + * The socket details for Discord (remote) + */ + remote; + /** + * The counter used in the keep alive mechanism. + */ + keepAliveCounter = 0; + /** + * The buffer used to write the keep alive counter into. + */ + keepAliveBuffer; + /** + * The Node.js interval for the keep-alive mechanism. + */ + keepAliveInterval; + /** + * The time taken to receive a response to keep alive messages. + * + * @deprecated This field is no longer updated as keep alive messages are no longer tracked. + */ + ping; + /** + * Creates a new VoiceUDPSocket. + * + * @param remote - Details of the remote socket + */ + constructor(remote) { super(); - __publicField(this, "socket"); - __publicField(this, "remote"); - __publicField(this, "keepAlives"); - __publicField(this, "keepAliveCounter", 0); - __publicField(this, "keepAliveBuffer"); - __publicField(this, "keepAliveInterval"); - __publicField(this, "ping"); - __publicField(this, "debug"); this.socket = (0, import_node_dgram.createSocket)("udp4"); this.socket.on("error", (error) => this.emit("error", error)); this.socket.on("message", (buffer) => this.onMessage(buffer)); this.socket.on("close", () => this.emit("close")); this.remote = remote; - this.keepAlives = []; - this.keepAliveBuffer = Buffer.alloc(8); + this.keepAliveBuffer = import_node_buffer2.Buffer.alloc(8); this.keepAliveInterval = setInterval(() => this.keepAlive(), KEEP_ALIVE_INTERVAL); setImmediate(() => this.keepAlive()); - this.debug = debug ? (message) => this.emit("debug", message) : null; } + /** + * Called when a message is received on the UDP socket. + * + * @param buffer - The received buffer + */ onMessage(buffer) { - if (buffer.length === 8) { - const counter = buffer.readUInt32LE(0); - const index = this.keepAlives.findIndex(({ value }) => value === counter); - if (index === -1) - return; - this.ping = Date.now() - this.keepAlives[index].timestamp; - this.keepAlives.splice(0, index); - } this.emit("message", buffer); } + /** + * Called at a regular interval to check whether we are still able to send datagrams to Discord. + */ keepAlive() { - if (this.keepAlives.length >= KEEP_ALIVE_LIMIT) { - this.debug?.("UDP socket has not received enough responses from Discord - closing socket"); - this.destroy(); - return; - } this.keepAliveBuffer.writeUInt32LE(this.keepAliveCounter, 0); this.send(this.keepAliveBuffer); - this.keepAlives.push({ - value: this.keepAliveCounter, - timestamp: Date.now() - }); this.keepAliveCounter++; if (this.keepAliveCounter > MAX_COUNTER_VALUE) { this.keepAliveCounter = 0; } } + /** + * Sends a buffer to Discord. + * + * @param buffer - The buffer to send + */ send(buffer) { - return this.socket.send(buffer, this.remote.port, this.remote.ip); + this.socket.send(buffer, this.remote.port, this.remote.ip); } + /** + * Closes the socket, the instance will not be able to be reused. + */ destroy() { try { this.socket.close(); @@ -335,7 +343,12 @@ var VoiceUDPSocket = class extends import_node_events.EventEmitter { } clearInterval(this.keepAliveInterval); } - performIPDiscovery(ssrc) { + /** + * Performs IP discovery to discover the local address and port to be used for the voice connection. + * + * @param ssrc - The SSRC received from Discord + */ + async performIPDiscovery(ssrc) { return new Promise((resolve2, reject) => { const listener = /* @__PURE__ */ __name((message) => { try { @@ -349,7 +362,7 @@ var VoiceUDPSocket = class extends import_node_events.EventEmitter { }, "listener"); this.socket.on("message", listener); this.socket.once("close", () => reject(new Error("Cannot perform IP discovery - socket closed"))); - const discoveryBuffer = Buffer.alloc(74); + const discoveryBuffer = import_node_buffer2.Buffer.alloc(74); discoveryBuffer.writeUInt16BE(1, 0); discoveryBuffer.writeUInt16BE(70, 2); discoveryBuffer.writeUInt32BE(ssrc, 4); @@ -364,34 +377,71 @@ var import_node_events2 = require("events"); var import_v4 = require("discord-api-types/voice/v4"); var import_ws = __toESM(require("ws")); var VoiceWebSocket = class extends import_node_events2.EventEmitter { + /** + * The current heartbeat interval, if any. + */ + heartbeatInterval; + /** + * The time (milliseconds since UNIX epoch) that the last heartbeat acknowledgement packet was received. + * This is set to 0 if an acknowledgement packet hasn't been received yet. + */ + lastHeartbeatAck; + /** + * The time (milliseconds since UNIX epoch) that the last heartbeat was sent. This is set to 0 if a heartbeat + * hasn't been sent yet. + */ + lastHeartbeatSend; + /** + * The number of consecutively missed heartbeats. + */ + missedHeartbeats = 0; + /** + * The last recorded ping. + */ + ping; + /** + * The debug logger function, if debugging is enabled. + */ + debug; + /** + * The underlying WebSocket of this wrapper. + */ + ws; + /** + * Creates a new VoiceWebSocket. + * + * @param address - The address to connect to + */ constructor(address, debug) { super(); - __publicField(this, "heartbeatInterval"); - __publicField(this, "lastHeartbeatAck"); - __publicField(this, "lastHeartbeatSend"); - __publicField(this, "missedHeartbeats", 0); - __publicField(this, "ping"); - __publicField(this, "debug"); - __publicField(this, "ws"); this.ws = new import_ws.default(address); - this.ws.onmessage = (e) => this.onMessage(e); - this.ws.onopen = (e) => this.emit("open", e); - this.ws.onerror = (e) => this.emit("error", e instanceof Error ? e : e.error); - this.ws.onclose = (e) => this.emit("close", e); + this.ws.onmessage = (err) => this.onMessage(err); + this.ws.onopen = (err) => this.emit("open", err); + this.ws.onerror = (err) => this.emit("error", err instanceof Error ? err : err.error); + this.ws.onclose = (err) => this.emit("close", err); this.lastHeartbeatAck = 0; this.lastHeartbeatSend = 0; this.debug = debug ? (message) => this.emit("debug", message) : null; } + /** + * Destroys the VoiceWebSocket. The heartbeat interval is cleared, and the connection is closed. + */ destroy() { try { this.debug?.("destroyed"); this.setHeartbeatInterval(-1); this.ws.close(1e3); } catch (error) { - const e = error; - this.emit("error", e); + const err = error; + this.emit("error", err); } } + /** + * Handles message events on the WebSocket. Attempts to JSON parse the messages and emit them + * as packets. + * + * @param event - The message event + */ onMessage(event) { if (typeof event.data !== "string") return; @@ -400,8 +450,8 @@ var VoiceWebSocket = class extends import_node_events2.EventEmitter { try { packet = JSON.parse(event.data); } catch (error) { - const e = error; - this.emit("error", e); + const err = error; + this.emit("error", err); return; } if (packet.op === import_v4.VoiceOpcodes.HeartbeatAck) { @@ -411,27 +461,42 @@ var VoiceWebSocket = class extends import_node_events2.EventEmitter { } this.emit("packet", packet); } + /** + * Sends a JSON-stringifiable packet over the WebSocket. + * + * @param packet - The packet to send + */ sendPacket(packet) { try { const stringified = JSON.stringify(packet); this.debug?.(`>> ${stringified}`); - return this.ws.send(stringified); + this.ws.send(stringified); + return; } catch (error) { - const e = error; - this.emit("error", e); + const err = error; + this.emit("error", err); } } + /** + * Sends a heartbeat over the WebSocket. + */ sendHeartbeat() { this.lastHeartbeatSend = Date.now(); this.missedHeartbeats++; const nonce2 = this.lastHeartbeatSend; - return this.sendPacket({ + this.sendPacket({ op: import_v4.VoiceOpcodes.Heartbeat, + // eslint-disable-next-line id-length d: nonce2 }); } + /** + * Sets/clears an interval to send heartbeats over the WebSocket. + * + * @param ms - The interval in milliseconds. If negative, the interval will be unset + */ setHeartbeatInterval(ms) { - if (typeof this.heartbeatInterval !== "undefined") + if (this.heartbeatInterval !== void 0) clearInterval(this.heartbeatInterval); if (ms > 0) { this.heartbeatInterval = setInterval(() => { @@ -446,80 +511,12 @@ var VoiceWebSocket = class extends import_node_events2.EventEmitter { }; __name(VoiceWebSocket, "VoiceWebSocket"); -// src/util/Secretbox.ts -var libs = { - "sodium-native": (sodium) => ({ - open: (buffer, nonce2, secretKey) => { - if (buffer) { - const output = Buffer.allocUnsafe(buffer.length - sodium.crypto_box_MACBYTES); - if (sodium.crypto_secretbox_open_easy(output, buffer, nonce2, secretKey)) - return output; - } - return null; - }, - close: (opusPacket, nonce2, secretKey) => { - const output = Buffer.allocUnsafe(opusPacket.length + sodium.crypto_box_MACBYTES); - sodium.crypto_secretbox_easy(output, opusPacket, nonce2, secretKey); - return output; - }, - random: (n, buffer = Buffer.allocUnsafe(n)) => { - sodium.randombytes_buf(buffer); - return buffer; - } - }), - sodium: (sodium) => ({ - open: sodium.api.crypto_secretbox_open_easy, - close: sodium.api.crypto_secretbox_easy, - random: (n, buffer = Buffer.allocUnsafe(n)) => { - sodium.api.randombytes_buf(buffer); - return buffer; - } - }), - "libsodium-wrappers": (sodium) => ({ - open: sodium.crypto_secretbox_open_easy, - close: sodium.crypto_secretbox_easy, - random: sodium.randombytes_buf - }), - tweetnacl: (tweetnacl) => ({ - open: tweetnacl.secretbox.open, - close: tweetnacl.secretbox, - random: tweetnacl.randomBytes - }) -}; -var fallbackError = /* @__PURE__ */ __name(() => { - throw new Error(`Cannot play audio as no valid encryption package is installed. -- Install sodium, libsodium-wrappers, or tweetnacl. -- Use the generateDependencyReport() function for more information. -`); -}, "fallbackError"); -var methods = { - open: fallbackError, - close: fallbackError, - random: fallbackError -}; -void (async () => { - for (const libName of Object.keys(libs)) { - try { - const lib = require(libName); - if (libName === "libsodium-wrappers" && lib.ready) - await lib.ready; - Object.assign(methods, libs[libName](lib)); - break; - } catch { - } - } -})(); - -// src/util/util.ts -var noop = /* @__PURE__ */ __name(() => { -}, "noop"); - // src/networking/Networking.ts var CHANNELS = 2; var TIMESTAMP_INC = 48e3 / 100 * CHANNELS; var MAX_NONCE_SIZE = 2 ** 32 - 1; var SUPPORTED_ENCRYPTION_MODES = ["xsalsa20_poly1305_lite", "xsalsa20_poly1305_suffix", "xsalsa20_poly1305"]; -var nonce = Buffer.alloc(24); +var nonce = import_node_buffer3.Buffer.alloc(24); function stringifyState(state) { return JSON.stringify({ ...state, @@ -536,15 +533,21 @@ function chooseEncryptionMode(options) { return option; } __name(chooseEncryptionMode, "chooseEncryptionMode"); -function randomNBit(n) { - return Math.floor(Math.random() * 2 ** n); +function randomNBit(numberOfBits) { + return Math.floor(Math.random() * 2 ** numberOfBits); } __name(randomNBit, "randomNBit"); var Networking = class extends import_node_events3.EventEmitter { + _state; + /** + * The debug logger function, if debugging is enabled. + */ + debug; + /** + * Creates a new Networking instance. + */ constructor(options, debug) { super(); - __publicField(this, "_state"); - __publicField(this, "debug"); this.onWsOpen = this.onWsOpen.bind(this); this.onChildError = this.onChildError.bind(this); this.onWsPacket = this.onWsPacket.bind(this); @@ -559,14 +562,23 @@ var Networking = class extends import_node_events3.EventEmitter { connectionOptions: options }; } + /** + * Destroys the Networking instance, transitioning it into the Closed state. + */ destroy() { this.state = { code: 6 /* Closed */ }; } + /** + * The current state of the networking instance. + */ get state() { return this._state; } + /** + * Sets a new state for the networking instance, performing clean-up operations where necessary. + */ set state(newState) { const oldWs = Reflect.get(this._state, "ws"); const newWs = Reflect.get(newState, "ws"); @@ -595,6 +607,11 @@ var Networking = class extends import_node_events3.EventEmitter { from ${stringifyState(oldState)} to ${stringifyState(newState)}`); } + /** + * Creates a new WebSocket to a Discord Voice gateway. + * + * @param endpoint - The endpoint to connect to + */ createWebSocket(endpoint) { const ws = new VoiceWebSocket(`wss://${endpoint}?v=4`, Boolean(this.debug)); ws.on("error", this.onChildError); @@ -604,9 +621,18 @@ to ${stringifyState(newState)}`); ws.on("debug", this.onWsDebug); return ws; } + /** + * Propagates errors from the children VoiceWebSocket and VoiceUDPSocket. + * + * @param error - The error that was emitted by a child + */ onChildError(error) { this.emit("error", error); } + /** + * Called when the WebSocket opens. Depending on the state that the instance is in, + * it will either identify with a new session, or it will attempt to resume an existing session. + */ onWsOpen() { if (this.state.code === 0 /* OpeningWs */) { const packet = { @@ -635,6 +661,13 @@ to ${stringifyState(newState)}`); this.state.ws.sendPacket(packet); } } + /** + * Called when the WebSocket closes. Based on the reason for closing (given by the code parameter), + * the instance will either attempt to resume, or enter the closed state and emit a 'close' event + * with the close code, allowing the user to decide whether or not they would like to reconnect. + * + * @param code - The close code + */ onWsClose({ code }) { const canResume = code === 4015 || code < 4e3; if (canResume && this.state.code === 4 /* Ready */) { @@ -648,6 +681,9 @@ to ${stringifyState(newState)}`); this.emit("close", code); } } + /** + * Called when the UDP socket has closed itself if it has stopped receiving replies from Discord. + */ onUdpClose() { if (this.state.code === 4 /* Ready */) { this.state = { @@ -657,6 +693,11 @@ to ${stringifyState(newState)}`); }; } } + /** + * Called when a packet is received on the connection's WebSocket. + * + * @param packet - The received packet + */ onWsPacket(packet) { if (packet.op === import_v42.VoiceOpcodes.Hello && this.state.code !== 6 /* Closed */) { this.state.ws.setHeartbeatInterval(packet.d.heartbeat_interval); @@ -705,7 +746,7 @@ to ${stringifyState(newState)}`); sequence: randomNBit(16), timestamp: randomNBit(32), nonce: 0, - nonceBuffer: Buffer.alloc(24), + nonceBuffer: import_node_buffer3.Buffer.alloc(24), speaking: false, packetsPlayed: 0 } @@ -718,12 +759,32 @@ to ${stringifyState(newState)}`); this.state.connectionData.speaking = false; } } + /** + * Propagates debug messages from the child WebSocket. + * + * @param message - The emitted debug message + */ onWsDebug(message) { this.debug?.(`[WS] ${message}`); } + /** + * Propagates debug messages from the child UDPSocket. + * + * @param message - The emitted debug message + */ onUdpDebug(message) { this.debug?.(`[UDP] ${message}`); } + /** + * Prepares an Opus packet for playback. This includes attaching metadata to it and encrypting it. + * It will be stored within the instance, and can be played by dispatchAudio() + * + * @remarks + * Calling this method while there is already a prepared audio packet that has not yet been dispatched + * will overwrite the existing audio packet. This should be avoided. + * @param opusPacket - The Opus packet to encrypt + * @returns The audio packet that was prepared + */ prepareAudioPacket(opusPacket) { const state = this.state; if (state.code !== 4 /* Ready */) @@ -731,17 +792,26 @@ to ${stringifyState(newState)}`); state.preparedPacket = this.createAudioPacket(opusPacket, state.connectionData); return state.preparedPacket; } + /** + * Dispatches the audio packet previously prepared by prepareAudioPacket(opusPacket). The audio packet + * is consumed and cannot be dispatched again. + */ dispatchAudio() { const state = this.state; if (state.code !== 4 /* Ready */) return false; - if (typeof state.preparedPacket !== "undefined") { + if (state.preparedPacket !== void 0) { this.playAudioPacket(state.preparedPacket); state.preparedPacket = void 0; return true; } return false; } + /** + * Plays an audio packet, updating timing metadata used for playback. + * + * @param audioPacket - The audio packet to play + */ playAudioPacket(audioPacket) { const state = this.state; if (state.code !== 4 /* Ready */) @@ -757,6 +827,12 @@ to ${stringifyState(newState)}`); this.setSpeaking(true); state.udp.send(audioPacket); } + /** + * Sends a packet to the voice gateway indicating that the client has start/stopped sending + * audio. + * + * @param speaking - Whether or not the client should be shown as speaking + */ setSpeaking(speaking) { const state = this.state; if (state.code !== 4 /* Ready */) @@ -773,8 +849,15 @@ to ${stringifyState(newState)}`); } }); } + /** + * Creates a new audio packet from an Opus packet. This involves encrypting the packet, + * then prepending a header that includes metadata. + * + * @param opusPacket - The Opus packet to prepare + * @param connectionData - The current connection data of the instance + */ createAudioPacket(opusPacket, connectionData) { - const packetBuffer = Buffer.alloc(12); + const packetBuffer = import_node_buffer3.Buffer.alloc(12); packetBuffer[0] = 128; packetBuffer[1] = 120; const { sequence, timestamp, ssrc } = connectionData; @@ -782,8 +865,14 @@ to ${stringifyState(newState)}`); packetBuffer.writeUIntBE(timestamp, 4, 4); packetBuffer.writeUIntBE(ssrc, 8, 4); packetBuffer.copy(nonce, 0, 0, 12); - return Buffer.concat([packetBuffer, ...this.encryptOpusPacket(opusPacket, connectionData)]); - } + return import_node_buffer3.Buffer.concat([packetBuffer, ...this.encryptOpusPacket(opusPacket, connectionData)]); + } + /** + * Encrypts an Opus packet using the format agreed upon by the instance and Discord. + * + * @param opusPacket - The Opus packet to encrypt + * @param connectionData - The current connection data of the instance + */ encryptOpusPacket(opusPacket, connectionData) { const { secretKey, encryptionMode } = connectionData; if (encryptionMode === "xsalsa20_poly1305_lite") { @@ -805,19 +894,24 @@ to ${stringifyState(newState)}`); __name(Networking, "Networking"); // src/receive/VoiceReceiver.ts +var import_node_buffer5 = require("buffer"); var import_v43 = require("discord-api-types/voice/v4"); // src/receive/AudioReceiveStream.ts var import_node_stream = require("stream"); // src/audio/AudioPlayer.ts -var import_node_events4 = __toESM(require("events")); +var import_node_buffer4 = require("buffer"); +var import_node_events4 = require("events"); // src/audio/AudioPlayerError.ts var AudioPlayerError = class extends Error { + /** + * The resource associated with the audio player at the time the error was thrown. + */ + resource; constructor(error, resource) { super(error.message); - __publicField(this, "resource"); this.resource = resource; this.name = error.name; this.stack = error.stack; @@ -827,12 +921,22 @@ __name(AudioPlayerError, "AudioPlayerError"); // src/audio/PlayerSubscription.ts var PlayerSubscription = class { + /** + * The voice connection of this subscription. + */ + connection; + /** + * The audio player of this subscription. + */ + player; constructor(connection, player) { - __publicField(this, "connection"); - __publicField(this, "player"); this.connection = connection; this.player = player; } + /** + * Unsubscribes the connection from the audio player, meaning that the + * audio player cannot stream audio to it until a new subscription is made. + */ unsubscribe() { this.connection["onSubscriptionRemoved"](this); this.player["unsubscribe"](this); @@ -841,7 +945,7 @@ var PlayerSubscription = class { __name(PlayerSubscription, "PlayerSubscription"); // src/audio/AudioPlayer.ts -var SILENCE_FRAME = Buffer.from([248, 255, 254]); +var SILENCE_FRAME = import_node_buffer4.Buffer.from([248, 255, 254]); var NoSubscriberBehavior = /* @__PURE__ */ ((NoSubscriberBehavior2) => { NoSubscriberBehavior2["Pause"] = "pause"; NoSubscriberBehavior2["Play"] = "play"; @@ -849,11 +953,11 @@ var NoSubscriberBehavior = /* @__PURE__ */ ((NoSubscriberBehavior2) => { return NoSubscriberBehavior2; })(NoSubscriberBehavior || {}); var AudioPlayerStatus = /* @__PURE__ */ ((AudioPlayerStatus2) => { - AudioPlayerStatus2["Idle"] = "idle"; + AudioPlayerStatus2["AutoPaused"] = "autopaused"; AudioPlayerStatus2["Buffering"] = "buffering"; + AudioPlayerStatus2["Idle"] = "idle"; AudioPlayerStatus2["Paused"] = "paused"; AudioPlayerStatus2["Playing"] = "playing"; - AudioPlayerStatus2["AutoPaused"] = "autopaused"; return AudioPlayerStatus2; })(AudioPlayerStatus || {}); function stringifyState2(state) { @@ -864,13 +968,29 @@ function stringifyState2(state) { }); } __name(stringifyState2, "stringifyState"); -var AudioPlayer = class extends import_node_events4.default { +var AudioPlayer = class extends import_node_events4.EventEmitter { + /** + * The state that the AudioPlayer is in. + */ + _state; + /** + * A list of VoiceConnections that are registered to this AudioPlayer. The player will attempt to play audio + * to the streams in this list. + */ + subscribers = []; + /** + * The behavior that the player should follow when it enters certain situations. + */ + behaviors; + /** + * The debug logger function, if debugging is enabled. + */ + debug; + /** + * Creates a new AudioPlayer. + */ constructor(options = {}) { super(); - __publicField(this, "_state"); - __publicField(this, "subscribers", []); - __publicField(this, "behaviors"); - __publicField(this, "debug"); this._state = { status: "idle" /* Idle */ }; this.behaviors = { noSubscriber: "pause" /* Pause */, @@ -879,9 +999,22 @@ var AudioPlayer = class extends import_node_events4.default { }; this.debug = options.debug === false ? null : (message) => this.emit("debug", message); } + /** + * A list of subscribed voice connections that can currently receive audio to play. + */ get playable() { return this.subscribers.filter(({ connection }) => connection.state.status === "ready" /* Ready */).map(({ connection }) => connection); } + /** + * Subscribes a VoiceConnection to the audio player's play list. If the VoiceConnection is already subscribed, + * then the existing subscription is used. + * + * @remarks + * This method should not be directly called. Instead, use VoiceConnection#subscribe. + * @param connection - The connection to subscribe + * @returns The new subscription if the voice connection is not yet subscribed, otherwise the existing subscription + */ + // @ts-ignore subscribe(connection) { const existingSubscription = this.subscribers.find((subscription) => subscription.connection === connection); if (!existingSubscription) { @@ -892,6 +1025,15 @@ var AudioPlayer = class extends import_node_events4.default { } return existingSubscription; } + /** + * Unsubscribes a subscription - i.e. removes a voice connection from the play list of the audio player. + * + * @remarks + * This method should not be directly called. Instead, use PlayerSubscription#unsubscribe. + * @param subscription - The subscription to remove + * @returns Whether or not the subscription existed on the player and was removed + */ + // @ts-ignore unsubscribe(subscription) { const index = this.subscribers.indexOf(subscription); const exists = index !== -1; @@ -902,9 +1044,15 @@ var AudioPlayer = class extends import_node_events4.default { } return exists; } + /** + * The state that the player is in. + */ get state() { return this._state; } + /** + * Sets a new state for the player, performing clean-up operations where necessary. + */ set state(newState) { const oldState = this._state; const newResource = Reflect.get(newState, "resource"); @@ -938,6 +1086,19 @@ var AudioPlayer = class extends import_node_events4.default { from ${stringifyState2(oldState)} to ${stringifyState2(newState)}`); } + /** + * Plays a new resource on the player. If the player is already playing a resource, the existing resource is destroyed + * (it cannot be reused, even in another player) and is replaced with the new resource. + * + * @remarks + * The player will transition to the Playing state once playback begins, and will return to the Idle state once + * playback is ended. + * + * If the player was previously playing a resource and this method is called, the player will not transition to the + * Idle state during the swap over. + * @param resource - The resource to play + * @throws Will throw if attempting to play an audio resource that has already ended, or is being played by another player + */ play(resource) { if (resource.ended) { throw new Error("Cannot play a resource that has already ended."); @@ -1000,6 +1161,12 @@ to ${stringifyState2(newState)}`); }; } } + /** + * Pauses playback of the current resource, if any. + * + * @param interpolateSilence - If true, the player will play 5 packets of silence after pausing to prevent audio glitches + * @returns `true` if the player was successfully paused, otherwise `false` + */ pause(interpolateSilence = true) { if (this.state.status !== "playing" /* Playing */) return false; @@ -1010,6 +1177,11 @@ to ${stringifyState2(newState)}`); }; return true; } + /** + * Unpauses playback of the current resource, if any. + * + * @returns `true` if the player was successfully unpaused, otherwise `false` + */ unpause() { if (this.state.status !== "paused" /* Paused */) return false; @@ -1020,6 +1192,13 @@ to ${stringifyState2(newState)}`); }; return true; } + /** + * Stops playback of the current resource and destroys the resource. The player will either transition to the Idle state, + * or remain in its current state until the silence padding frames of the resource have been played. + * + * @param force - If true, will force the player to enter the Idle state even if the resource has silence padding frames + * @returns `true` if the player will come to a stop, otherwise `false` + */ stop(force = false) { if (this.state.status === "idle" /* Idle */) return false; @@ -1032,6 +1211,11 @@ to ${stringifyState2(newState)}`); } return true; } + /** + * Checks whether the underlying resource (if any) is playable (readable) + * + * @returns `true` if the resource is playable, otherwise `false` + */ checkPlayable() { const state = this._state; if (state.status === "idle" /* Idle */ || state.status === "buffering" /* Buffering */) @@ -1044,12 +1228,25 @@ to ${stringifyState2(newState)}`); } return true; } + /** + * Called roughly every 20ms by the global audio player timer. Dispatches any audio packets that are buffered + * by the active connections of this audio player. + */ + // @ts-ignore _stepDispatch() { const state = this._state; if (state.status === "idle" /* Idle */ || state.status === "buffering" /* Buffering */) return; - this.playable.forEach((connection) => connection.dispatchAudio()); + for (const connection of this.playable) { + connection.dispatchAudio(); + } } + /** + * Called roughly every 20ms by the global audio player timer. Attempts to read an audio packet from the + * underlying resource of the stream, and then has all the active connections of the audio player prepare it + * (encrypt it, append header data) so that it is ready to play at the start of the next cycle. + */ + // @ts-ignore _stepPrepare() { const state = this._state; if (state.status === "idle" /* Idle */ || state.status === "buffering" /* Buffering */) @@ -1098,12 +1295,27 @@ to ${stringifyState2(newState)}`); } } } + /** + * Signals to all the subscribed connections that they should send a packet to Discord indicating + * they are no longer speaking. Called once playback of a resource ends. + */ _signalStopSpeaking() { - return this.subscribers.forEach(({ connection }) => connection.setSpeaking(false)); + for (const { connection } of this.subscribers) { + connection.setSpeaking(false); + } } + /** + * Instructs the given connections to each prepare this packet to be played at the start of the + * next cycle. + * + * @param packet - The Opus packet to be prepared by each receiver + * @param receivers - The connections that should play this packet + */ _preparePacket(packet, receivers, state) { state.playbackDuration += 20; - receivers.forEach((connection) => connection.prepareAudioPacket(packet)); + for (const connection of receivers) { + connection.prepareAudioPacket(packet); + } } }; __name(AudioPlayer, "AudioPlayer"); @@ -1128,20 +1340,21 @@ function createDefaultAudioReceiveStreamOptions() { } __name(createDefaultAudioReceiveStreamOptions, "createDefaultAudioReceiveStreamOptions"); var AudioReceiveStream = class extends import_node_stream.Readable { + /** + * The end behavior of the receive stream. + */ + end; + endTimeout; constructor({ end, ...options }) { super({ ...options, objectMode: true }); - __publicField(this, "end"); - __publicField(this, "endTimeout"); this.end = end; } push(buffer) { - if (buffer) { - if (this.end.behavior === 2 /* AfterInactivity */ || this.end.behavior === 1 /* AfterSilence */ && (buffer.compare(SILENCE_FRAME) !== 0 || typeof this.endTimeout === "undefined")) { - this.renewEndTimeout(this.end); - } + if (buffer && (this.end.behavior === 2 /* AfterInactivity */ || this.end.behavior === 1 /* AfterSilence */ && (buffer.compare(SILENCE_FRAME) !== 0 || this.endTimeout === void 0))) { + this.renewEndTimeout(this.end); } return super.push(buffer); } @@ -1159,11 +1372,19 @@ __name(AudioReceiveStream, "AudioReceiveStream"); // src/receive/SSRCMap.ts var import_node_events5 = require("events"); var SSRCMap = class extends import_node_events5.EventEmitter { + /** + * The underlying map. + */ + map; constructor() { super(); - __publicField(this, "map"); this.map = /* @__PURE__ */ new Map(); } + /** + * Updates the map with new user data + * + * @param data - The data to update with + */ update(data) { const existing = this.map.get(data.audioSSRC); const newValue = { @@ -1175,6 +1396,11 @@ var SSRCMap = class extends import_node_events5.EventEmitter { this.emit("create", newValue); this.emit("update", existing, newValue); } + /** + * Gets the stored voice data of a user. + * + * @param target - The target, either their user id or audio SSRC + */ get(target) { if (typeof target === "number") { return this.map.get(target); @@ -1186,6 +1412,12 @@ var SSRCMap = class extends import_node_events5.EventEmitter { } return void 0; } + /** + * Deletes the stored voice data about a user. + * + * @param target - The target of the delete operation, either their audio SSRC or user id + * @returns The data that was deleted, if any + */ delete(target) { if (typeof target === "number") { const existing = this.map.get(target); @@ -1210,10 +1442,13 @@ __name(SSRCMap, "SSRCMap"); // src/receive/SpeakingMap.ts var import_node_events6 = require("events"); var _SpeakingMap = class extends import_node_events6.EventEmitter { + /** + * The currently speaking users, mapped to the milliseconds since UNIX epoch at which they started speaking. + */ + users; + speakingTimeouts; constructor() { super(); - __publicField(this, "users"); - __publicField(this, "speakingTimeouts"); this.users = /* @__PURE__ */ new Map(); this.speakingTimeouts = /* @__PURE__ */ new Map(); } @@ -1228,25 +1463,48 @@ var _SpeakingMap = class extends import_node_events6.EventEmitter { this.startTimeout(userId); } startTimeout(userId) { - this.speakingTimeouts.set(userId, setTimeout(() => { - this.emit("end", userId); - this.speakingTimeouts.delete(userId); - this.users.delete(userId); - }, _SpeakingMap.DELAY)); + this.speakingTimeouts.set( + userId, + setTimeout(() => { + this.emit("end", userId); + this.speakingTimeouts.delete(userId); + this.users.delete(userId); + }, _SpeakingMap.DELAY) + ); } }; var SpeakingMap = _SpeakingMap; __name(SpeakingMap, "SpeakingMap"); +/** + * The delay after a packet is received from a user until they're marked as not speaking anymore. + */ __publicField(SpeakingMap, "DELAY", 100); // src/receive/VoiceReceiver.ts var VoiceReceiver = class { + /** + * The attached connection of this receiver. + */ + voiceConnection; + /** + * Maps SSRCs to Discord user ids. + */ + ssrcMap; + /** + * The current audio subscriptions of this receiver. + */ + subscriptions; + /** + * The connection data of the receiver. + * + * @internal + */ + connectionData; + /** + * The speaking map of the receiver. + */ + speaking; constructor(voiceConnection) { - __publicField(this, "voiceConnection"); - __publicField(this, "ssrcMap"); - __publicField(this, "subscriptions"); - __publicField(this, "connectionData"); - __publicField(this, "speaking"); this.voiceConnection = voiceConnection; this.ssrcMap = new SSRCMap(); this.speaking = new SpeakingMap(); @@ -1255,6 +1513,12 @@ var VoiceReceiver = class { this.onWsPacket = this.onWsPacket.bind(this); this.onUdpMessage = this.onUdpMessage.bind(this); } + /** + * Called when a packet is received on the attached connection's WebSocket. + * + * @param packet - The received packet + * @internal + */ onWsPacket(packet) { if (packet.op === import_v43.VoiceOpcodes.ClientDisconnect && typeof packet.d?.user_id === "string") { this.ssrcMap.delete(packet.d.user_id); @@ -1282,8 +1546,17 @@ var VoiceReceiver = class { const decrypted = methods.open(buffer.slice(12, end), nonce2, secretKey); if (!decrypted) return; - return Buffer.from(decrypted); - } + return import_node_buffer5.Buffer.from(decrypted); + } + /** + * Parses an audio packet, decrypting it to yield an Opus packet. + * + * @param buffer - The buffer to parse + * @param mode - The encryption mode + * @param nonce - The nonce buffer used by the connection for encryption + * @param secretKey - The secret key used by the connection for encryption + * @returns The parsed Opus packet + */ parsePacket(buffer, mode, nonce2, secretKey) { let packet = this.decrypt(buffer, mode, nonce2, secretKey); if (!packet) @@ -1294,6 +1567,12 @@ var VoiceReceiver = class { } return packet; } + /** + * Called when the UDP socket of the attached connection receives a message. + * + * @param msg - The received message + * @internal + */ onUdpMessage(msg) { if (msg.length <= 8) return; @@ -1306,7 +1585,12 @@ var VoiceReceiver = class { if (!stream) return; if (this.connectionData.encryptionMode && this.connectionData.nonceBuffer && this.connectionData.secretKey) { - const packet = this.parsePacket(msg, this.connectionData.encryptionMode, this.connectionData.nonceBuffer, this.connectionData.secretKey); + const packet = this.parsePacket( + msg, + this.connectionData.encryptionMode, + this.connectionData.nonceBuffer, + this.connectionData.secretKey + ); if (packet) { stream.push(packet); } else { @@ -1314,6 +1598,12 @@ var VoiceReceiver = class { } } } + /** + * Creates a subscription for the given user id. + * + * @param target - The id of the user to subscribe to + * @returns A readable stream of Opus packets received from the target + */ subscribe(userId, options) { const existing = this.subscriptions.get(userId); if (existing) @@ -1331,11 +1621,11 @@ __name(VoiceReceiver, "VoiceReceiver"); // src/VoiceConnection.ts var VoiceConnectionStatus = /* @__PURE__ */ ((VoiceConnectionStatus2) => { - VoiceConnectionStatus2["Signalling"] = "signalling"; VoiceConnectionStatus2["Connecting"] = "connecting"; - VoiceConnectionStatus2["Ready"] = "ready"; - VoiceConnectionStatus2["Disconnected"] = "disconnected"; VoiceConnectionStatus2["Destroyed"] = "destroyed"; + VoiceConnectionStatus2["Disconnected"] = "disconnected"; + VoiceConnectionStatus2["Ready"] = "ready"; + VoiceConnectionStatus2["Signalling"] = "signalling"; return VoiceConnectionStatus2; })(VoiceConnectionStatus || {}); var VoiceConnectionDisconnectReason = /* @__PURE__ */ ((VoiceConnectionDisconnectReason2) => { @@ -1345,23 +1635,52 @@ var VoiceConnectionDisconnectReason = /* @__PURE__ */ ((VoiceConnectionDisconnec VoiceConnectionDisconnectReason2[VoiceConnectionDisconnectReason2["Manual"] = 3] = "Manual"; return VoiceConnectionDisconnectReason2; })(VoiceConnectionDisconnectReason || {}); -var VoiceConnection2 = class extends import_node_events7.EventEmitter { - constructor(joinConfig, { debug, adapterCreator }) { +var VoiceConnection = class extends import_node_events7.EventEmitter { + /** + * The number of consecutive rejoin attempts. Initially 0, and increments for each rejoin. + * When a connection is successfully established, it resets to 0. + */ + rejoinAttempts; + /** + * The state of the voice connection. + */ + _state; + /** + * A configuration storing all the data needed to reconnect to a Guild's voice server. + * + * @internal + */ + joinConfig; + /** + * The two packets needed to successfully establish a voice connection. They are received + * from the main Discord gateway after signalling to change the voice state. + */ + packets; + /** + * The receiver of this voice connection. You should join the voice channel with `selfDeaf` set + * to false for this feature to work properly. + */ + receiver; + /** + * The debug logger function, if debugging is enabled. + */ + debug; + /** + * Creates a new voice connection. + * + * @param joinConfig - The data required to establish the voice connection + * @param options - The options used to create this voice connection + */ + constructor(joinConfig, options) { super(); - __publicField(this, "rejoinAttempts"); - __publicField(this, "_state"); - __publicField(this, "joinConfig"); - __publicField(this, "packets"); - __publicField(this, "receiver"); - __publicField(this, "debug"); - this.debug = debug ? (message) => this.emit("debug", message) : null; + this.debug = options.debug ? (message) => this.emit("debug", message) : null; this.rejoinAttempts = 0; this.receiver = new VoiceReceiver(this); this.onNetworkingClose = this.onNetworkingClose.bind(this); this.onNetworkingStateChange = this.onNetworkingStateChange.bind(this); this.onNetworkingError = this.onNetworkingError.bind(this); this.onNetworkingDebug = this.onNetworkingDebug.bind(this); - const adapter = adapterCreator({ + const adapter = options.adapterCreator({ onVoiceServerUpdate: (data) => this.addServerPacket(data), onVoiceStateUpdate: (data) => this.addStatePacket(data), destroy: () => this.destroy(false) @@ -1373,9 +1692,15 @@ var VoiceConnection2 = class extends import_node_events7.EventEmitter { }; this.joinConfig = joinConfig; } + /** + * The current state of the voice connection. + */ get state() { return this._state; } + /** + * Updates the state of the voice connection, performing clean-up operations where necessary. + */ set state(newState) { const oldState = this._state; const oldNetworking = Reflect.get(oldState, "networking"); @@ -1414,6 +1739,12 @@ var VoiceConnection2 = class extends import_node_events7.EventEmitter { this.emit(newState.status, oldState, newState); } } + /** + * Registers a `VOICE_SERVER_UPDATE` packet to the voice connection. This will cause it to reconnect using the + * new data provided in the packet. + * + * @param packet - The received `VOICE_SERVER_UPDATE` packet + */ addServerPacket(packet) { this.packets.server = packet; if (packet.endpoint) { @@ -1426,15 +1757,28 @@ var VoiceConnection2 = class extends import_node_events7.EventEmitter { }; } } + /** + * Registers a `VOICE_STATE_UPDATE` packet to the voice connection. Most importantly, it stores the id of the + * channel that the client is connected to. + * + * @param packet - The received `VOICE_STATE_UPDATE` packet + */ addStatePacket(packet) { this.packets.state = packet; - if (typeof packet.self_deaf !== "undefined") + if (packet.self_deaf !== void 0) this.joinConfig.selfDeaf = packet.self_deaf; - if (typeof packet.self_mute !== "undefined") + if (packet.self_mute !== void 0) this.joinConfig.selfMute = packet.self_mute; if (packet.channel_id) this.joinConfig.channelId = packet.channel_id; } + /** + * Called when the networking state changes, and the new ws/udp packet/message handlers need to be rebound + * to the new instances. + * + * @param newState - The new networking state + * @param oldState - The old networking state, if there is one + */ updateReceiveBindings(newState, oldState) { const oldWs = Reflect.get(oldState ?? {}, "ws"); const newWs = Reflect.get(newState, "ws"); @@ -1450,17 +1794,31 @@ var VoiceConnection2 = class extends import_node_events7.EventEmitter { } this.receiver.connectionData = Reflect.get(newState, "connectionData") ?? {}; } + /** + * Attempts to configure a networking instance for this voice connection using the received packets. + * Both packets are required, and any existing networking instance will be destroyed. + * + * @remarks + * This is called when the voice server of the connection changes, e.g. if the bot is moved into a + * different channel in the same guild but has a different voice server. In this instance, the connection + * needs to be re-established to the new voice server. + * + * The connection will transition to the Connecting state when this is called. + */ configureNetworking() { const { server, state } = this.packets; if (!server || !state || this.state.status === "destroyed" /* Destroyed */ || !server.endpoint) return; - const networking = new Networking({ - endpoint: server.endpoint, - serverId: server.guild_id, - token: server.token, - sessionId: state.session_id, - userId: state.user_id - }, Boolean(this.debug)); + const networking = new Networking( + { + endpoint: server.endpoint, + serverId: server.guild_id, + token: server.token, + sessionId: state.session_id, + userId: state.user_id + }, + Boolean(this.debug) + ); networking.once("close", this.onNetworkingClose); networking.on("stateChange", this.onNetworkingStateChange); networking.on("error", this.onNetworkingError); @@ -1471,6 +1829,17 @@ var VoiceConnection2 = class extends import_node_events7.EventEmitter { networking }; } + /** + * Called when the networking instance for this connection closes. If the close code is 4014 (do not reconnect), + * the voice connection will transition to the Disconnected state which will store the close code. You can + * decide whether or not to reconnect when this occurs by listening for the state change and calling reconnect(). + * + * @remarks + * If the close code was anything other than 4014, it is likely that the closing was not intended, and so the + * VoiceConnection will signal to Discord that it would like to rejoin the channel. This automatically attempts + * to re-establish the connection. This would be seen as a transition from the Ready state to the Signalling state. + * @param code - The close code + */ onNetworkingClose(code) { if (this.state.status === "destroyed" /* Destroyed */) return; @@ -1496,6 +1865,12 @@ var VoiceConnection2 = class extends import_node_events7.EventEmitter { } } } + /** + * Called when the state of the networking instance changes. This is used to derive the state of the voice connection. + * + * @param oldState - The previous state + * @param newState - The new state + */ onNetworkingStateChange(oldState, newState) { this.updateReceiveBindings(newState, oldState); if (oldState.code === newState.code) @@ -1514,24 +1889,47 @@ var VoiceConnection2 = class extends import_node_events7.EventEmitter { }; } } + /** + * Propagates errors from the underlying network instance. + * + * @param error - The error to propagate + */ onNetworkingError(error) { this.emit("error", error); } + /** + * Propagates debug messages from the underlying network instance. + * + * @param message - The debug message to propagate + */ onNetworkingDebug(message) { this.debug?.(`[NW] ${message}`); } + /** + * Prepares an audio packet for dispatch. + * + * @param buffer - The Opus packet to prepare + */ prepareAudioPacket(buffer) { const state = this.state; if (state.status !== "ready" /* Ready */) return; return state.networking.prepareAudioPacket(buffer); } + /** + * Dispatches the previously prepared audio packet (if any) + */ dispatchAudio() { const state = this.state; if (state.status !== "ready" /* Ready */) return; return state.networking.dispatchAudio(); } + /** + * Prepares an audio packet and dispatches it immediately. + * + * @param buffer - The Opus packet to play + */ playOpusPacket(buffer) { const state = this.state; if (state.status !== "ready" /* Ready */) @@ -1539,6 +1937,13 @@ var VoiceConnection2 = class extends import_node_events7.EventEmitter { state.networking.prepareAudioPacket(buffer); return state.networking.dispatchAudio(); } + /** + * Destroys the VoiceConnection, preventing it from connecting to voice again. + * This method should be called when you no longer require the VoiceConnection to + * prevent memory leaks. + * + * @param adapterAvailable - Whether the adapter can be used + */ destroy(adapterAvailable = true) { if (this.state.status === "destroyed" /* Destroyed */) { throw new Error("Cannot destroy VoiceConnection - it has already been destroyed"); @@ -1553,6 +1958,11 @@ var VoiceConnection2 = class extends import_node_events7.EventEmitter { status: "destroyed" /* Destroyed */ }; } + /** + * Disconnects the VoiceConnection, allowing the possibility of rejoining later on. + * + * @returns `true` if the connection was successfully disconnected + */ disconnect() { if (this.state.status === "destroyed" /* Destroyed */ || this.state.status === "signalling" /* Signalling */) { return false; @@ -1574,6 +1984,16 @@ var VoiceConnection2 = class extends import_node_events7.EventEmitter { }; return true; } + /** + * Attempts to rejoin (better explanation soon:tm:) + * + * @remarks + * Calling this method successfully will automatically increment the `rejoinAttempts` counter, + * which you can use to inform whether or not you'd like to keep attempting to reconnect your + * voice connection. + * + * A state transition from Disconnected to Signalling will be observed when this is called. + */ rejoin(joinConfig) { if (this.state.status === "destroyed" /* Destroyed */) { return false; @@ -1599,11 +2019,23 @@ var VoiceConnection2 = class extends import_node_events7.EventEmitter { }; return false; } + /** + * Updates the speaking status of the voice connection. This is used when audio players are done playing audio, + * and need to signal that the connection is no longer playing audio. + * + * @param enabled - Whether or not to show as speaking + */ setSpeaking(enabled) { if (this.state.status !== "ready" /* Ready */) return false; return this.state.networking.setSpeaking(enabled); } + /** + * Subscribes to an audio player, allowing the player to play audio on this voice connection. + * + * @param player - The audio player to subscribe to + * @returns The created subscription + */ subscribe(player) { if (this.state.status === "destroyed" /* Destroyed */) return; @@ -1614,6 +2046,14 @@ var VoiceConnection2 = class extends import_node_events7.EventEmitter { }; return subscription; } + /** + * The latest ping (in milliseconds) for the WebSocket connection and audio playback for this voice + * connection, if this data is available. + * + * @remarks + * For this data to be available, the VoiceConnection must be in the Ready state, and its underlying + * WebSocket connection and UDP socket must have had at least one ping-pong exchange. + */ get ping() { if (this.state.status === "ready" /* Ready */ && this.state.networking.state.code === 4 /* Ready */) { return { @@ -1626,6 +2066,11 @@ var VoiceConnection2 = class extends import_node_events7.EventEmitter { udp: void 0 }; } + /** + * Called when a subscription of this voice connection to an audio player is removed. + * + * @param subscription - The removed subscription + */ onSubscriptionRemoved(subscription) { if (this.state.status !== "destroyed" /* Destroyed */ && this.state.subscription === subscription) { this.state = { @@ -1635,7 +2080,7 @@ var VoiceConnection2 = class extends import_node_events7.EventEmitter { } } }; -__name(VoiceConnection2, "VoiceConnection"); +__name(VoiceConnection, "VoiceConnection"); function createVoiceConnection(joinConfig, options) { const payload = createJoinVoiceChannelPayload(joinConfig); const existing = getVoiceConnection(joinConfig.guildId, joinConfig.group); @@ -1655,16 +2100,14 @@ function createVoiceConnection(joinConfig, options) { } return existing; } - const voiceConnection = new VoiceConnection2(joinConfig, options); + const voiceConnection = new VoiceConnection(joinConfig, options); trackVoiceConnection(voiceConnection); - if (voiceConnection.state.status !== "destroyed" /* Destroyed */) { - if (!voiceConnection.state.adapter.sendPayload(payload)) { - voiceConnection.state = { - ...voiceConnection.state, - status: "disconnected" /* Disconnected */, - reason: 1 /* AdapterUnavailable */ - }; - } + if (voiceConnection.state.status !== "destroyed" /* Destroyed */ && !voiceConnection.state.adapter.sendPayload(payload)) { + voiceConnection.state = { + ...voiceConnection.state, + status: "disconnected" /* Disconnected */, + reason: 1 /* AdapterUnavailable */ + }; } return voiceConnection; } @@ -1708,18 +2151,29 @@ var FFMPEG_OPUS_ARGUMENTS = [ ]; var StreamType = /* @__PURE__ */ ((StreamType2) => { StreamType2["Arbitrary"] = "arbitrary"; - StreamType2["Raw"] = "raw"; StreamType2["OggOpus"] = "ogg/opus"; - StreamType2["WebmOpus"] = "webm/opus"; StreamType2["Opus"] = "opus"; + StreamType2["Raw"] = "raw"; + StreamType2["WebmOpus"] = "webm/opus"; return StreamType2; })(StreamType || {}); var Node = class { + /** + * The outbound edges from this node. + */ + edges = []; + /** + * The type of stream for this node. + */ + type; constructor(type) { - __publicField(this, "edges", []); - __publicField(this, "type"); this.type = type; } + /** + * Creates an outbound edge from this node. + * + * @param edge - The edge to create + */ addEdge(edge) { this.edges.push({ ...edge, from: this }); } @@ -1802,9 +2256,9 @@ function findPath(from, constraints, goal = getNode("opus" /* Opus */), path = [ if (from === goal && constraints(path)) { return { cost: 0 }; } else if (depth === 0) { - return { cost: Infinity }; + return { cost: Number.POSITIVE_INFINITY }; } - let currentBest = void 0; + let currentBest; for (const edge of from.edges) { if (currentBest && edge.cost > currentBest.cost) continue; @@ -1814,7 +2268,7 @@ function findPath(from, constraints, goal = getNode("opus" /* Opus */), path = [ currentBest = { cost, edge, next }; } } - return currentBest ?? { cost: Infinity }; + return currentBest ?? { cost: Number.POSITIVE_INFINITY }; } __name(findPath, "findPath"); function constructPipeline(step) { @@ -1834,17 +2288,51 @@ __name(findPipeline, "findPipeline"); // src/audio/AudioResource.ts var AudioResource = class { + /** + * An object-mode Readable stream that emits Opus packets. This is what is played by audio players. + */ + playStream; + /** + * The pipeline used to convert the input stream into a playable format. For example, this may + * contain an FFmpeg component for arbitrary inputs, and it may contain a VolumeTransformer component + * for resources with inline volume transformation enabled. + */ + edges; + /** + * Optional metadata that can be used to identify the resource. + */ + metadata; + /** + * If the resource was created with inline volume transformation enabled, then this will be a + * prism-media VolumeTransformer. You can use this to alter the volume of the stream. + */ + volume; + /** + * If using an Opus encoder to create this audio resource, then this will be a prism-media opus.Encoder. + * You can use this to control settings such as bitrate, FEC, PLP. + */ + encoder; + /** + * The audio player that the resource is subscribed to, if any. + */ + audioPlayer; + /** + * The playback duration of this audio resource, given in milliseconds. + */ + playbackDuration = 0; + /** + * Whether or not the stream for this resource has started (data has become readable) + */ + started = false; + /** + * The number of silence frames to append to the end of the resource's audio stream, to prevent interpolation glitches. + */ + silencePaddingFrames; + /** + * The number of remaining silence frames to play. If -1, the frames have not yet started playing. + */ + silenceRemaining = -1; constructor(edges, streams, metadata, silencePaddingFrames) { - __publicField(this, "playStream"); - __publicField(this, "edges"); - __publicField(this, "metadata"); - __publicField(this, "volume"); - __publicField(this, "encoder"); - __publicField(this, "audioPlayer"); - __publicField(this, "playbackDuration", 0); - __publicField(this, "started", false); - __publicField(this, "silencePaddingFrames"); - __publicField(this, "silenceRemaining", -1); this.edges = edges; this.playStream = streams.length > 1 ? (0, import_node_stream2.pipeline)(streams, noop) : streams[0]; this.metadata = metadata; @@ -1858,6 +2346,10 @@ var AudioResource = class { } this.playStream.once("readable", () => this.started = true); } + /** + * Whether this resource is readable. If the underlying resource is no longer readable, this will still return true + * while there are silence padding frames left to play. + */ get readable() { if (this.silenceRemaining === 0) return false; @@ -1869,9 +2361,22 @@ var AudioResource = class { } return real; } + /** + * Whether this resource has ended or not. + */ get ended() { return this.playStream.readableEnded || this.playStream.destroyed || this.silenceRemaining === 0; } + /** + * Attempts to read an Opus packet from the audio resource. If a packet is available, the playbackDuration + * is incremented. + * + * @remarks + * It is advisable to check that the playStream is readable before calling this method. While no runtime + * errors will be thrown, you should check that the resource is still available before attempting to + * read from it. + * @internal + */ read() { if (this.silenceRemaining === 0) { return null; @@ -1909,7 +2414,7 @@ function createAudioResource(input, options = {}) { let needsInlineVolume = Boolean(options.inlineVolume); if (typeof input === "string") { inputType = "arbitrary" /* Arbitrary */; - } else if (typeof inputType === "undefined") { + } else if (inputType === void 0) { const analysis = inferStreamType(input); inputType = analysis.streamType; needsInlineVolume = needsInlineVolume && !analysis.hasVolume; @@ -1923,7 +2428,12 @@ function createAudioResource(input, options = {}) { const streams = transformerPipeline.map((edge) => edge.transformer(input)); if (typeof input !== "string") streams.unshift(input); - return new AudioResource(transformerPipeline, streams, options.metadata ?? null, options.silencePaddingFrames ?? 5); + return new AudioResource( + transformerPipeline, + streams, + options.metadata ?? null, + options.silencePaddingFrames ?? 5 + ); } __name(createAudioResource, "createAudioResource"); @@ -1939,16 +2449,19 @@ function findPackageJSON(dir, packageName, depth) { if (pkg.name !== packageName) throw new Error("package.json does not match"); return pkg; - } catch (err) { + } catch { return findPackageJSON((0, import_node_path.resolve)(dir, ".."), packageName, depth - 1); } } __name(findPackageJSON, "findPackageJSON"); function version(name) { try { - const pkg = name === "@discordjs/voice" ? require_package() : findPackageJSON((0, import_node_path.dirname)(require.resolve(name)), name, 3); + if (name === "@discordjs/voice") { + return "0.16.0"; + } + const pkg = findPackageJSON((0, import_node_path.dirname)(require.resolve(name)), name, 3); return pkg?.version ?? "not found"; - } catch (err) { + } catch { return "not found"; } } @@ -1975,7 +2488,7 @@ function generateDependencyReport() { const info = import_prism_media3.default.FFmpeg.getInfo(); report.push(`- version: ${info.version}`); report.push(`- libopus: ${info.output.includes("--enable-libopus") ? "yes" : "no"}`); - } catch (err) { + } catch { report.push("- not found"); } return ["-".repeat(50), ...report, "-".repeat(50)].join("\n"); @@ -2009,6 +2522,8 @@ async function entersState(target, status, timeoutOrSignal) { __name(entersState, "entersState"); // src/util/demuxProbe.ts +var import_node_buffer6 = require("buffer"); +var import_node_process = __toESM(require("process")); var import_node_stream3 = require("stream"); var import_prism_media4 = __toESM(require("prism-media")); function validateDiscordOpusHead(opusHead) { @@ -2017,14 +2532,18 @@ function validateDiscordOpusHead(opusHead) { return channels === 2 && sampleRate === 48e3; } __name(validateDiscordOpusHead, "validateDiscordOpusHead"); -function demuxProbe(stream, probeSize = 1024, validator = validateDiscordOpusHead) { +async function demuxProbe(stream, probeSize = 1024, validator = validateDiscordOpusHead) { return new Promise((resolve2, reject) => { - if (stream.readableObjectMode) - return reject(new Error("Cannot probe a readable stream in object mode")); - if (stream.readableEnded) - return reject(new Error("Cannot probe a stream that has ended")); - let readBuffer = Buffer.alloc(0); - let resolved = void 0; + if (stream.readableObjectMode) { + reject(new Error("Cannot probe a readable stream in object mode")); + return; + } + if (stream.readableEnded) { + reject(new Error("Cannot probe a stream that has ended")); + return; + } + let readBuffer = import_node_buffer6.Buffer.alloc(0); + let resolved; const finish = /* @__PURE__ */ __name((type) => { stream.off("data", onData); stream.off("close", onClose); @@ -2063,13 +2582,13 @@ function demuxProbe(stream, probeSize = 1024, validator = validateDiscordOpusHea } }, "onClose"); const onData = /* @__PURE__ */ __name((buffer) => { - readBuffer = Buffer.concat([readBuffer, buffer]); + readBuffer = import_node_buffer6.Buffer.concat([readBuffer, buffer]); webm.write(buffer); ogg.write(buffer); if (readBuffer.length >= probeSize) { stream.off("data", onData); stream.pause(); - process.nextTick(onClose); + import_node_process.default.nextTick(onClose); } }, "onData"); stream.once("error", reject); @@ -2079,6 +2598,9 @@ function demuxProbe(stream, probeSize = 1024, validator = validateDiscordOpusHea }); } __name(demuxProbe, "demuxProbe"); + +// src/index.ts +var version2 = "0.16.0"; // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { AudioPlayer, @@ -2106,6 +2628,7 @@ __name(demuxProbe, "demuxProbe"); getVoiceConnection, getVoiceConnections, joinVoiceChannel, - validateDiscordOpusHead + validateDiscordOpusHead, + version }); //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@discordjs/voice/dist/index.js.map b/node_modules/@discordjs/voice/dist/index.js.map index 019d3db..c191620 100644 --- a/node_modules/@discordjs/voice/dist/index.js.map +++ b/node_modules/@discordjs/voice/dist/index.js.map @@ -1 +1 @@ -{"version":3,"sources":["../src/index.ts","../src/VoiceConnection.ts","../src/DataStore.ts","../src/networking/Networking.ts","../src/networking/VoiceUDPSocket.ts","../src/networking/VoiceWebSocket.ts","../src/util/Secretbox.ts","../src/util/util.ts","../src/receive/VoiceReceiver.ts","../src/receive/AudioReceiveStream.ts","../src/audio/AudioPlayer.ts","../src/audio/AudioPlayerError.ts","../src/audio/PlayerSubscription.ts","../src/receive/SSRCMap.ts","../src/receive/SpeakingMap.ts","../src/joinVoiceChannel.ts","../src/audio/AudioResource.ts","../src/audio/TransformerGraph.ts","../src/util/generateDependencyReport.ts","../src/util/entersState.ts","../src/util/abortAfter.ts","../src/util/demuxProbe.ts"],"sourcesContent":["export * from './joinVoiceChannel';\nexport * from './audio';\nexport * from './util';\nexport * from './receive';\n\nexport {\n\tVoiceConnection,\n\tVoiceConnectionState,\n\tVoiceConnectionStatus,\n\tVoiceConnectionConnectingState,\n\tVoiceConnectionDestroyedState,\n\tVoiceConnectionDisconnectedState,\n\tVoiceConnectionDisconnectedBaseState,\n\tVoiceConnectionDisconnectedOtherState,\n\tVoiceConnectionDisconnectedWebSocketState,\n\tVoiceConnectionDisconnectReason,\n\tVoiceConnectionReadyState,\n\tVoiceConnectionSignallingState,\n} from './VoiceConnection';\n\nexport { JoinConfig, getVoiceConnection, getVoiceConnections, getGroups } from './DataStore';\n","/* eslint-disable @typescript-eslint/method-signature-style */\nimport { EventEmitter } from 'node:events';\nimport type { GatewayVoiceServerUpdateDispatchData, GatewayVoiceStateUpdateDispatchData } from 'discord-api-types/v10';\nimport type { CreateVoiceConnectionOptions } from '.';\nimport {\n\tgetVoiceConnection,\n\tcreateJoinVoiceChannelPayload,\n\ttrackVoiceConnection,\n\tJoinConfig,\n\tuntrackVoiceConnection,\n} from './DataStore';\nimport type { AudioPlayer } from './audio/AudioPlayer';\nimport type { PlayerSubscription } from './audio/PlayerSubscription';\nimport type { VoiceWebSocket, VoiceUDPSocket } from './networking';\nimport { Networking, NetworkingState, NetworkingStatusCode } from './networking/Networking';\nimport { VoiceReceiver } from './receive';\nimport type { DiscordGatewayAdapterImplementerMethods } from './util/adapter';\nimport { noop } from './util/util';\n\n/**\n * The various status codes a voice connection can hold at any one time.\n */\nexport enum VoiceConnectionStatus {\n\t/**\n\t * Sending a packet to the main Discord gateway to indicate we want to change our voice state.\n\t */\n\tSignalling = 'signalling',\n\n\t/**\n\t * The `VOICE_SERVER_UPDATE` and `VOICE_STATE_UPDATE` packets have been received, now attempting to establish a voice connection.\n\t */\n\tConnecting = 'connecting',\n\n\t/**\n\t * A voice connection has been established, and is ready to be used.\n\t */\n\tReady = 'ready',\n\n\t/**\n\t * The voice connection has either been severed or not established.\n\t */\n\tDisconnected = 'disconnected',\n\n\t/**\n\t * The voice connection has been destroyed and untracked, it cannot be reused.\n\t */\n\tDestroyed = 'destroyed',\n}\n\n/**\n * The state that a VoiceConnection will be in when it is waiting to receive a VOICE_SERVER_UPDATE and\n * VOICE_STATE_UPDATE packet from Discord, provided by the adapter.\n */\nexport interface VoiceConnectionSignallingState {\n\tstatus: VoiceConnectionStatus.Signalling;\n\tsubscription?: PlayerSubscription;\n\tadapter: DiscordGatewayAdapterImplementerMethods;\n}\n\n/**\n * The reasons a voice connection can be in the disconnected state.\n */\nexport enum VoiceConnectionDisconnectReason {\n\t/**\n\t * When the WebSocket connection has been closed.\n\t */\n\tWebSocketClose,\n\n\t/**\n\t * When the adapter was unable to send a message requested by the VoiceConnection.\n\t */\n\tAdapterUnavailable,\n\n\t/**\n\t * When a VOICE_SERVER_UPDATE packet is received with a null endpoint, causing the connection to be severed.\n\t */\n\tEndpointRemoved,\n\n\t/**\n\t * When a manual disconnect was requested.\n\t */\n\tManual,\n}\n\n/**\n * The state that a VoiceConnection will be in when it is not connected to a Discord voice server nor is\n * it attempting to connect. You can manually attempt to reconnect using VoiceConnection#reconnect.\n */\nexport interface VoiceConnectionDisconnectedBaseState {\n\tstatus: VoiceConnectionStatus.Disconnected;\n\tsubscription?: PlayerSubscription;\n\tadapter: DiscordGatewayAdapterImplementerMethods;\n}\n\n/**\n * The state that a VoiceConnection will be in when it is not connected to a Discord voice server nor is\n * it attempting to connect. You can manually attempt to reconnect using VoiceConnection#reconnect.\n */\nexport interface VoiceConnectionDisconnectedOtherState extends VoiceConnectionDisconnectedBaseState {\n\treason: Exclude;\n}\n\n/**\n * The state that a VoiceConnection will be in when its WebSocket connection was closed.\n * You can manually attempt to reconnect using VoiceConnection#reconnect.\n */\nexport interface VoiceConnectionDisconnectedWebSocketState extends VoiceConnectionDisconnectedBaseState {\n\treason: VoiceConnectionDisconnectReason.WebSocketClose;\n\n\t/**\n\t * The close code of the WebSocket connection to the Discord voice server.\n\t */\n\tcloseCode: number;\n}\n\n/**\n * The states that a VoiceConnection can be in when it is not connected to a Discord voice server nor is\n * it attempting to connect. You can manually attempt to connect using VoiceConnection#reconnect.\n */\nexport type VoiceConnectionDisconnectedState =\n\t| VoiceConnectionDisconnectedOtherState\n\t| VoiceConnectionDisconnectedWebSocketState;\n\n/**\n * The state that a VoiceConnection will be in when it is establishing a connection to a Discord\n * voice server.\n */\nexport interface VoiceConnectionConnectingState {\n\tstatus: VoiceConnectionStatus.Connecting;\n\tnetworking: Networking;\n\tsubscription?: PlayerSubscription;\n\tadapter: DiscordGatewayAdapterImplementerMethods;\n}\n\n/**\n * The state that a VoiceConnection will be in when it has an active connection to a Discord\n * voice server.\n */\nexport interface VoiceConnectionReadyState {\n\tstatus: VoiceConnectionStatus.Ready;\n\tnetworking: Networking;\n\tsubscription?: PlayerSubscription;\n\tadapter: DiscordGatewayAdapterImplementerMethods;\n}\n\n/**\n * The state that a VoiceConnection will be in when it has been permanently been destroyed by the\n * user and untracked by the library. It cannot be reconnected, instead, a new VoiceConnection\n * needs to be established.\n */\nexport interface VoiceConnectionDestroyedState {\n\tstatus: VoiceConnectionStatus.Destroyed;\n}\n\n/**\n * The various states that a voice connection can be in.\n */\nexport type VoiceConnectionState =\n\t| VoiceConnectionSignallingState\n\t| VoiceConnectionDisconnectedState\n\t| VoiceConnectionConnectingState\n\t| VoiceConnectionReadyState\n\t| VoiceConnectionDestroyedState;\n\nexport interface VoiceConnection extends EventEmitter {\n\t/**\n\t * Emitted when there is an error emitted from the voice connection\n\t * @event\n\t */\n\ton(event: 'error', listener: (error: Error) => void): this;\n\t/**\n\t * Emitted debugging information about the voice connection\n\t * @event\n\t */\n\ton(event: 'debug', listener: (message: string) => void): this;\n\t/**\n\t * Emitted when the state of the voice connection changes\n\t * @event\n\t */\n\ton(event: 'stateChange', listener: (oldState: VoiceConnectionState, newState: VoiceConnectionState) => void): this;\n\t/**\n\t * Emitted when the state of the voice connection changes to a specific status\n\t * @event\n\t */\n\ton(\n\t\tevent: T,\n\t\tlistener: (oldState: VoiceConnectionState, newState: VoiceConnectionState & { status: T }) => void,\n\t): this;\n}\n\n/**\n * A connection to the voice server of a Guild, can be used to play audio in voice channels.\n */\nexport class VoiceConnection extends EventEmitter {\n\t/**\n\t * The number of consecutive rejoin attempts. Initially 0, and increments for each rejoin.\n\t * When a connection is successfully established, it resets to 0.\n\t */\n\tpublic rejoinAttempts: number;\n\n\t/**\n\t * The state of the voice connection.\n\t */\n\tprivate _state: VoiceConnectionState;\n\n\t/**\n\t * A configuration storing all the data needed to reconnect to a Guild's voice server.\n\t *\n\t * @internal\n\t */\n\tpublic readonly joinConfig: JoinConfig;\n\n\t/**\n\t * The two packets needed to successfully establish a voice connection. They are received\n\t * from the main Discord gateway after signalling to change the voice state.\n\t */\n\tprivate readonly packets: {\n\t\tserver: GatewayVoiceServerUpdateDispatchData | undefined;\n\t\tstate: GatewayVoiceStateUpdateDispatchData | undefined;\n\t};\n\n\t/**\n\t * The receiver of this voice connection. You should join the voice channel with `selfDeaf` set\n\t * to false for this feature to work properly.\n\t */\n\tpublic readonly receiver: VoiceReceiver;\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: null | ((message: string) => void);\n\n\t/**\n\t * Creates a new voice connection.\n\t *\n\t * @param joinConfig - The data required to establish the voice connection\n\t * @param options - The options used to create this voice connection\n\t */\n\tpublic constructor(joinConfig: JoinConfig, { debug, adapterCreator }: CreateVoiceConnectionOptions) {\n\t\tsuper();\n\n\t\tthis.debug = debug ? (message: string) => this.emit('debug', message) : null;\n\t\tthis.rejoinAttempts = 0;\n\n\t\tthis.receiver = new VoiceReceiver(this);\n\n\t\tthis.onNetworkingClose = this.onNetworkingClose.bind(this);\n\t\tthis.onNetworkingStateChange = this.onNetworkingStateChange.bind(this);\n\t\tthis.onNetworkingError = this.onNetworkingError.bind(this);\n\t\tthis.onNetworkingDebug = this.onNetworkingDebug.bind(this);\n\n\t\tconst adapter = adapterCreator({\n\t\t\tonVoiceServerUpdate: (data) => this.addServerPacket(data),\n\t\t\tonVoiceStateUpdate: (data) => this.addStatePacket(data),\n\t\t\tdestroy: () => this.destroy(false),\n\t\t});\n\n\t\tthis._state = { status: VoiceConnectionStatus.Signalling, adapter };\n\n\t\tthis.packets = {\n\t\t\tserver: undefined,\n\t\t\tstate: undefined,\n\t\t};\n\n\t\tthis.joinConfig = joinConfig;\n\t}\n\n\t/**\n\t * The current state of the voice connection.\n\t */\n\tpublic get state() {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * Updates the state of the voice connection, performing clean-up operations where necessary.\n\t */\n\tpublic set state(newState: VoiceConnectionState) {\n\t\tconst oldState = this._state;\n\t\tconst oldNetworking = Reflect.get(oldState, 'networking') as Networking | undefined;\n\t\tconst newNetworking = Reflect.get(newState, 'networking') as Networking | undefined;\n\n\t\tconst oldSubscription = Reflect.get(oldState, 'subscription') as PlayerSubscription | undefined;\n\t\tconst newSubscription = Reflect.get(newState, 'subscription') as PlayerSubscription | undefined;\n\n\t\tif (oldNetworking !== newNetworking) {\n\t\t\tif (oldNetworking) {\n\t\t\t\toldNetworking.on('error', noop);\n\t\t\t\toldNetworking.off('debug', this.onNetworkingDebug);\n\t\t\t\toldNetworking.off('error', this.onNetworkingError);\n\t\t\t\toldNetworking.off('close', this.onNetworkingClose);\n\t\t\t\toldNetworking.off('stateChange', this.onNetworkingStateChange);\n\t\t\t\toldNetworking.destroy();\n\t\t\t}\n\t\t\tif (newNetworking) this.updateReceiveBindings(newNetworking.state, oldNetworking?.state);\n\t\t}\n\n\t\tif (newState.status === VoiceConnectionStatus.Ready) {\n\t\t\tthis.rejoinAttempts = 0;\n\t\t} else if (newState.status === VoiceConnectionStatus.Destroyed) {\n\t\t\tfor (const stream of this.receiver.subscriptions.values()) {\n\t\t\t\tif (!stream.destroyed) stream.destroy();\n\t\t\t}\n\t\t}\n\n\t\t// If destroyed, the adapter can also be destroyed so it can be cleaned up by the user\n\t\tif (oldState.status !== VoiceConnectionStatus.Destroyed && newState.status === VoiceConnectionStatus.Destroyed) {\n\t\t\toldState.adapter.destroy();\n\t\t}\n\n\t\tthis._state = newState;\n\n\t\tif (oldSubscription && oldSubscription !== newSubscription) {\n\t\t\toldSubscription.unsubscribe();\n\t\t}\n\n\t\tthis.emit('stateChange', oldState, newState);\n\t\tif (oldState.status !== newState.status) {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\t\tthis.emit(newState.status, oldState, newState as any);\n\t\t}\n\t}\n\n\t/**\n\t * Registers a `VOICE_SERVER_UPDATE` packet to the voice connection. This will cause it to reconnect using the\n\t * new data provided in the packet.\n\t *\n\t * @param packet - The received `VOICE_SERVER_UPDATE` packet\n\t */\n\tprivate addServerPacket(packet: GatewayVoiceServerUpdateDispatchData) {\n\t\tthis.packets.server = packet;\n\t\tif (packet.endpoint) {\n\t\t\tthis.configureNetworking();\n\t\t} else if (this.state.status !== VoiceConnectionStatus.Destroyed) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.EndpointRemoved,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Registers a `VOICE_STATE_UPDATE` packet to the voice connection. Most importantly, it stores the id of the\n\t * channel that the client is connected to.\n\t *\n\t * @param packet - The received `VOICE_STATE_UPDATE` packet\n\t */\n\tprivate addStatePacket(packet: GatewayVoiceStateUpdateDispatchData) {\n\t\tthis.packets.state = packet;\n\n\t\tif (typeof packet.self_deaf !== 'undefined') this.joinConfig.selfDeaf = packet.self_deaf;\n\t\tif (typeof packet.self_mute !== 'undefined') this.joinConfig.selfMute = packet.self_mute;\n\t\tif (packet.channel_id) this.joinConfig.channelId = packet.channel_id;\n\t\t/*\n\t\t\tthe channel_id being null doesn't necessarily mean it was intended for the client to leave the voice channel\n\t\t\tas it may have disconnected due to network failure. This will be gracefully handled once the voice websocket\n\t\t\tdies, and then it is up to the user to decide how they wish to handle this.\n\t\t*/\n\t}\n\n\t/**\n\t * Called when the networking state changes, and the new ws/udp packet/message handlers need to be rebound\n\t * to the new instances.\n\t * @param newState - The new networking state\n\t * @param oldState - The old networking state, if there is one\n\t */\n\tprivate updateReceiveBindings(newState: NetworkingState, oldState?: NetworkingState) {\n\t\tconst oldWs = Reflect.get(oldState ?? {}, 'ws') as VoiceWebSocket | undefined;\n\t\tconst newWs = Reflect.get(newState, 'ws') as VoiceWebSocket | undefined;\n\t\tconst oldUdp = Reflect.get(oldState ?? {}, 'udp') as VoiceUDPSocket | undefined;\n\t\tconst newUdp = Reflect.get(newState, 'udp') as VoiceUDPSocket | undefined;\n\n\t\tif (oldWs !== newWs) {\n\t\t\toldWs?.off('packet', this.receiver.onWsPacket);\n\t\t\tnewWs?.on('packet', this.receiver.onWsPacket);\n\t\t}\n\n\t\tif (oldUdp !== newUdp) {\n\t\t\toldUdp?.off('message', this.receiver.onUdpMessage);\n\t\t\tnewUdp?.on('message', this.receiver.onUdpMessage);\n\t\t}\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\tthis.receiver.connectionData = Reflect.get(newState, 'connectionData') ?? {};\n\t}\n\n\t/**\n\t * Attempts to configure a networking instance for this voice connection using the received packets.\n\t * Both packets are required, and any existing networking instance will be destroyed.\n\t *\n\t * @remarks\n\t * This is called when the voice server of the connection changes, e.g. if the bot is moved into a\n\t * different channel in the same guild but has a different voice server. In this instance, the connection\n\t * needs to be re-established to the new voice server.\n\t *\n\t * The connection will transition to the Connecting state when this is called.\n\t */\n\tpublic configureNetworking() {\n\t\tconst { server, state } = this.packets;\n\t\tif (!server || !state || this.state.status === VoiceConnectionStatus.Destroyed || !server.endpoint) return;\n\n\t\tconst networking = new Networking(\n\t\t\t{\n\t\t\t\tendpoint: server.endpoint,\n\t\t\t\tserverId: server.guild_id,\n\t\t\t\ttoken: server.token,\n\t\t\t\tsessionId: state.session_id,\n\t\t\t\tuserId: state.user_id,\n\t\t\t},\n\t\t\tBoolean(this.debug),\n\t\t);\n\n\t\tnetworking.once('close', this.onNetworkingClose);\n\t\tnetworking.on('stateChange', this.onNetworkingStateChange);\n\t\tnetworking.on('error', this.onNetworkingError);\n\t\tnetworking.on('debug', this.onNetworkingDebug);\n\n\t\tthis.state = {\n\t\t\t...this.state,\n\t\t\tstatus: VoiceConnectionStatus.Connecting,\n\t\t\tnetworking,\n\t\t};\n\t}\n\n\t/**\n\t * Called when the networking instance for this connection closes. If the close code is 4014 (do not reconnect),\n\t * the voice connection will transition to the Disconnected state which will store the close code. You can\n\t * decide whether or not to reconnect when this occurs by listening for the state change and calling reconnect().\n\t *\n\t * @remarks\n\t * If the close code was anything other than 4014, it is likely that the closing was not intended, and so the\n\t * VoiceConnection will signal to Discord that it would like to rejoin the channel. This automatically attempts\n\t * to re-establish the connection. This would be seen as a transition from the Ready state to the Signalling state.\n\t *\n\t * @param code - The close code\n\t */\n\tprivate onNetworkingClose(code: number) {\n\t\tif (this.state.status === VoiceConnectionStatus.Destroyed) return;\n\t\t// If networking closes, try to connect to the voice channel again.\n\t\tif (code === 4014) {\n\t\t\t// Disconnected - networking is already destroyed here\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.WebSocketClose,\n\t\t\t\tcloseCode: code,\n\t\t\t};\n\t\t} else {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Signalling,\n\t\t\t};\n\t\t\tthis.rejoinAttempts++;\n\t\t\tif (!this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) {\n\t\t\t\tthis.state = {\n\t\t\t\t\t...this.state,\n\t\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Called when the state of the networking instance changes. This is used to derive the state of the voice connection.\n\t *\n\t * @param oldState - The previous state\n\t * @param newState - The new state\n\t */\n\tprivate onNetworkingStateChange(oldState: NetworkingState, newState: NetworkingState) {\n\t\tthis.updateReceiveBindings(newState, oldState);\n\t\tif (oldState.code === newState.code) return;\n\t\tif (this.state.status !== VoiceConnectionStatus.Connecting && this.state.status !== VoiceConnectionStatus.Ready)\n\t\t\treturn;\n\n\t\tif (newState.code === NetworkingStatusCode.Ready) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Ready,\n\t\t\t};\n\t\t} else if (newState.code !== NetworkingStatusCode.Closed) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Connecting,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Propagates errors from the underlying network instance.\n\t *\n\t * @param error - The error to propagate\n\t */\n\tprivate onNetworkingError(error: Error) {\n\t\tthis.emit('error', error);\n\t}\n\n\t/**\n\t * Propagates debug messages from the underlying network instance.\n\t *\n\t * @param message - The debug message to propagate\n\t */\n\tprivate onNetworkingDebug(message: string) {\n\t\tthis.debug?.(`[NW] ${message}`);\n\t}\n\n\t/**\n\t * Prepares an audio packet for dispatch.\n\t *\n\t * @param buffer - The Opus packet to prepare\n\t */\n\tpublic prepareAudioPacket(buffer: Buffer) {\n\t\tconst state = this.state;\n\t\tif (state.status !== VoiceConnectionStatus.Ready) return;\n\t\treturn state.networking.prepareAudioPacket(buffer);\n\t}\n\n\t/**\n\t * Dispatches the previously prepared audio packet (if any)\n\t */\n\tpublic dispatchAudio() {\n\t\tconst state = this.state;\n\t\tif (state.status !== VoiceConnectionStatus.Ready) return;\n\t\treturn state.networking.dispatchAudio();\n\t}\n\n\t/**\n\t * Prepares an audio packet and dispatches it immediately.\n\t *\n\t * @param buffer - The Opus packet to play\n\t */\n\tpublic playOpusPacket(buffer: Buffer) {\n\t\tconst state = this.state;\n\t\tif (state.status !== VoiceConnectionStatus.Ready) return;\n\t\tstate.networking.prepareAudioPacket(buffer);\n\t\treturn state.networking.dispatchAudio();\n\t}\n\n\t/**\n\t * Destroys the VoiceConnection, preventing it from connecting to voice again.\n\t * This method should be called when you no longer require the VoiceConnection to\n\t * prevent memory leaks.\n\t *\n\t * @param adapterAvailable - Whether the adapter can be used\n\t */\n\tpublic destroy(adapterAvailable = true) {\n\t\tif (this.state.status === VoiceConnectionStatus.Destroyed) {\n\t\t\tthrow new Error('Cannot destroy VoiceConnection - it has already been destroyed');\n\t\t}\n\t\tif (getVoiceConnection(this.joinConfig.guildId, this.joinConfig.group) === this) {\n\t\t\tuntrackVoiceConnection(this);\n\t\t}\n\t\tif (adapterAvailable) {\n\t\t\tthis.state.adapter.sendPayload(createJoinVoiceChannelPayload({ ...this.joinConfig, channelId: null }));\n\t\t}\n\t\tthis.state = {\n\t\t\tstatus: VoiceConnectionStatus.Destroyed,\n\t\t};\n\t}\n\n\t/**\n\t * Disconnects the VoiceConnection, allowing the possibility of rejoining later on.\n\t *\n\t * @returns `true` if the connection was successfully disconnected\n\t */\n\tpublic disconnect() {\n\t\tif (\n\t\t\tthis.state.status === VoiceConnectionStatus.Destroyed ||\n\t\t\tthis.state.status === VoiceConnectionStatus.Signalling\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tthis.joinConfig.channelId = null;\n\t\tif (!this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) {\n\t\t\tthis.state = {\n\t\t\t\tadapter: this.state.adapter,\n\t\t\t\tsubscription: this.state.subscription,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t\t};\n\t\t\treturn false;\n\t\t}\n\t\tthis.state = {\n\t\t\tadapter: this.state.adapter,\n\t\t\treason: VoiceConnectionDisconnectReason.Manual,\n\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t};\n\t\treturn true;\n\t}\n\n\t/**\n\t * Attempts to rejoin (better explanation soon:tm:)\n\t *\n\t * @remarks\n\t * Calling this method successfully will automatically increment the `rejoinAttempts` counter,\n\t * which you can use to inform whether or not you'd like to keep attempting to reconnect your\n\t * voice connection.\n\t *\n\t * A state transition from Disconnected to Signalling will be observed when this is called.\n\t */\n\tpublic rejoin(joinConfig?: Omit) {\n\t\tif (this.state.status === VoiceConnectionStatus.Destroyed) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst notReady = this.state.status !== VoiceConnectionStatus.Ready;\n\n\t\tif (notReady) this.rejoinAttempts++;\n\t\tObject.assign(this.joinConfig, joinConfig);\n\t\tif (this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) {\n\t\t\tif (notReady) {\n\t\t\t\tthis.state = {\n\t\t\t\t\t...this.state,\n\t\t\t\t\tstatus: VoiceConnectionStatus.Signalling,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tthis.state = {\n\t\t\tadapter: this.state.adapter,\n\t\t\tsubscription: this.state.subscription,\n\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t};\n\t\treturn false;\n\t}\n\n\t/**\n\t * Updates the speaking status of the voice connection. This is used when audio players are done playing audio,\n\t * and need to signal that the connection is no longer playing audio.\n\t *\n\t * @param enabled - Whether or not to show as speaking\n\t */\n\tpublic setSpeaking(enabled: boolean) {\n\t\tif (this.state.status !== VoiceConnectionStatus.Ready) return false;\n\t\treturn this.state.networking.setSpeaking(enabled);\n\t}\n\n\t/**\n\t * Subscribes to an audio player, allowing the player to play audio on this voice connection.\n\t *\n\t * @param player - The audio player to subscribe to\n\t *\n\t * @returns The created subscription\n\t */\n\tpublic subscribe(player: AudioPlayer) {\n\t\tif (this.state.status === VoiceConnectionStatus.Destroyed) return;\n\n\t\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\t\tconst subscription = player['subscribe'](this);\n\n\t\tthis.state = {\n\t\t\t...this.state,\n\t\t\tsubscription,\n\t\t};\n\n\t\treturn subscription;\n\t}\n\n\t/**\n\t * The latest ping (in milliseconds) for the WebSocket connection and audio playback for this voice\n\t * connection, if this data is available.\n\t *\n\t * @remarks\n\t * For this data to be available, the VoiceConnection must be in the Ready state, and its underlying\n\t * WebSocket connection and UDP socket must have had at least one ping-pong exchange.\n\t */\n\tpublic get ping() {\n\t\tif (\n\t\t\tthis.state.status === VoiceConnectionStatus.Ready &&\n\t\t\tthis.state.networking.state.code === NetworkingStatusCode.Ready\n\t\t) {\n\t\t\treturn {\n\t\t\t\tws: this.state.networking.state.ws.ping,\n\t\t\t\tudp: this.state.networking.state.udp.ping,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tws: undefined,\n\t\t\tudp: undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Called when a subscription of this voice connection to an audio player is removed.\n\t *\n\t * @param subscription - The removed subscription\n\t */\n\tprivate onSubscriptionRemoved(subscription: PlayerSubscription) {\n\t\tif (this.state.status !== VoiceConnectionStatus.Destroyed && this.state.subscription === subscription) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tsubscription: undefined,\n\t\t\t};\n\t\t}\n\t}\n}\n\n/**\n * Creates a new voice connection.\n *\n * @param joinConfig - The data required to establish the voice connection\n * @param options - The options to use when joining the voice channel\n */\nexport function createVoiceConnection(joinConfig: JoinConfig, options: CreateVoiceConnectionOptions) {\n\tconst payload = createJoinVoiceChannelPayload(joinConfig);\n\tconst existing = getVoiceConnection(joinConfig.guildId, joinConfig.group);\n\tif (existing && existing.state.status !== VoiceConnectionStatus.Destroyed) {\n\t\tif (existing.state.status === VoiceConnectionStatus.Disconnected) {\n\t\t\texisting.rejoin({\n\t\t\t\tchannelId: joinConfig.channelId,\n\t\t\t\tselfDeaf: joinConfig.selfDeaf,\n\t\t\t\tselfMute: joinConfig.selfMute,\n\t\t\t});\n\t\t} else if (!existing.state.adapter.sendPayload(payload)) {\n\t\t\texisting.state = {\n\t\t\t\t...existing.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t\t};\n\t\t}\n\t\treturn existing;\n\t}\n\n\tconst voiceConnection = new VoiceConnection(joinConfig, options);\n\ttrackVoiceConnection(voiceConnection);\n\tif (voiceConnection.state.status !== VoiceConnectionStatus.Destroyed) {\n\t\tif (!voiceConnection.state.adapter.sendPayload(payload)) {\n\t\t\tvoiceConnection.state = {\n\t\t\t\t...voiceConnection.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t\t};\n\t\t}\n\t}\n\treturn voiceConnection;\n}\n","import { GatewayOpcodes } from 'discord-api-types/v10';\nimport type { VoiceConnection } from './VoiceConnection';\nimport type { AudioPlayer } from './audio';\n\nexport interface JoinConfig {\n\tguildId: string;\n\tchannelId: string | null;\n\tselfDeaf: boolean;\n\tselfMute: boolean;\n\tgroup: string;\n}\n\n/**\n * Sends a voice state update to the main websocket shard of a guild, to indicate joining/leaving/moving across\n * voice channels.\n *\n * @param config - The configuration to use when joining the voice channel\n */\nexport function createJoinVoiceChannelPayload(config: JoinConfig) {\n\treturn {\n\t\top: GatewayOpcodes.VoiceStateUpdate,\n\t\td: {\n\t\t\tguild_id: config.guildId,\n\t\t\tchannel_id: config.channelId,\n\t\t\tself_deaf: config.selfDeaf,\n\t\t\tself_mute: config.selfMute,\n\t\t},\n\t};\n}\n\n// Voice Connections\nconst groups = new Map>();\ngroups.set('default', new Map());\n\nfunction getOrCreateGroup(group: string) {\n\tconst existing = groups.get(group);\n\tif (existing) return existing;\n\tconst map = new Map();\n\tgroups.set(group, map);\n\treturn map;\n}\n\n/**\n * Retrieves the map of group names to maps of voice connections. By default, all voice connections\n * are created under the 'default' group.\n *\n * @returns The group map\n */\nexport function getGroups() {\n\treturn groups;\n}\n\n/**\n * Retrieves all the voice connections under the 'default' group.\n *\n * @param group - The group to look up\n *\n * @returns The map of voice connections\n */\nexport function getVoiceConnections(group?: 'default'): Map;\n\n/**\n * Retrieves all the voice connections under the given group name.\n *\n * @param group - The group to look up\n *\n * @returns The map of voice connections\n */\nexport function getVoiceConnections(group: string): Map | undefined;\n\n/**\n * Retrieves all the voice connections under the given group name. Defaults to the 'default' group.\n *\n * @param group - The group to look up\n *\n * @returns The map of voice connections\n */\nexport function getVoiceConnections(group = 'default') {\n\treturn groups.get(group);\n}\n\n/**\n * Finds a voice connection with the given guild id and group. Defaults to the 'default' group.\n *\n * @param guildId - The guild id of the voice connection\n * @param group - the group that the voice connection was registered with\n *\n * @returns The voice connection, if it exists\n */\nexport function getVoiceConnection(guildId: string, group = 'default') {\n\treturn getVoiceConnections(group)?.get(guildId);\n}\n\nexport function untrackVoiceConnection(voiceConnection: VoiceConnection) {\n\treturn getVoiceConnections(voiceConnection.joinConfig.group)?.delete(voiceConnection.joinConfig.guildId);\n}\n\nexport function trackVoiceConnection(voiceConnection: VoiceConnection) {\n\treturn getOrCreateGroup(voiceConnection.joinConfig.group).set(voiceConnection.joinConfig.guildId, voiceConnection);\n}\n\n// Audio Players\n\n// Each audio packet is 20ms long\nconst FRAME_LENGTH = 20;\n\nlet audioCycleInterval: NodeJS.Timeout | undefined;\nlet nextTime = -1;\n\n/**\n * A list of created audio players that are still active and haven't been destroyed.\n */\nconst audioPlayers: AudioPlayer[] = [];\n\n/**\n * Called roughly every 20 milliseconds. Dispatches audio from all players, and then gets the players to prepare\n * the next audio frame.\n */\nfunction audioCycleStep() {\n\tif (nextTime === -1) return;\n\n\tnextTime += FRAME_LENGTH;\n\tconst available = audioPlayers.filter((player) => player.checkPlayable());\n\n\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\tavailable.forEach((player) => player['_stepDispatch']());\n\n\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\tprepareNextAudioFrame(available);\n}\n\n/**\n * Recursively gets the players that have been passed as parameters to prepare audio frames that can be played\n * at the start of the next cycle.\n */\nfunction prepareNextAudioFrame(players: AudioPlayer[]) {\n\tconst nextPlayer = players.shift();\n\n\tif (!nextPlayer) {\n\t\tif (nextTime !== -1) {\n\t\t\taudioCycleInterval = setTimeout(() => audioCycleStep(), nextTime - Date.now());\n\t\t}\n\t\treturn;\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\tnextPlayer['_stepPrepare']();\n\n\t// setImmediate to avoid long audio player chains blocking other scheduled tasks\n\tsetImmediate(() => prepareNextAudioFrame(players));\n}\n\n/**\n * Checks whether or not the given audio player is being driven by the data store clock.\n *\n * @param target - The target to test for\n *\n * @returns `true` if it is being tracked, `false` otherwise\n */\nexport function hasAudioPlayer(target: AudioPlayer) {\n\treturn audioPlayers.includes(target);\n}\n\n/**\n * Adds an audio player to the data store tracking list, if it isn't already there.\n *\n * @param player - The player to track\n */\nexport function addAudioPlayer(player: AudioPlayer) {\n\tif (hasAudioPlayer(player)) return player;\n\taudioPlayers.push(player);\n\tif (audioPlayers.length === 1) {\n\t\tnextTime = Date.now();\n\t\tsetImmediate(() => audioCycleStep());\n\t}\n\treturn player;\n}\n\n/**\n * Removes an audio player from the data store tracking list, if it is present there.\n */\nexport function deleteAudioPlayer(player: AudioPlayer) {\n\tconst index = audioPlayers.indexOf(player);\n\tif (index === -1) return;\n\taudioPlayers.splice(index, 1);\n\tif (audioPlayers.length === 0) {\n\t\tnextTime = -1;\n\t\tif (typeof audioCycleInterval !== 'undefined') clearTimeout(audioCycleInterval);\n\t}\n}\n","/* eslint-disable @typescript-eslint/method-signature-style */\nimport { EventEmitter } from 'node:events';\nimport { VoiceOpcodes } from 'discord-api-types/voice/v4';\nimport type { CloseEvent } from 'ws';\nimport { VoiceUDPSocket } from './VoiceUDPSocket';\nimport { VoiceWebSocket } from './VoiceWebSocket';\nimport * as secretbox from '../util/Secretbox';\nimport { noop } from '../util/util';\n\n// The number of audio channels required by Discord\nconst CHANNELS = 2;\nconst TIMESTAMP_INC = (48000 / 100) * CHANNELS;\nconst MAX_NONCE_SIZE = 2 ** 32 - 1;\n\nexport const SUPPORTED_ENCRYPTION_MODES = ['xsalsa20_poly1305_lite', 'xsalsa20_poly1305_suffix', 'xsalsa20_poly1305'];\n\n/**\n * The different statuses that a networking instance can hold. The order\n * of the states between OpeningWs and Ready is chronological (first the\n * instance enters OpeningWs, then it enters Identifying etc.)\n */\nexport enum NetworkingStatusCode {\n\tOpeningWs,\n\tIdentifying,\n\tUdpHandshaking,\n\tSelectingProtocol,\n\tReady,\n\tResuming,\n\tClosed,\n}\n\n/**\n * The initial Networking state. Instances will be in this state when a WebSocket connection to a Discord\n * voice gateway is being opened.\n */\nexport interface NetworkingOpeningWsState {\n\tcode: NetworkingStatusCode.OpeningWs;\n\tws: VoiceWebSocket;\n\tconnectionOptions: ConnectionOptions;\n}\n\n/**\n * The state that a Networking instance will be in when it is attempting to authorize itself.\n */\nexport interface NetworkingIdentifyingState {\n\tcode: NetworkingStatusCode.Identifying;\n\tws: VoiceWebSocket;\n\tconnectionOptions: ConnectionOptions;\n}\n\n/**\n * The state that a Networking instance will be in when opening a UDP connection to the IP and port provided\n * by Discord, as well as performing IP discovery.\n */\nexport interface NetworkingUdpHandshakingState {\n\tcode: NetworkingStatusCode.UdpHandshaking;\n\tws: VoiceWebSocket;\n\tudp: VoiceUDPSocket;\n\tconnectionOptions: ConnectionOptions;\n\tconnectionData: Pick;\n}\n\n/**\n * The state that a Networking instance will be in when selecting an encryption protocol for audio packets.\n */\nexport interface NetworkingSelectingProtocolState {\n\tcode: NetworkingStatusCode.SelectingProtocol;\n\tws: VoiceWebSocket;\n\tudp: VoiceUDPSocket;\n\tconnectionOptions: ConnectionOptions;\n\tconnectionData: Pick;\n}\n\n/**\n * The state that a Networking instance will be in when it has a fully established connection to a Discord\n * voice server.\n */\nexport interface NetworkingReadyState {\n\tcode: NetworkingStatusCode.Ready;\n\tws: VoiceWebSocket;\n\tudp: VoiceUDPSocket;\n\tconnectionOptions: ConnectionOptions;\n\tconnectionData: ConnectionData;\n\tpreparedPacket?: Buffer;\n}\n\n/**\n * The state that a Networking instance will be in when its connection has been dropped unexpectedly, and it\n * is attempting to resume an existing session.\n */\nexport interface NetworkingResumingState {\n\tcode: NetworkingStatusCode.Resuming;\n\tws: VoiceWebSocket;\n\tudp: VoiceUDPSocket;\n\tconnectionOptions: ConnectionOptions;\n\tconnectionData: ConnectionData;\n\tpreparedPacket?: Buffer;\n}\n\n/**\n * The state that a Networking instance will be in when it has been destroyed. It cannot be recovered from this\n * state.\n */\nexport interface NetworkingClosedState {\n\tcode: NetworkingStatusCode.Closed;\n}\n\n/**\n * The various states that a networking instance can be in.\n */\nexport type NetworkingState =\n\t| NetworkingOpeningWsState\n\t| NetworkingIdentifyingState\n\t| NetworkingUdpHandshakingState\n\t| NetworkingSelectingProtocolState\n\t| NetworkingReadyState\n\t| NetworkingResumingState\n\t| NetworkingClosedState;\n\n/**\n * Details required to connect to the Discord voice gateway. These details\n * are first received on the main bot gateway, in the form of VOICE_SERVER_UPDATE\n * and VOICE_STATE_UPDATE packets.\n */\ninterface ConnectionOptions {\n\tserverId: string;\n\tuserId: string;\n\tsessionId: string;\n\ttoken: string;\n\tendpoint: string;\n}\n\n/**\n * Information about the current connection, e.g. which encryption mode is to be used on\n * the connection, timing information for playback of streams.\n */\nexport interface ConnectionData {\n\tssrc: number;\n\tencryptionMode: string;\n\tsecretKey: Uint8Array;\n\tsequence: number;\n\ttimestamp: number;\n\tpacketsPlayed: number;\n\tnonce: number;\n\tnonceBuffer: Buffer;\n\tspeaking: boolean;\n}\n\n/**\n * An empty buffer that is reused in packet encryption by many different networking instances.\n */\nconst nonce = Buffer.alloc(24);\n\nexport interface Networking extends EventEmitter {\n\t/**\n\t * Debug event for Networking.\n\t *\n\t * @event\n\t */\n\ton(event: 'debug', listener: (message: string) => void): this;\n\ton(event: 'error', listener: (error: Error) => void): this;\n\ton(event: 'stateChange', listener: (oldState: NetworkingState, newState: NetworkingState) => void): this;\n\ton(event: 'close', listener: (code: number) => void): this;\n}\n\n/**\n * Stringifies a NetworkingState.\n *\n * @param state - The state to stringify\n */\nfunction stringifyState(state: NetworkingState) {\n\treturn JSON.stringify({\n\t\t...state,\n\t\tws: Reflect.has(state, 'ws'),\n\t\tudp: Reflect.has(state, 'udp'),\n\t});\n}\n\n/**\n * Chooses an encryption mode from a list of given options. Chooses the most preferred option.\n *\n * @param options - The available encryption options\n */\nfunction chooseEncryptionMode(options: string[]): string {\n\tconst option = options.find((option) => SUPPORTED_ENCRYPTION_MODES.includes(option));\n\tif (!option) {\n\t\tthrow new Error(`No compatible encryption modes. Available include: ${options.join(', ')}`);\n\t}\n\treturn option;\n}\n\n/**\n * Returns a random number that is in the range of n bits.\n *\n * @param n - The number of bits\n */\nfunction randomNBit(n: number) {\n\treturn Math.floor(Math.random() * 2 ** n);\n}\n\n/**\n * Manages the networking required to maintain a voice connection and dispatch audio packets\n */\nexport class Networking extends EventEmitter {\n\tprivate _state: NetworkingState;\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: null | ((message: string) => void);\n\n\t/**\n\t * Creates a new Networking instance.\n\t */\n\tpublic constructor(options: ConnectionOptions, debug: boolean) {\n\t\tsuper();\n\n\t\tthis.onWsOpen = this.onWsOpen.bind(this);\n\t\tthis.onChildError = this.onChildError.bind(this);\n\t\tthis.onWsPacket = this.onWsPacket.bind(this);\n\t\tthis.onWsClose = this.onWsClose.bind(this);\n\t\tthis.onWsDebug = this.onWsDebug.bind(this);\n\t\tthis.onUdpDebug = this.onUdpDebug.bind(this);\n\t\tthis.onUdpClose = this.onUdpClose.bind(this);\n\n\t\tthis.debug = debug ? (message: string) => this.emit('debug', message) : null;\n\n\t\tthis._state = {\n\t\t\tcode: NetworkingStatusCode.OpeningWs,\n\t\t\tws: this.createWebSocket(options.endpoint),\n\t\t\tconnectionOptions: options,\n\t\t};\n\t}\n\n\t/**\n\t * Destroys the Networking instance, transitioning it into the Closed state.\n\t */\n\tpublic destroy() {\n\t\tthis.state = {\n\t\t\tcode: NetworkingStatusCode.Closed,\n\t\t};\n\t}\n\n\t/**\n\t * The current state of the networking instance.\n\t */\n\tpublic get state(): NetworkingState {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * Sets a new state for the networking instance, performing clean-up operations where necessary.\n\t */\n\tpublic set state(newState: NetworkingState) {\n\t\tconst oldWs = Reflect.get(this._state, 'ws') as VoiceWebSocket | undefined;\n\t\tconst newWs = Reflect.get(newState, 'ws') as VoiceWebSocket | undefined;\n\t\tif (oldWs && oldWs !== newWs) {\n\t\t\t// The old WebSocket is being freed - remove all handlers from it\n\t\t\toldWs.off('debug', this.onWsDebug);\n\t\t\toldWs.on('error', noop);\n\t\t\toldWs.off('error', this.onChildError);\n\t\t\toldWs.off('open', this.onWsOpen);\n\t\t\toldWs.off('packet', this.onWsPacket);\n\t\t\toldWs.off('close', this.onWsClose);\n\t\t\toldWs.destroy();\n\t\t}\n\n\t\tconst oldUdp = Reflect.get(this._state, 'udp') as VoiceUDPSocket | undefined;\n\t\tconst newUdp = Reflect.get(newState, 'udp') as VoiceUDPSocket | undefined;\n\n\t\tif (oldUdp && oldUdp !== newUdp) {\n\t\t\toldUdp.on('error', noop);\n\t\t\toldUdp.off('error', this.onChildError);\n\t\t\toldUdp.off('close', this.onUdpClose);\n\t\t\toldUdp.off('debug', this.onUdpDebug);\n\t\t\toldUdp.destroy();\n\t\t}\n\n\t\tconst oldState = this._state;\n\t\tthis._state = newState;\n\t\tthis.emit('stateChange', oldState, newState);\n\n\t\tthis.debug?.(`state change:\\nfrom ${stringifyState(oldState)}\\nto ${stringifyState(newState)}`);\n\t}\n\n\t/**\n\t * Creates a new WebSocket to a Discord Voice gateway.\n\t *\n\t * @param endpoint - The endpoint to connect to\n\t * @param debug - Whether to enable debug logging\n\t */\n\tprivate createWebSocket(endpoint: string) {\n\t\tconst ws = new VoiceWebSocket(`wss://${endpoint}?v=4`, Boolean(this.debug));\n\n\t\tws.on('error', this.onChildError);\n\t\tws.once('open', this.onWsOpen);\n\t\tws.on('packet', this.onWsPacket);\n\t\tws.once('close', this.onWsClose);\n\t\tws.on('debug', this.onWsDebug);\n\n\t\treturn ws;\n\t}\n\n\t/**\n\t * Propagates errors from the children VoiceWebSocket and VoiceUDPSocket.\n\t *\n\t * @param error - The error that was emitted by a child\n\t */\n\tprivate onChildError(error: Error) {\n\t\tthis.emit('error', error);\n\t}\n\n\t/**\n\t * Called when the WebSocket opens. Depending on the state that the instance is in,\n\t * it will either identify with a new session, or it will attempt to resume an existing session.\n\t */\n\tprivate onWsOpen() {\n\t\tif (this.state.code === NetworkingStatusCode.OpeningWs) {\n\t\t\tconst packet = {\n\t\t\t\top: VoiceOpcodes.Identify,\n\t\t\t\td: {\n\t\t\t\t\tserver_id: this.state.connectionOptions.serverId,\n\t\t\t\t\tuser_id: this.state.connectionOptions.userId,\n\t\t\t\t\tsession_id: this.state.connectionOptions.sessionId,\n\t\t\t\t\ttoken: this.state.connectionOptions.token,\n\t\t\t\t},\n\t\t\t};\n\t\t\tthis.state.ws.sendPacket(packet);\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Identifying,\n\t\t\t};\n\t\t} else if (this.state.code === NetworkingStatusCode.Resuming) {\n\t\t\tconst packet = {\n\t\t\t\top: VoiceOpcodes.Resume,\n\t\t\t\td: {\n\t\t\t\t\tserver_id: this.state.connectionOptions.serverId,\n\t\t\t\t\tsession_id: this.state.connectionOptions.sessionId,\n\t\t\t\t\ttoken: this.state.connectionOptions.token,\n\t\t\t\t},\n\t\t\t};\n\t\t\tthis.state.ws.sendPacket(packet);\n\t\t}\n\t}\n\n\t/**\n\t * Called when the WebSocket closes. Based on the reason for closing (given by the code parameter),\n\t * the instance will either attempt to resume, or enter the closed state and emit a 'close' event\n\t * with the close code, allowing the user to decide whether or not they would like to reconnect.\n\t *\n\t * @param code - The close code\n\t */\n\tprivate onWsClose({ code }: CloseEvent) {\n\t\tconst canResume = code === 4015 || code < 4000;\n\t\tif (canResume && this.state.code === NetworkingStatusCode.Ready) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Resuming,\n\t\t\t\tws: this.createWebSocket(this.state.connectionOptions.endpoint),\n\t\t\t};\n\t\t} else if (this.state.code !== NetworkingStatusCode.Closed) {\n\t\t\tthis.destroy();\n\t\t\tthis.emit('close', code);\n\t\t}\n\t}\n\n\t/**\n\t * Called when the UDP socket has closed itself if it has stopped receiving replies from Discord.\n\t */\n\tprivate onUdpClose() {\n\t\tif (this.state.code === NetworkingStatusCode.Ready) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Resuming,\n\t\t\t\tws: this.createWebSocket(this.state.connectionOptions.endpoint),\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Called when a packet is received on the connection's WebSocket.\n\t *\n\t * @param packet - The received packet\n\t */\n\tprivate onWsPacket(packet: any) {\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\tif (packet.op === VoiceOpcodes.Hello && this.state.code !== NetworkingStatusCode.Closed) {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access\n\t\t\tthis.state.ws.setHeartbeatInterval(packet.d.heartbeat_interval);\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t} else if (packet.op === VoiceOpcodes.Ready && this.state.code === NetworkingStatusCode.Identifying) {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\t\tconst { ip, port, ssrc, modes } = packet.d;\n\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\t\tconst udp = new VoiceUDPSocket({ ip, port });\n\t\t\tudp.on('error', this.onChildError);\n\t\t\tudp.on('debug', this.onUdpDebug);\n\t\t\tudp.once('close', this.onUdpClose);\n\t\t\tudp\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\t\t\t.performIPDiscovery(ssrc)\n\t\t\t\t.then((localConfig) => {\n\t\t\t\t\tif (this.state.code !== NetworkingStatusCode.UdpHandshaking) return;\n\t\t\t\t\tthis.state.ws.sendPacket({\n\t\t\t\t\t\top: VoiceOpcodes.SelectProtocol,\n\t\t\t\t\t\td: {\n\t\t\t\t\t\t\tprotocol: 'udp',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\taddress: localConfig.ip,\n\t\t\t\t\t\t\t\tport: localConfig.port,\n\t\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\t\t\t\t\t\t\tmode: chooseEncryptionMode(modes),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tthis.state = {\n\t\t\t\t\t\t...this.state,\n\t\t\t\t\t\tcode: NetworkingStatusCode.SelectingProtocol,\n\t\t\t\t\t};\n\t\t\t\t})\n\t\t\t\t.catch((error: Error) => this.emit('error', error));\n\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.UdpHandshaking,\n\t\t\t\tudp,\n\t\t\t\tconnectionData: {\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\t\t\t\tssrc,\n\t\t\t\t},\n\t\t\t};\n\t\t} else if (\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\tpacket.op === VoiceOpcodes.SessionDescription &&\n\t\t\tthis.state.code === NetworkingStatusCode.SelectingProtocol\n\t\t) {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\t\tconst { mode: encryptionMode, secret_key: secretKey } = packet.d;\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Ready,\n\t\t\t\tconnectionData: {\n\t\t\t\t\t...this.state.connectionData,\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\t\t\t\tencryptionMode,\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\t\t\t\tsecretKey: new Uint8Array(secretKey),\n\t\t\t\t\tsequence: randomNBit(16),\n\t\t\t\t\ttimestamp: randomNBit(32),\n\t\t\t\t\tnonce: 0,\n\t\t\t\t\tnonceBuffer: Buffer.alloc(24),\n\t\t\t\t\tspeaking: false,\n\t\t\t\t\tpacketsPlayed: 0,\n\t\t\t\t},\n\t\t\t};\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t} else if (packet.op === VoiceOpcodes.Resumed && this.state.code === NetworkingStatusCode.Resuming) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Ready,\n\t\t\t};\n\t\t\tthis.state.connectionData.speaking = false;\n\t\t}\n\t}\n\n\t/**\n\t * Propagates debug messages from the child WebSocket.\n\t *\n\t * @param message - The emitted debug message\n\t */\n\tprivate onWsDebug(message: string) {\n\t\tthis.debug?.(`[WS] ${message}`);\n\t}\n\n\t/**\n\t * Propagates debug messages from the child UDPSocket.\n\t *\n\t * @param message - The emitted debug message\n\t */\n\tprivate onUdpDebug(message: string) {\n\t\tthis.debug?.(`[UDP] ${message}`);\n\t}\n\n\t/**\n\t * Prepares an Opus packet for playback. This includes attaching metadata to it and encrypting it.\n\t * It will be stored within the instance, and can be played by dispatchAudio()\n\t *\n\t * @remarks\n\t * Calling this method while there is already a prepared audio packet that has not yet been dispatched\n\t * will overwrite the existing audio packet. This should be avoided.\n\t *\n\t * @param opusPacket - The Opus packet to encrypt\n\t *\n\t * @returns The audio packet that was prepared\n\t */\n\tpublic prepareAudioPacket(opusPacket: Buffer) {\n\t\tconst state = this.state;\n\t\tif (state.code !== NetworkingStatusCode.Ready) return;\n\t\tstate.preparedPacket = this.createAudioPacket(opusPacket, state.connectionData);\n\t\treturn state.preparedPacket;\n\t}\n\n\t/**\n\t * Dispatches the audio packet previously prepared by prepareAudioPacket(opusPacket). The audio packet\n\t * is consumed and cannot be dispatched again.\n\t */\n\tpublic dispatchAudio() {\n\t\tconst state = this.state;\n\t\tif (state.code !== NetworkingStatusCode.Ready) return false;\n\t\tif (typeof state.preparedPacket !== 'undefined') {\n\t\t\tthis.playAudioPacket(state.preparedPacket);\n\t\t\tstate.preparedPacket = undefined;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Plays an audio packet, updating timing metadata used for playback.\n\t *\n\t * @param audioPacket - The audio packet to play\n\t */\n\tprivate playAudioPacket(audioPacket: Buffer) {\n\t\tconst state = this.state;\n\t\tif (state.code !== NetworkingStatusCode.Ready) return;\n\t\tconst { connectionData } = state;\n\t\tconnectionData.packetsPlayed++;\n\t\tconnectionData.sequence++;\n\t\tconnectionData.timestamp += TIMESTAMP_INC;\n\t\tif (connectionData.sequence >= 2 ** 16) connectionData.sequence = 0;\n\t\tif (connectionData.timestamp >= 2 ** 32) connectionData.timestamp = 0;\n\t\tthis.setSpeaking(true);\n\t\tstate.udp.send(audioPacket);\n\t}\n\n\t/**\n\t * Sends a packet to the voice gateway indicating that the client has start/stopped sending\n\t * audio.\n\t *\n\t * @param speaking - Whether or not the client should be shown as speaking\n\t */\n\tpublic setSpeaking(speaking: boolean) {\n\t\tconst state = this.state;\n\t\tif (state.code !== NetworkingStatusCode.Ready) return;\n\t\tif (state.connectionData.speaking === speaking) return;\n\t\tstate.connectionData.speaking = speaking;\n\t\tstate.ws.sendPacket({\n\t\t\top: VoiceOpcodes.Speaking,\n\t\t\td: {\n\t\t\t\tspeaking: speaking ? 1 : 0,\n\t\t\t\tdelay: 0,\n\t\t\t\tssrc: state.connectionData.ssrc,\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Creates a new audio packet from an Opus packet. This involves encrypting the packet,\n\t * then prepending a header that includes metadata.\n\t *\n\t * @param opusPacket - The Opus packet to prepare\n\t * @param connectionData - The current connection data of the instance\n\t */\n\tprivate createAudioPacket(opusPacket: Buffer, connectionData: ConnectionData) {\n\t\tconst packetBuffer = Buffer.alloc(12);\n\t\tpacketBuffer[0] = 0x80;\n\t\tpacketBuffer[1] = 0x78;\n\n\t\tconst { sequence, timestamp, ssrc } = connectionData;\n\n\t\tpacketBuffer.writeUIntBE(sequence, 2, 2);\n\t\tpacketBuffer.writeUIntBE(timestamp, 4, 4);\n\t\tpacketBuffer.writeUIntBE(ssrc, 8, 4);\n\n\t\tpacketBuffer.copy(nonce, 0, 0, 12);\n\t\treturn Buffer.concat([packetBuffer, ...this.encryptOpusPacket(opusPacket, connectionData)]);\n\t}\n\n\t/**\n\t * Encrypts an Opus packet using the format agreed upon by the instance and Discord.\n\t *\n\t * @param opusPacket - The Opus packet to encrypt\n\t * @param connectionData - The current connection data of the instance\n\t */\n\tprivate encryptOpusPacket(opusPacket: Buffer, connectionData: ConnectionData) {\n\t\tconst { secretKey, encryptionMode } = connectionData;\n\n\t\tif (encryptionMode === 'xsalsa20_poly1305_lite') {\n\t\t\tconnectionData.nonce++;\n\t\t\tif (connectionData.nonce > MAX_NONCE_SIZE) connectionData.nonce = 0;\n\t\t\tconnectionData.nonceBuffer.writeUInt32BE(connectionData.nonce, 0);\n\t\t\treturn [\n\t\t\t\tsecretbox.methods.close(opusPacket, connectionData.nonceBuffer, secretKey),\n\t\t\t\tconnectionData.nonceBuffer.slice(0, 4),\n\t\t\t];\n\t\t} else if (encryptionMode === 'xsalsa20_poly1305_suffix') {\n\t\t\tconst random = secretbox.methods.random(24, connectionData.nonceBuffer);\n\t\t\treturn [secretbox.methods.close(opusPacket, random, secretKey), random];\n\t\t}\n\t\treturn [secretbox.methods.close(opusPacket, nonce, secretKey)];\n\t}\n}\n","/* eslint-disable @typescript-eslint/method-signature-style */\nimport { createSocket, Socket } from 'node:dgram';\nimport { EventEmitter } from 'node:events';\nimport { isIPv4 } from 'node:net';\n\n/**\n * Stores an IP address and port. Used to store socket details for the local client as well as\n * for Discord.\n */\nexport interface SocketConfig {\n\tip: string;\n\tport: number;\n}\n\ninterface KeepAlive {\n\tvalue: number;\n\ttimestamp: number;\n}\n\n/**\n * Parses the response from Discord to aid with local IP discovery.\n *\n * @param message - The received message\n */\nexport function parseLocalPacket(message: Buffer): SocketConfig {\n\tconst packet = Buffer.from(message);\n\n\tconst ip = packet.slice(8, packet.indexOf(0, 8)).toString('utf-8');\n\n\tif (!isIPv4(ip)) {\n\t\tthrow new Error('Malformed IP address');\n\t}\n\n\tconst port = packet.readUInt16BE(packet.length - 2);\n\n\treturn { ip, port };\n}\n\n/**\n * The interval in milliseconds at which keep alive datagrams are sent.\n */\nconst KEEP_ALIVE_INTERVAL = 5e3;\n\n/**\n * The maximum number of keep alive packets which can be missed.\n */\nconst KEEP_ALIVE_LIMIT = 12;\n\n/**\n * The maximum value of the keep alive counter.\n */\nconst MAX_COUNTER_VALUE = 2 ** 32 - 1;\n\nexport interface VoiceUDPSocket extends EventEmitter {\n\ton(event: 'error', listener: (error: Error) => void): this;\n\ton(event: 'close', listener: () => void): this;\n\ton(event: 'debug', listener: (message: string) => void): this;\n\ton(event: 'message', listener: (message: Buffer) => void): this;\n}\n\n/**\n * Manages the UDP networking for a voice connection.\n */\nexport class VoiceUDPSocket extends EventEmitter {\n\t/**\n\t * The underlying network Socket for the VoiceUDPSocket.\n\t */\n\tprivate readonly socket: Socket;\n\n\t/**\n\t * The socket details for Discord (remote)\n\t */\n\tprivate readonly remote: SocketConfig;\n\n\t/**\n\t * A list of keep alives that are waiting to be acknowledged.\n\t */\n\tprivate readonly keepAlives: KeepAlive[];\n\n\t/**\n\t * The counter used in the keep alive mechanism.\n\t */\n\tprivate keepAliveCounter = 0;\n\n\t/**\n\t * The buffer used to write the keep alive counter into.\n\t */\n\tprivate readonly keepAliveBuffer: Buffer;\n\n\t/**\n\t * The Node.js interval for the keep-alive mechanism.\n\t */\n\tprivate readonly keepAliveInterval: NodeJS.Timeout;\n\n\t/**\n\t * The time taken to receive a response to keep alive messages.\n\t */\n\tpublic ping?: number;\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: null | ((message: string) => void);\n\n\t/**\n\t * Creates a new VoiceUDPSocket.\n\t *\n\t * @param remote - Details of the remote socket\n\t */\n\tpublic constructor(remote: SocketConfig, debug = false) {\n\t\tsuper();\n\t\tthis.socket = createSocket('udp4');\n\t\tthis.socket.on('error', (error: Error) => this.emit('error', error));\n\t\tthis.socket.on('message', (buffer: Buffer) => this.onMessage(buffer));\n\t\tthis.socket.on('close', () => this.emit('close'));\n\t\tthis.remote = remote;\n\t\tthis.keepAlives = [];\n\t\tthis.keepAliveBuffer = Buffer.alloc(8);\n\t\tthis.keepAliveInterval = setInterval(() => this.keepAlive(), KEEP_ALIVE_INTERVAL);\n\t\tsetImmediate(() => this.keepAlive());\n\n\t\tthis.debug = debug ? (message: string) => this.emit('debug', message) : null;\n\t}\n\n\t/**\n\t * Called when a message is received on the UDP socket.\n\t *\n\t * @param buffer - The received buffer\n\t */\n\tprivate onMessage(buffer: Buffer): void {\n\t\t// Handle keep alive message\n\t\tif (buffer.length === 8) {\n\t\t\tconst counter = buffer.readUInt32LE(0);\n\t\t\tconst index = this.keepAlives.findIndex(({ value }) => value === counter);\n\t\t\tif (index === -1) return;\n\t\t\tthis.ping = Date.now() - this.keepAlives[index]!.timestamp;\n\t\t\t// Delete all keep alives up to and including the received one\n\t\t\tthis.keepAlives.splice(0, index);\n\t\t}\n\t\t// Propagate the message\n\t\tthis.emit('message', buffer);\n\t}\n\n\t/**\n\t * Called at a regular interval to check whether we are still able to send datagrams to Discord.\n\t */\n\tprivate keepAlive() {\n\t\tif (this.keepAlives.length >= KEEP_ALIVE_LIMIT) {\n\t\t\tthis.debug?.('UDP socket has not received enough responses from Discord - closing socket');\n\t\t\tthis.destroy();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.keepAliveBuffer.writeUInt32LE(this.keepAliveCounter, 0);\n\t\tthis.send(this.keepAliveBuffer);\n\t\tthis.keepAlives.push({\n\t\t\tvalue: this.keepAliveCounter,\n\t\t\ttimestamp: Date.now(),\n\t\t});\n\t\tthis.keepAliveCounter++;\n\t\tif (this.keepAliveCounter > MAX_COUNTER_VALUE) {\n\t\t\tthis.keepAliveCounter = 0;\n\t\t}\n\t}\n\n\t/**\n\t * Sends a buffer to Discord.\n\t *\n\t * @param buffer - The buffer to send\n\t */\n\tpublic send(buffer: Buffer) {\n\t\treturn this.socket.send(buffer, this.remote.port, this.remote.ip);\n\t}\n\n\t/**\n\t * Closes the socket, the instance will not be able to be reused.\n\t */\n\tpublic destroy() {\n\t\ttry {\n\t\t\tthis.socket.close();\n\t\t} catch {}\n\t\tclearInterval(this.keepAliveInterval);\n\t}\n\n\t/**\n\t * Performs IP discovery to discover the local address and port to be used for the voice connection.\n\t *\n\t * @param ssrc - The SSRC received from Discord\n\t */\n\tpublic performIPDiscovery(ssrc: number): Promise {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst listener = (message: Buffer) => {\n\t\t\t\ttry {\n\t\t\t\t\tif (message.readUInt16BE(0) !== 2) return;\n\t\t\t\t\tconst packet = parseLocalPacket(message);\n\t\t\t\t\tthis.socket.off('message', listener);\n\t\t\t\t\tresolve(packet);\n\t\t\t\t} catch {}\n\t\t\t};\n\n\t\t\tthis.socket.on('message', listener);\n\t\t\tthis.socket.once('close', () => reject(new Error('Cannot perform IP discovery - socket closed')));\n\n\t\t\tconst discoveryBuffer = Buffer.alloc(74);\n\n\t\t\tdiscoveryBuffer.writeUInt16BE(1, 0);\n\t\t\tdiscoveryBuffer.writeUInt16BE(70, 2);\n\t\t\tdiscoveryBuffer.writeUInt32BE(ssrc, 4);\n\t\t\tthis.send(discoveryBuffer);\n\t\t});\n\t}\n}\n","/* eslint-disable @typescript-eslint/method-signature-style */\nimport { EventEmitter } from 'node:events';\nimport { VoiceOpcodes } from 'discord-api-types/voice/v4';\nimport WebSocket, { MessageEvent } from 'ws';\n\nexport interface VoiceWebSocket extends EventEmitter {\n\ton(event: 'error', listener: (error: Error) => void): this;\n\ton(event: 'open', listener: (event: WebSocket.Event) => void): this;\n\ton(event: 'close', listener: (event: WebSocket.CloseEvent) => void): this;\n\t/**\n\t * Debug event for VoiceWebSocket.\n\t *\n\t * @event\n\t */\n\ton(event: 'debug', listener: (message: string) => void): this;\n\t/**\n\t * Packet event.\n\t *\n\t * @event\n\t */\n\ton(event: 'packet', listener: (packet: any) => void): this;\n}\n\n/**\n * An extension of the WebSocket class to provide helper functionality when interacting\n * with the Discord Voice gateway.\n */\nexport class VoiceWebSocket extends EventEmitter {\n\t/**\n\t * The current heartbeat interval, if any.\n\t */\n\tprivate heartbeatInterval?: NodeJS.Timeout;\n\n\t/**\n\t * The time (milliseconds since UNIX epoch) that the last heartbeat acknowledgement packet was received.\n\t * This is set to 0 if an acknowledgement packet hasn't been received yet.\n\t */\n\tprivate lastHeartbeatAck: number;\n\n\t/**\n\t * The time (milliseconds since UNIX epoch) that the last heartbeat was sent. This is set to 0 if a heartbeat\n\t * hasn't been sent yet.\n\t */\n\tprivate lastHeartbeatSend: number;\n\n\t/**\n\t * The number of consecutively missed heartbeats.\n\t */\n\tprivate missedHeartbeats = 0;\n\n\t/**\n\t * The last recorded ping.\n\t */\n\tpublic ping?: number;\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: null | ((message: string) => void);\n\n\t/**\n\t * The underlying WebSocket of this wrapper.\n\t */\n\tprivate readonly ws: WebSocket;\n\n\t/**\n\t * Creates a new VoiceWebSocket.\n\t *\n\t * @param address - The address to connect to\n\t */\n\tpublic constructor(address: string, debug: boolean) {\n\t\tsuper();\n\t\tthis.ws = new WebSocket(address);\n\t\tthis.ws.onmessage = (e) => this.onMessage(e);\n\t\tthis.ws.onopen = (e) => this.emit('open', e);\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\tthis.ws.onerror = (e: Error | WebSocket.ErrorEvent) => this.emit('error', e instanceof Error ? e : e.error);\n\t\tthis.ws.onclose = (e) => this.emit('close', e);\n\n\t\tthis.lastHeartbeatAck = 0;\n\t\tthis.lastHeartbeatSend = 0;\n\n\t\tthis.debug = debug ? (message: string) => this.emit('debug', message) : null;\n\t}\n\n\t/**\n\t * Destroys the VoiceWebSocket. The heartbeat interval is cleared, and the connection is closed.\n\t */\n\tpublic destroy() {\n\t\ttry {\n\t\t\tthis.debug?.('destroyed');\n\t\t\tthis.setHeartbeatInterval(-1);\n\t\t\tthis.ws.close(1000);\n\t\t} catch (error) {\n\t\t\tconst e = error as Error;\n\t\t\tthis.emit('error', e);\n\t\t}\n\t}\n\n\t/**\n\t * Handles message events on the WebSocket. Attempts to JSON parse the messages and emit them\n\t * as packets.\n\t *\n\t * @param event - The message event\n\t */\n\tpublic onMessage(event: MessageEvent) {\n\t\tif (typeof event.data !== 'string') return;\n\n\t\tthis.debug?.(`<< ${event.data}`);\n\n\t\tlet packet: any;\n\t\ttry {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\t\tpacket = JSON.parse(event.data);\n\t\t} catch (error) {\n\t\t\tconst e = error as Error;\n\t\t\tthis.emit('error', e);\n\t\t\treturn;\n\t\t}\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\tif (packet.op === VoiceOpcodes.HeartbeatAck) {\n\t\t\tthis.lastHeartbeatAck = Date.now();\n\t\t\tthis.missedHeartbeats = 0;\n\t\t\tthis.ping = this.lastHeartbeatAck - this.lastHeartbeatSend;\n\t\t}\n\n\t\tthis.emit('packet', packet);\n\t}\n\n\t/**\n\t * Sends a JSON-stringifiable packet over the WebSocket.\n\t *\n\t * @param packet - The packet to send\n\t */\n\tpublic sendPacket(packet: any) {\n\t\ttry {\n\t\t\tconst stringified = JSON.stringify(packet);\n\t\t\tthis.debug?.(`>> ${stringified}`);\n\t\t\treturn this.ws.send(stringified);\n\t\t} catch (error) {\n\t\t\tconst e = error as Error;\n\t\t\tthis.emit('error', e);\n\t\t}\n\t}\n\n\t/**\n\t * Sends a heartbeat over the WebSocket.\n\t */\n\tprivate sendHeartbeat() {\n\t\tthis.lastHeartbeatSend = Date.now();\n\t\tthis.missedHeartbeats++;\n\t\tconst nonce = this.lastHeartbeatSend;\n\t\treturn this.sendPacket({\n\t\t\top: VoiceOpcodes.Heartbeat,\n\t\t\td: nonce,\n\t\t});\n\t}\n\n\t/**\n\t * Sets/clears an interval to send heartbeats over the WebSocket.\n\t *\n\t * @param ms - The interval in milliseconds. If negative, the interval will be unset\n\t */\n\tpublic setHeartbeatInterval(ms: number) {\n\t\tif (typeof this.heartbeatInterval !== 'undefined') clearInterval(this.heartbeatInterval);\n\t\tif (ms > 0) {\n\t\t\tthis.heartbeatInterval = setInterval(() => {\n\t\t\t\tif (this.lastHeartbeatSend !== 0 && this.missedHeartbeats >= 3) {\n\t\t\t\t\t// Missed too many heartbeats - disconnect\n\t\t\t\t\tthis.ws.close();\n\t\t\t\t\tthis.setHeartbeatInterval(-1);\n\t\t\t\t}\n\t\t\t\tthis.sendHeartbeat();\n\t\t\t}, ms);\n\t\t}\n\t}\n}\n","interface Methods {\n\topen: (buffer: Buffer, nonce: Buffer, secretKey: Uint8Array) => Buffer | null;\n\tclose: (opusPacket: Buffer, nonce: Buffer, secretKey: Uint8Array) => Buffer;\n\trandom: (bytes: number, nonce: Buffer) => Buffer;\n}\n\nconst libs = {\n\t'sodium-native': (sodium: any): Methods => ({\n\t\topen: (buffer: Buffer, nonce: Buffer, secretKey: Uint8Array) => {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n\t\t\tif (buffer) {\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\t\tconst output = Buffer.allocUnsafe(buffer.length - sodium.crypto_box_MACBYTES);\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n\t\t\t\tif (sodium.crypto_secretbox_open_easy(output, buffer, nonce, secretKey)) return output;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t\tclose: (opusPacket: Buffer, nonce: Buffer, secretKey: Uint8Array) => {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument, @typescript-eslint/restrict-plus-operands\n\t\t\tconst output = Buffer.allocUnsafe(opusPacket.length + sodium.crypto_box_MACBYTES);\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n\t\t\tsodium.crypto_secretbox_easy(output, opusPacket, nonce, secretKey);\n\t\t\treturn output;\n\t\t},\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\trandom: (n: number, buffer: Buffer = Buffer.allocUnsafe(n)) => {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n\t\t\tsodium.randombytes_buf(buffer);\n\t\t\treturn buffer;\n\t\t},\n\t}),\n\tsodium: (sodium: any): Methods => ({\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\topen: sodium.api.crypto_secretbox_open_easy,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\tclose: sodium.api.crypto_secretbox_easy,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\trandom: (n: number, buffer: Buffer = Buffer.allocUnsafe(n)) => {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n\t\t\tsodium.api.randombytes_buf(buffer);\n\t\t\treturn buffer;\n\t\t},\n\t}),\n\t'libsodium-wrappers': (sodium: any): Methods => ({\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\topen: sodium.crypto_secretbox_open_easy,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\tclose: sodium.crypto_secretbox_easy,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\trandom: sodium.randombytes_buf,\n\t}),\n\ttweetnacl: (tweetnacl: any): Methods => ({\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\topen: tweetnacl.secretbox.open,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\tclose: tweetnacl.secretbox,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\trandom: tweetnacl.randomBytes,\n\t}),\n} as const;\n\nconst fallbackError = () => {\n\tthrow new Error(\n\t\t`Cannot play audio as no valid encryption package is installed.\n- Install sodium, libsodium-wrappers, or tweetnacl.\n- Use the generateDependencyReport() function for more information.\\n`,\n\t);\n};\n\nconst methods: Methods = {\n\topen: fallbackError,\n\tclose: fallbackError,\n\trandom: fallbackError,\n};\n\nvoid (async () => {\n\tfor (const libName of Object.keys(libs) as (keyof typeof libs)[]) {\n\t\ttry {\n\t\t\t// eslint-disable-next-line\n\t\t\tconst lib = require(libName);\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\tif (libName === 'libsodium-wrappers' && lib.ready) await lib.ready;\n\t\t\tObject.assign(methods, libs[libName](lib));\n\t\t\tbreak;\n\t\t} catch {}\n\t}\n})();\n\nexport { methods };\n","// eslint-disable-next-line @typescript-eslint/no-empty-function\nexport const noop = () => {};\n","import { VoiceOpcodes } from 'discord-api-types/voice/v4';\nimport {\n\tAudioReceiveStream,\n\tAudioReceiveStreamOptions,\n\tcreateDefaultAudioReceiveStreamOptions,\n} from './AudioReceiveStream';\nimport { SSRCMap } from './SSRCMap';\nimport { SpeakingMap } from './SpeakingMap';\nimport type { VoiceConnection } from '../VoiceConnection';\nimport type { ConnectionData } from '../networking/Networking';\nimport { methods } from '../util/Secretbox';\n\n/**\n * Attaches to a VoiceConnection, allowing you to receive audio packets from other\n * users that are speaking.\n *\n * @beta\n */\nexport class VoiceReceiver {\n\t/**\n\t * The attached connection of this receiver.\n\t */\n\tpublic readonly voiceConnection;\n\n\t/**\n\t * Maps SSRCs to Discord user ids.\n\t */\n\tpublic readonly ssrcMap: SSRCMap;\n\n\t/**\n\t * The current audio subscriptions of this receiver.\n\t */\n\tpublic readonly subscriptions: Map;\n\n\t/**\n\t * The connection data of the receiver.\n\t *\n\t * @internal\n\t */\n\tpublic connectionData: Partial;\n\n\t/**\n\t * The speaking map of the receiver.\n\t */\n\tpublic readonly speaking: SpeakingMap;\n\n\tpublic constructor(voiceConnection: VoiceConnection) {\n\t\tthis.voiceConnection = voiceConnection;\n\t\tthis.ssrcMap = new SSRCMap();\n\t\tthis.speaking = new SpeakingMap();\n\t\tthis.subscriptions = new Map();\n\t\tthis.connectionData = {};\n\n\t\tthis.onWsPacket = this.onWsPacket.bind(this);\n\t\tthis.onUdpMessage = this.onUdpMessage.bind(this);\n\t}\n\n\t/**\n\t * Called when a packet is received on the attached connection's WebSocket.\n\t *\n\t * @param packet - The received packet\n\t *\n\t * @internal\n\t */\n\tpublic onWsPacket(packet: any) {\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\tif (packet.op === VoiceOpcodes.ClientDisconnect && typeof packet.d?.user_id === 'string') {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access\n\t\t\tthis.ssrcMap.delete(packet.d.user_id);\n\t\t} else if (\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\tpacket.op === VoiceOpcodes.Speaking &&\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\ttypeof packet.d?.user_id === 'string' &&\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\ttypeof packet.d?.ssrc === 'number'\n\t\t) {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\t\tthis.ssrcMap.update({ userId: packet.d.user_id, audioSSRC: packet.d.ssrc });\n\t\t} else if (\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\tpacket.op === VoiceOpcodes.ClientConnect &&\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\ttypeof packet.d?.user_id === 'string' &&\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\ttypeof packet.d?.audio_ssrc === 'number'\n\t\t) {\n\t\t\tthis.ssrcMap.update({\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\t\t\tuserId: packet.d.user_id,\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\t\t\taudioSSRC: packet.d.audio_ssrc,\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\t\t\tvideoSSRC: packet.d.video_ssrc === 0 ? undefined : packet.d.video_ssrc,\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate decrypt(buffer: Buffer, mode: string, nonce: Buffer, secretKey: Uint8Array) {\n\t\t// Choose correct nonce depending on encryption\n\t\tlet end;\n\t\tif (mode === 'xsalsa20_poly1305_lite') {\n\t\t\tbuffer.copy(nonce, 0, buffer.length - 4);\n\t\t\tend = buffer.length - 4;\n\t\t} else if (mode === 'xsalsa20_poly1305_suffix') {\n\t\t\tbuffer.copy(nonce, 0, buffer.length - 24);\n\t\t\tend = buffer.length - 24;\n\t\t} else {\n\t\t\tbuffer.copy(nonce, 0, 0, 12);\n\t\t}\n\n\t\t// Open packet\n\t\tconst decrypted = methods.open(buffer.slice(12, end), nonce, secretKey);\n\t\tif (!decrypted) return;\n\t\treturn Buffer.from(decrypted);\n\t}\n\n\t/**\n\t * Parses an audio packet, decrypting it to yield an Opus packet.\n\t *\n\t * @param buffer - The buffer to parse\n\t * @param mode - The encryption mode\n\t * @param nonce - The nonce buffer used by the connection for encryption\n\t * @param secretKey - The secret key used by the connection for encryption\n\t *\n\t * @returns The parsed Opus packet\n\t */\n\tprivate parsePacket(buffer: Buffer, mode: string, nonce: Buffer, secretKey: Uint8Array) {\n\t\tlet packet = this.decrypt(buffer, mode, nonce, secretKey);\n\t\tif (!packet) return;\n\n\t\t// Strip RTP Header Extensions (one-byte only)\n\t\tif (packet[0] === 0xbe && packet[1] === 0xde) {\n\t\t\tconst headerExtensionLength = packet.readUInt16BE(2);\n\t\t\tpacket = packet.subarray(4 + 4 * headerExtensionLength);\n\t\t}\n\n\t\treturn packet;\n\t}\n\n\t/**\n\t * Called when the UDP socket of the attached connection receives a message.\n\t *\n\t * @param msg - The received message\n\t *\n\t * @internal\n\t */\n\tpublic onUdpMessage(msg: Buffer) {\n\t\tif (msg.length <= 8) return;\n\t\tconst ssrc = msg.readUInt32BE(8);\n\n\t\tconst userData = this.ssrcMap.get(ssrc);\n\t\tif (!userData) return;\n\n\t\tthis.speaking.onPacket(userData.userId);\n\n\t\tconst stream = this.subscriptions.get(userData.userId);\n\t\tif (!stream) return;\n\n\t\tif (this.connectionData.encryptionMode && this.connectionData.nonceBuffer && this.connectionData.secretKey) {\n\t\t\tconst packet = this.parsePacket(\n\t\t\t\tmsg,\n\t\t\t\tthis.connectionData.encryptionMode,\n\t\t\t\tthis.connectionData.nonceBuffer,\n\t\t\t\tthis.connectionData.secretKey,\n\t\t\t);\n\t\t\tif (packet) {\n\t\t\t\tstream.push(packet);\n\t\t\t} else {\n\t\t\t\tstream.destroy(new Error('Failed to parse packet'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Creates a subscription for the given user id.\n\t *\n\t * @param target - The id of the user to subscribe to\n\t *\n\t * @returns A readable stream of Opus packets received from the target\n\t */\n\tpublic subscribe(userId: string, options?: Partial) {\n\t\tconst existing = this.subscriptions.get(userId);\n\t\tif (existing) return existing;\n\n\t\tconst stream = new AudioReceiveStream({\n\t\t\t...createDefaultAudioReceiveStreamOptions(),\n\t\t\t...options,\n\t\t});\n\n\t\tstream.once('close', () => this.subscriptions.delete(userId));\n\t\tthis.subscriptions.set(userId, stream);\n\t\treturn stream;\n\t}\n}\n","import { Readable, ReadableOptions } from 'node:stream';\nimport { SILENCE_FRAME } from '../audio/AudioPlayer';\n\n/**\n * The different behaviors an audio receive stream can have for deciding when to end.\n */\nexport enum EndBehaviorType {\n\t/**\n\t * The stream will only end when manually destroyed.\n\t */\n\tManual,\n\n\t/**\n\t * The stream will end after a given time period of silence/no audio packets.\n\t */\n\tAfterSilence,\n\n\t/**\n\t * The stream will end after a given time period of no audio packets.\n\t */\n\tAfterInactivity,\n}\n\nexport type EndBehavior =\n\t| {\n\t\t\tbehavior: EndBehaviorType.Manual;\n\t }\n\t| {\n\t\t\tbehavior: EndBehaviorType.AfterSilence | EndBehaviorType.AfterInactivity;\n\t\t\tduration: number;\n\t };\n\nexport interface AudioReceiveStreamOptions extends ReadableOptions {\n\tend: EndBehavior;\n}\n\nexport function createDefaultAudioReceiveStreamOptions(): AudioReceiveStreamOptions {\n\treturn {\n\t\tend: {\n\t\t\tbehavior: EndBehaviorType.Manual,\n\t\t},\n\t};\n}\n\n/**\n * A readable stream of Opus packets received from a specific entity\n * in a Discord voice connection.\n */\nexport class AudioReceiveStream extends Readable {\n\t/**\n\t * The end behavior of the receive stream.\n\t */\n\tpublic readonly end: EndBehavior;\n\n\tprivate endTimeout?: NodeJS.Timeout;\n\n\tpublic constructor({ end, ...options }: AudioReceiveStreamOptions) {\n\t\tsuper({\n\t\t\t...options,\n\t\t\tobjectMode: true,\n\t\t});\n\n\t\tthis.end = end;\n\t}\n\n\tpublic override push(buffer: Buffer | null) {\n\t\tif (buffer) {\n\t\t\tif (\n\t\t\t\tthis.end.behavior === EndBehaviorType.AfterInactivity ||\n\t\t\t\t(this.end.behavior === EndBehaviorType.AfterSilence &&\n\t\t\t\t\t(buffer.compare(SILENCE_FRAME) !== 0 || typeof this.endTimeout === 'undefined'))\n\t\t\t) {\n\t\t\t\tthis.renewEndTimeout(this.end);\n\t\t\t}\n\t\t}\n\n\t\treturn super.push(buffer);\n\t}\n\n\tprivate renewEndTimeout(end: EndBehavior & { duration: number }) {\n\t\tif (this.endTimeout) {\n\t\t\tclearTimeout(this.endTimeout);\n\t\t}\n\t\tthis.endTimeout = setTimeout(() => this.push(null), end.duration);\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/no-empty-function\n\tpublic override _read() {}\n}\n","/* eslint-disable @typescript-eslint/prefer-ts-expect-error, @typescript-eslint/method-signature-style */\nimport EventEmitter from 'node:events';\nimport { AudioPlayerError } from './AudioPlayerError';\nimport type { AudioResource } from './AudioResource';\nimport { PlayerSubscription } from './PlayerSubscription';\nimport { addAudioPlayer, deleteAudioPlayer } from '../DataStore';\nimport { VoiceConnection, VoiceConnectionStatus } from '../VoiceConnection';\nimport { noop } from '../util/util';\n\n// The Opus \"silent\" frame\nexport const SILENCE_FRAME = Buffer.from([0xf8, 0xff, 0xfe]);\n\n/**\n * Describes the behavior of the player when an audio packet is played but there are no available\n * voice connections to play to.\n */\nexport enum NoSubscriberBehavior {\n\t/**\n\t * Pauses playing the stream until a voice connection becomes available.\n\t */\n\tPause = 'pause',\n\n\t/**\n\t * Continues to play through the resource regardless.\n\t */\n\tPlay = 'play',\n\n\t/**\n\t * The player stops and enters the Idle state.\n\t */\n\tStop = 'stop',\n}\n\nexport enum AudioPlayerStatus {\n\t/**\n\t * When there is currently no resource for the player to be playing.\n\t */\n\tIdle = 'idle',\n\n\t/**\n\t * When the player is waiting for an audio resource to become readable before transitioning to Playing.\n\t */\n\tBuffering = 'buffering',\n\n\t/**\n\t * When the player has been manually paused.\n\t */\n\tPaused = 'paused',\n\n\t/**\n\t * When the player is actively playing an audio resource.\n\t */\n\tPlaying = 'playing',\n\n\t/**\n\t * When the player has paused itself. Only possible with the \"pause\" no subscriber behavior.\n\t */\n\tAutoPaused = 'autopaused',\n}\n\n/**\n * Options that can be passed when creating an audio player, used to specify its behavior.\n */\nexport interface CreateAudioPlayerOptions {\n\tdebug?: boolean;\n\tbehaviors?: {\n\t\tnoSubscriber?: NoSubscriberBehavior;\n\t\tmaxMissedFrames?: number;\n\t};\n}\n\n/**\n * The state that an AudioPlayer is in when it has no resource to play. This is the starting state.\n */\nexport interface AudioPlayerIdleState {\n\tstatus: AudioPlayerStatus.Idle;\n}\n\n/**\n * The state that an AudioPlayer is in when it is waiting for a resource to become readable. Once this\n * happens, the AudioPlayer will enter the Playing state. If the resource ends/errors before this, then\n * it will re-enter the Idle state.\n */\nexport interface AudioPlayerBufferingState {\n\tstatus: AudioPlayerStatus.Buffering;\n\t/**\n\t * The resource that the AudioPlayer is waiting for\n\t */\n\tresource: AudioResource;\n\tonReadableCallback: () => void;\n\tonFailureCallback: () => void;\n\tonStreamError: (error: Error) => void;\n}\n\n/**\n * The state that an AudioPlayer is in when it is actively playing an AudioResource. When playback ends,\n * it will enter the Idle state.\n */\nexport interface AudioPlayerPlayingState {\n\tstatus: AudioPlayerStatus.Playing;\n\t/**\n\t * The number of consecutive times that the audio resource has been unable to provide an Opus frame.\n\t */\n\tmissedFrames: number;\n\n\t/**\n\t * The playback duration in milliseconds of the current audio resource. This includes filler silence packets\n\t * that have been played when the resource was buffering.\n\t */\n\tplaybackDuration: number;\n\n\t/**\n\t * The resource that is being played.\n\t */\n\tresource: AudioResource;\n\n\tonStreamError: (error: Error) => void;\n}\n\n/**\n * The state that an AudioPlayer is in when it has either been explicitly paused by the user, or done\n * automatically by the AudioPlayer itself if there are no available subscribers.\n */\nexport interface AudioPlayerPausedState {\n\tstatus: AudioPlayerStatus.Paused | AudioPlayerStatus.AutoPaused;\n\t/**\n\t * How many silence packets still need to be played to avoid audio interpolation due to the stream suddenly pausing.\n\t */\n\tsilencePacketsRemaining: number;\n\n\t/**\n\t * The playback duration in milliseconds of the current audio resource. This includes filler silence packets\n\t * that have been played when the resource was buffering.\n\t */\n\tplaybackDuration: number;\n\n\t/**\n\t * The current resource of the audio player.\n\t */\n\tresource: AudioResource;\n\n\tonStreamError: (error: Error) => void;\n}\n\n/**\n * The various states that the player can be in.\n */\nexport type AudioPlayerState =\n\t| AudioPlayerIdleState\n\t| AudioPlayerBufferingState\n\t| AudioPlayerPlayingState\n\t| AudioPlayerPausedState;\n\nexport interface AudioPlayer extends EventEmitter {\n\t/**\n\t * Emitted when there is an error emitted from the audio resource played by the audio player\n\t * @event\n\t */\n\ton(event: 'error', listener: (error: AudioPlayerError) => void): this;\n\t/**\n\t * Emitted debugging information about the audio player\n\t * @event\n\t */\n\ton(event: 'debug', listener: (message: string) => void): this;\n\t/**\n\t * Emitted when the state of the audio player changes\n\t * @event\n\t */\n\ton(event: 'stateChange', listener: (oldState: AudioPlayerState, newState: AudioPlayerState) => void): this;\n\t/**\n\t * Emitted when the audio player is subscribed to a voice connection\n\t * @event\n\t */\n\ton(event: 'subscribe' | 'unsubscribe', listener: (subscription: PlayerSubscription) => void): this;\n\t/**\n\t * Emitted when the status of state changes to a specific status\n\t * @event\n\t */\n\ton(\n\t\tevent: T,\n\t\tlistener: (oldState: AudioPlayerState, newState: AudioPlayerState & { status: T }) => void,\n\t): this;\n}\n\n/**\n * Stringifies an AudioPlayerState instance.\n *\n * @param state - The state to stringify\n */\nfunction stringifyState(state: AudioPlayerState) {\n\treturn JSON.stringify({\n\t\t...state,\n\t\tresource: Reflect.has(state, 'resource'),\n\t\tstepTimeout: Reflect.has(state, 'stepTimeout'),\n\t});\n}\n\n/**\n * Used to play audio resources (i.e. tracks, streams) to voice connections.\n *\n * @remarks\n * Audio players are designed to be re-used - even if a resource has finished playing, the player itself\n * can still be used.\n *\n * The AudioPlayer drives the timing of playback, and therefore is unaffected by voice connections\n * becoming unavailable. Its behavior in these scenarios can be configured.\n */\nexport class AudioPlayer extends EventEmitter {\n\t/**\n\t * The state that the AudioPlayer is in.\n\t */\n\tprivate _state: AudioPlayerState;\n\n\t/**\n\t * A list of VoiceConnections that are registered to this AudioPlayer. The player will attempt to play audio\n\t * to the streams in this list.\n\t */\n\tprivate readonly subscribers: PlayerSubscription[] = [];\n\n\t/**\n\t * The behavior that the player should follow when it enters certain situations.\n\t */\n\tprivate readonly behaviors: {\n\t\tnoSubscriber: NoSubscriberBehavior;\n\t\tmaxMissedFrames: number;\n\t};\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: null | ((message: string) => void);\n\n\t/**\n\t * Creates a new AudioPlayer.\n\t */\n\tpublic constructor(options: CreateAudioPlayerOptions = {}) {\n\t\tsuper();\n\t\tthis._state = { status: AudioPlayerStatus.Idle };\n\t\tthis.behaviors = {\n\t\t\tnoSubscriber: NoSubscriberBehavior.Pause,\n\t\t\tmaxMissedFrames: 5,\n\t\t\t...options.behaviors,\n\t\t};\n\t\tthis.debug = options.debug === false ? null : (message: string) => this.emit('debug', message);\n\t}\n\n\t/**\n\t * A list of subscribed voice connections that can currently receive audio to play.\n\t */\n\tpublic get playable() {\n\t\treturn this.subscribers\n\t\t\t.filter(({ connection }) => connection.state.status === VoiceConnectionStatus.Ready)\n\t\t\t.map(({ connection }) => connection);\n\t}\n\n\t/**\n\t * Subscribes a VoiceConnection to the audio player's play list. If the VoiceConnection is already subscribed,\n\t * then the existing subscription is used.\n\t *\n\t * @remarks\n\t * This method should not be directly called. Instead, use VoiceConnection#subscribe.\n\t *\n\t * @param connection - The connection to subscribe\n\t *\n\t * @returns The new subscription if the voice connection is not yet subscribed, otherwise the existing subscription\n\t */\n\t// @ts-ignore\n\tprivate subscribe(connection: VoiceConnection) {\n\t\tconst existingSubscription = this.subscribers.find((subscription) => subscription.connection === connection);\n\t\tif (!existingSubscription) {\n\t\t\tconst subscription = new PlayerSubscription(connection, this);\n\t\t\tthis.subscribers.push(subscription);\n\t\t\tsetImmediate(() => this.emit('subscribe', subscription));\n\t\t\treturn subscription;\n\t\t}\n\t\treturn existingSubscription;\n\t}\n\n\t/**\n\t * Unsubscribes a subscription - i.e. removes a voice connection from the play list of the audio player.\n\t *\n\t * @remarks\n\t * This method should not be directly called. Instead, use PlayerSubscription#unsubscribe.\n\t *\n\t * @param subscription - The subscription to remove\n\t *\n\t * @returns Whether or not the subscription existed on the player and was removed\n\t */\n\t// @ts-ignore\n\tprivate unsubscribe(subscription: PlayerSubscription) {\n\t\tconst index = this.subscribers.indexOf(subscription);\n\t\tconst exists = index !== -1;\n\t\tif (exists) {\n\t\t\tthis.subscribers.splice(index, 1);\n\t\t\tsubscription.connection.setSpeaking(false);\n\t\t\tthis.emit('unsubscribe', subscription);\n\t\t}\n\t\treturn exists;\n\t}\n\n\t/**\n\t * The state that the player is in.\n\t */\n\tpublic get state() {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * Sets a new state for the player, performing clean-up operations where necessary.\n\t */\n\tpublic set state(newState: AudioPlayerState) {\n\t\tconst oldState = this._state;\n\t\tconst newResource = Reflect.get(newState, 'resource') as AudioResource | undefined;\n\n\t\tif (oldState.status !== AudioPlayerStatus.Idle && oldState.resource !== newResource) {\n\t\t\toldState.resource.playStream.on('error', noop);\n\t\t\toldState.resource.playStream.off('error', oldState.onStreamError);\n\t\t\toldState.resource.audioPlayer = undefined;\n\t\t\toldState.resource.playStream.destroy();\n\t\t\toldState.resource.playStream.read(); // required to ensure buffered data is drained, prevents memory leak\n\t\t}\n\n\t\t// When leaving the Buffering state (or buffering a new resource), then remove the event listeners from it\n\t\tif (\n\t\t\toldState.status === AudioPlayerStatus.Buffering &&\n\t\t\t(newState.status !== AudioPlayerStatus.Buffering || newState.resource !== oldState.resource)\n\t\t) {\n\t\t\toldState.resource.playStream.off('end', oldState.onFailureCallback);\n\t\t\toldState.resource.playStream.off('close', oldState.onFailureCallback);\n\t\t\toldState.resource.playStream.off('finish', oldState.onFailureCallback);\n\t\t\toldState.resource.playStream.off('readable', oldState.onReadableCallback);\n\t\t}\n\n\t\t// transitioning into an idle should ensure that connections stop speaking\n\t\tif (newState.status === AudioPlayerStatus.Idle) {\n\t\t\tthis._signalStopSpeaking();\n\t\t\tdeleteAudioPlayer(this);\n\t\t}\n\n\t\t// attach to the global audio player timer\n\t\tif (newResource) {\n\t\t\taddAudioPlayer(this);\n\t\t}\n\n\t\t// playing -> playing state changes should still transition if a resource changed (seems like it would be useful!)\n\t\tconst didChangeResources =\n\t\t\toldState.status !== AudioPlayerStatus.Idle &&\n\t\t\tnewState.status === AudioPlayerStatus.Playing &&\n\t\t\toldState.resource !== newState.resource;\n\n\t\tthis._state = newState;\n\n\t\tthis.emit('stateChange', oldState, this._state);\n\t\tif (oldState.status !== newState.status || didChangeResources) {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\t\tthis.emit(newState.status, oldState, this._state as any);\n\t\t}\n\t\tthis.debug?.(`state change:\\nfrom ${stringifyState(oldState)}\\nto ${stringifyState(newState)}`);\n\t}\n\n\t/**\n\t * Plays a new resource on the player. If the player is already playing a resource, the existing resource is destroyed\n\t * (it cannot be reused, even in another player) and is replaced with the new resource.\n\t *\n\t * @remarks\n\t * The player will transition to the Playing state once playback begins, and will return to the Idle state once\n\t * playback is ended.\n\t *\n\t * If the player was previously playing a resource and this method is called, the player will not transition to the\n\t * Idle state during the swap over.\n\t *\n\t * @param resource - The resource to play\n\t *\n\t * @throws Will throw if attempting to play an audio resource that has already ended, or is being played by another player\n\t */\n\tpublic play(resource: AudioResource) {\n\t\tif (resource.ended) {\n\t\t\tthrow new Error('Cannot play a resource that has already ended.');\n\t\t}\n\n\t\tif (resource.audioPlayer) {\n\t\t\tif (resource.audioPlayer === this) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error('Resource is already being played by another audio player.');\n\t\t}\n\t\tresource.audioPlayer = this;\n\n\t\t// Attach error listeners to the stream that will propagate the error and then return to the Idle\n\t\t// state if the resource is still being used.\n\t\tconst onStreamError = (error: Error) => {\n\t\t\tif (this.state.status !== AudioPlayerStatus.Idle) {\n\t\t\t\tthis.emit('error', new AudioPlayerError(error, this.state.resource));\n\t\t\t}\n\n\t\t\tif (this.state.status !== AudioPlayerStatus.Idle && this.state.resource === resource) {\n\t\t\t\tthis.state = {\n\t\t\t\t\tstatus: AudioPlayerStatus.Idle,\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\n\t\tresource.playStream.once('error', onStreamError);\n\n\t\tif (resource.started) {\n\t\t\tthis.state = {\n\t\t\t\tstatus: AudioPlayerStatus.Playing,\n\t\t\t\tmissedFrames: 0,\n\t\t\t\tplaybackDuration: 0,\n\t\t\t\tresource,\n\t\t\t\tonStreamError,\n\t\t\t};\n\t\t} else {\n\t\t\tconst onReadableCallback = () => {\n\t\t\t\tif (this.state.status === AudioPlayerStatus.Buffering && this.state.resource === resource) {\n\t\t\t\t\tthis.state = {\n\t\t\t\t\t\tstatus: AudioPlayerStatus.Playing,\n\t\t\t\t\t\tmissedFrames: 0,\n\t\t\t\t\t\tplaybackDuration: 0,\n\t\t\t\t\t\tresource,\n\t\t\t\t\t\tonStreamError,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst onFailureCallback = () => {\n\t\t\t\tif (this.state.status === AudioPlayerStatus.Buffering && this.state.resource === resource) {\n\t\t\t\t\tthis.state = {\n\t\t\t\t\t\tstatus: AudioPlayerStatus.Idle,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tresource.playStream.once('readable', onReadableCallback);\n\n\t\t\tresource.playStream.once('end', onFailureCallback);\n\t\t\tresource.playStream.once('close', onFailureCallback);\n\t\t\tresource.playStream.once('finish', onFailureCallback);\n\n\t\t\tthis.state = {\n\t\t\t\tstatus: AudioPlayerStatus.Buffering,\n\t\t\t\tresource,\n\t\t\t\tonReadableCallback,\n\t\t\t\tonFailureCallback,\n\t\t\t\tonStreamError,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Pauses playback of the current resource, if any.\n\t *\n\t * @param interpolateSilence - If true, the player will play 5 packets of silence after pausing to prevent audio glitches\n\t *\n\t * @returns `true` if the player was successfully paused, otherwise `false`\n\t */\n\tpublic pause(interpolateSilence = true) {\n\t\tif (this.state.status !== AudioPlayerStatus.Playing) return false;\n\t\tthis.state = {\n\t\t\t...this.state,\n\t\t\tstatus: AudioPlayerStatus.Paused,\n\t\t\tsilencePacketsRemaining: interpolateSilence ? 5 : 0,\n\t\t};\n\t\treturn true;\n\t}\n\n\t/**\n\t * Unpauses playback of the current resource, if any.\n\t *\n\t * @returns `true` if the player was successfully unpaused, otherwise `false`\n\t */\n\tpublic unpause() {\n\t\tif (this.state.status !== AudioPlayerStatus.Paused) return false;\n\t\tthis.state = {\n\t\t\t...this.state,\n\t\t\tstatus: AudioPlayerStatus.Playing,\n\t\t\tmissedFrames: 0,\n\t\t};\n\t\treturn true;\n\t}\n\n\t/**\n\t * Stops playback of the current resource and destroys the resource. The player will either transition to the Idle state,\n\t * or remain in its current state until the silence padding frames of the resource have been played.\n\t *\n\t * @param force - If true, will force the player to enter the Idle state even if the resource has silence padding frames\n\t *\n\t * @returns `true` if the player will come to a stop, otherwise `false`\n\t */\n\tpublic stop(force = false) {\n\t\tif (this.state.status === AudioPlayerStatus.Idle) return false;\n\t\tif (force || this.state.resource.silencePaddingFrames === 0) {\n\t\t\tthis.state = {\n\t\t\t\tstatus: AudioPlayerStatus.Idle,\n\t\t\t};\n\t\t} else if (this.state.resource.silenceRemaining === -1) {\n\t\t\tthis.state.resource.silenceRemaining = this.state.resource.silencePaddingFrames;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks whether the underlying resource (if any) is playable (readable)\n\t *\n\t * @returns `true` if the resource is playable, otherwise `false`\n\t */\n\tpublic checkPlayable() {\n\t\tconst state = this._state;\n\t\tif (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) return false;\n\n\t\t// If the stream has been destroyed or is no longer readable, then transition to the Idle state.\n\t\tif (!state.resource.readable) {\n\t\t\tthis.state = {\n\t\t\t\tstatus: AudioPlayerStatus.Idle,\n\t\t\t};\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Called roughly every 20ms by the global audio player timer. Dispatches any audio packets that are buffered\n\t * by the active connections of this audio player.\n\t */\n\t// @ts-ignore\n\tprivate _stepDispatch() {\n\t\tconst state = this._state;\n\n\t\t// Guard against the Idle state\n\t\tif (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) return;\n\n\t\t// Dispatch any audio packets that were prepared in the previous cycle\n\t\tthis.playable.forEach((connection) => connection.dispatchAudio());\n\t}\n\n\t/**\n\t * Called roughly every 20ms by the global audio player timer. Attempts to read an audio packet from the\n\t * underlying resource of the stream, and then has all the active connections of the audio player prepare it\n\t * (encrypt it, append header data) so that it is ready to play at the start of the next cycle.\n\t */\n\t// @ts-ignore\n\tprivate _stepPrepare() {\n\t\tconst state = this._state;\n\n\t\t// Guard against the Idle state\n\t\tif (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) return;\n\n\t\t// List of connections that can receive the packet\n\t\tconst playable = this.playable;\n\n\t\t/* If the player was previously in the AutoPaused state, check to see whether there are newly available\n\t\t connections, allowing us to transition out of the AutoPaused state back into the Playing state */\n\t\tif (state.status === AudioPlayerStatus.AutoPaused && playable.length > 0) {\n\t\t\tthis.state = {\n\t\t\t\t...state,\n\t\t\t\tstatus: AudioPlayerStatus.Playing,\n\t\t\t\tmissedFrames: 0,\n\t\t\t};\n\t\t}\n\n\t\t/* If the player is (auto)paused, check to see whether silence packets should be played and\n\t\t set a timeout to begin the next cycle, ending the current cycle here. */\n\t\tif (state.status === AudioPlayerStatus.Paused || state.status === AudioPlayerStatus.AutoPaused) {\n\t\t\tif (state.silencePacketsRemaining > 0) {\n\t\t\t\tstate.silencePacketsRemaining--;\n\t\t\t\tthis._preparePacket(SILENCE_FRAME, playable, state);\n\t\t\t\tif (state.silencePacketsRemaining === 0) {\n\t\t\t\t\tthis._signalStopSpeaking();\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// If there are no available connections in this cycle, observe the configured \"no subscriber\" behavior.\n\t\tif (playable.length === 0) {\n\t\t\tif (this.behaviors.noSubscriber === NoSubscriberBehavior.Pause) {\n\t\t\t\tthis.state = {\n\t\t\t\t\t...state,\n\t\t\t\t\tstatus: AudioPlayerStatus.AutoPaused,\n\t\t\t\t\tsilencePacketsRemaining: 5,\n\t\t\t\t};\n\t\t\t\treturn;\n\t\t\t} else if (this.behaviors.noSubscriber === NoSubscriberBehavior.Stop) {\n\t\t\t\tthis.stop(true);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Attempt to read an Opus packet from the resource. If there isn't an available packet,\n\t\t * play a silence packet. If there are 5 consecutive cycles with failed reads, then the\n\t\t * playback will end.\n\t\t */\n\t\tconst packet: Buffer | null = state.resource.read();\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n\t\tif (state.status === AudioPlayerStatus.Playing) {\n\t\t\tif (packet) {\n\t\t\t\tthis._preparePacket(packet, playable, state);\n\t\t\t\tstate.missedFrames = 0;\n\t\t\t} else {\n\t\t\t\tthis._preparePacket(SILENCE_FRAME, playable, state);\n\t\t\t\tstate.missedFrames++;\n\t\t\t\tif (state.missedFrames >= this.behaviors.maxMissedFrames) {\n\t\t\t\t\tthis.stop();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Signals to all the subscribed connections that they should send a packet to Discord indicating\n\t * they are no longer speaking. Called once playback of a resource ends.\n\t */\n\tprivate _signalStopSpeaking() {\n\t\treturn this.subscribers.forEach(({ connection }) => connection.setSpeaking(false));\n\t}\n\n\t/**\n\t * Instructs the given connections to each prepare this packet to be played at the start of the\n\t * next cycle.\n\t *\n\t * @param packet - The Opus packet to be prepared by each receiver\n\t * @param receivers - The connections that should play this packet\n\t */\n\tprivate _preparePacket(\n\t\tpacket: Buffer,\n\t\treceivers: VoiceConnection[],\n\t\tstate: AudioPlayerPlayingState | AudioPlayerPausedState,\n\t) {\n\t\tstate.playbackDuration += 20;\n\t\treceivers.forEach((connection) => connection.prepareAudioPacket(packet));\n\t}\n}\n\n/**\n * Creates a new AudioPlayer to be used.\n */\nexport function createAudioPlayer(options?: CreateAudioPlayerOptions) {\n\treturn new AudioPlayer(options);\n}\n","import type { AudioResource } from './AudioResource';\n\n/**\n * An error emitted by an AudioPlayer. Contains an attached resource to aid with\n * debugging and identifying where the error came from.\n */\nexport class AudioPlayerError extends Error {\n\t/**\n\t * The resource associated with the audio player at the time the error was thrown.\n\t */\n\tpublic readonly resource: AudioResource;\n\tpublic constructor(error: Error, resource: AudioResource) {\n\t\tsuper(error.message);\n\t\tthis.resource = resource;\n\t\tthis.name = error.name;\n\t\tthis.stack = error.stack;\n\t}\n}\n","/* eslint-disable @typescript-eslint/dot-notation */\nimport type { AudioPlayer } from './AudioPlayer';\nimport type { VoiceConnection } from '../VoiceConnection';\n\n/**\n * Represents a subscription of a voice connection to an audio player, allowing\n * the audio player to play audio on the voice connection.\n */\nexport class PlayerSubscription {\n\t/**\n\t * The voice connection of this subscription.\n\t */\n\tpublic readonly connection: VoiceConnection;\n\n\t/**\n\t * The audio player of this subscription.\n\t */\n\tpublic readonly player: AudioPlayer;\n\n\tpublic constructor(connection: VoiceConnection, player: AudioPlayer) {\n\t\tthis.connection = connection;\n\t\tthis.player = player;\n\t}\n\n\t/**\n\t * Unsubscribes the connection from the audio player, meaning that the\n\t * audio player cannot stream audio to it until a new subscription is made.\n\t */\n\tpublic unsubscribe() {\n\t\tthis.connection['onSubscriptionRemoved'](this);\n\t\tthis.player['unsubscribe'](this);\n\t}\n}\n","/* eslint-disable @typescript-eslint/method-signature-style */\nimport { EventEmitter } from 'node:events';\n\n/**\n * The known data for a user in a Discord voice connection.\n */\nexport interface VoiceUserData {\n\t/**\n\t * The SSRC of the user's audio stream.\n\t */\n\taudioSSRC: number;\n\n\t/**\n\t * The SSRC of the user's video stream (if one exists)\n\t * Cannot be 0. If undefined, the user has no video stream.\n\t */\n\tvideoSSRC?: number;\n\n\t/**\n\t * The Discord user id of the user.\n\t */\n\tuserId: string;\n}\n\nexport interface SSRCMap extends EventEmitter {\n\ton(event: 'create', listener: (newData: VoiceUserData) => void): this;\n\ton(event: 'update', listener: (oldData: VoiceUserData | undefined, newData: VoiceUserData) => void): this;\n\ton(event: 'delete', listener: (deletedData: VoiceUserData) => void): this;\n}\n\n/**\n * Maps audio SSRCs to data of users in voice connections.\n */\nexport class SSRCMap extends EventEmitter {\n\t/**\n\t * The underlying map.\n\t */\n\tprivate readonly map: Map;\n\n\tpublic constructor() {\n\t\tsuper();\n\t\tthis.map = new Map();\n\t}\n\n\t/**\n\t * Updates the map with new user data\n\t *\n\t * @param data - The data to update with\n\t */\n\tpublic update(data: VoiceUserData) {\n\t\tconst existing = this.map.get(data.audioSSRC);\n\n\t\tconst newValue = {\n\t\t\t...this.map.get(data.audioSSRC),\n\t\t\t...data,\n\t\t};\n\n\t\tthis.map.set(data.audioSSRC, newValue);\n\t\tif (!existing) this.emit('create', newValue);\n\t\tthis.emit('update', existing, newValue);\n\t}\n\n\t/**\n\t * Gets the stored voice data of a user.\n\t *\n\t * @param target - The target, either their user id or audio SSRC\n\t */\n\tpublic get(target: number | string) {\n\t\tif (typeof target === 'number') {\n\t\t\treturn this.map.get(target);\n\t\t}\n\n\t\tfor (const data of this.map.values()) {\n\t\t\tif (data.userId === target) {\n\t\t\t\treturn data;\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Deletes the stored voice data about a user.\n\t *\n\t * @param target - The target of the delete operation, either their audio SSRC or user id\n\t *\n\t * @returns The data that was deleted, if any\n\t */\n\tpublic delete(target: number | string) {\n\t\tif (typeof target === 'number') {\n\t\t\tconst existing = this.map.get(target);\n\t\t\tif (existing) {\n\t\t\t\tthis.map.delete(target);\n\t\t\t\tthis.emit('delete', existing);\n\t\t\t}\n\t\t\treturn existing;\n\t\t}\n\n\t\tfor (const [audioSSRC, data] of this.map.entries()) {\n\t\t\tif (data.userId === target) {\n\t\t\t\tthis.map.delete(audioSSRC);\n\t\t\t\tthis.emit('delete', data);\n\t\t\t\treturn data;\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n}\n","/* eslint-disable @typescript-eslint/method-signature-style, @typescript-eslint/unified-signatures */\nimport { EventEmitter } from 'node:events';\n\nexport interface SpeakingMap extends EventEmitter {\n\t/**\n\t * Emitted when a user starts speaking.\n\t * @event\n\t */\n\ton(event: 'start', listener: (userId: string) => void): this;\n\n\t/**\n\t * Emitted when a user ends speaking.\n\t * @event\n\t */\n\ton(event: 'end', listener: (userId: string) => void): this;\n}\n\n/**\n * Tracks the speaking states of users in a voice channel.\n */\nexport class SpeakingMap extends EventEmitter {\n\t/**\n\t * The delay after a packet is received from a user until they're marked as not speaking anymore.\n\t */\n\tpublic static readonly DELAY = 100;\n\n\t/**\n\t * The currently speaking users, mapped to the milliseconds since UNIX epoch at which they started speaking.\n\t */\n\tpublic readonly users: Map;\n\n\tprivate readonly speakingTimeouts: Map;\n\n\tpublic constructor() {\n\t\tsuper();\n\t\tthis.users = new Map();\n\t\tthis.speakingTimeouts = new Map();\n\t}\n\n\tpublic onPacket(userId: string) {\n\t\tconst timeout = this.speakingTimeouts.get(userId);\n\t\tif (timeout) {\n\t\t\tclearTimeout(timeout);\n\t\t} else {\n\t\t\tthis.users.set(userId, Date.now());\n\t\t\tthis.emit('start', userId);\n\t\t}\n\t\tthis.startTimeout(userId);\n\t}\n\n\tprivate startTimeout(userId: string) {\n\t\tthis.speakingTimeouts.set(\n\t\t\tuserId,\n\t\t\tsetTimeout(() => {\n\t\t\t\tthis.emit('end', userId);\n\t\t\t\tthis.speakingTimeouts.delete(userId);\n\t\t\t\tthis.users.delete(userId);\n\t\t\t}, SpeakingMap.DELAY),\n\t\t);\n\t}\n}\n","import type { JoinConfig } from './DataStore';\nimport { createVoiceConnection } from './VoiceConnection';\nimport type { DiscordGatewayAdapterCreator } from './util/adapter';\n\n/**\n * The options that can be given when creating a voice connection.\n */\nexport interface CreateVoiceConnectionOptions {\n\t/**\n\t * If true, debug messages will be enabled for the voice connection and its\n\t * related components. Defaults to false.\n\t */\n\tdebug?: boolean;\n\n\tadapterCreator: DiscordGatewayAdapterCreator;\n}\n\n/**\n * The options that can be given when joining a voice channel.\n */\nexport interface JoinVoiceChannelOptions {\n\t/**\n\t * The id of the Discord voice channel to join.\n\t */\n\tchannelId: string;\n\n\t/**\n\t * The id of the guild that the voice channel belongs to.\n\t */\n\tguildId: string;\n\n\t/**\n\t * Whether to join the channel deafened (defaults to true)\n\t */\n\tselfDeaf?: boolean;\n\n\t/**\n\t * Whether to join the channel muted (defaults to true)\n\t */\n\tselfMute?: boolean;\n\n\t/**\n\t * An optional group identifier for the voice connection.\n\t */\n\tgroup?: string;\n}\n\n/**\n * Creates a VoiceConnection to a Discord voice channel.\n *\n * @param voiceChannel - the voice channel to connect to\n * @param options - the options for joining the voice channel\n */\nexport function joinVoiceChannel(options: JoinVoiceChannelOptions & CreateVoiceConnectionOptions) {\n\tconst joinConfig: JoinConfig = {\n\t\tselfDeaf: true,\n\t\tselfMute: false,\n\t\tgroup: 'default',\n\t\t...options,\n\t};\n\n\treturn createVoiceConnection(joinConfig, {\n\t\tadapterCreator: options.adapterCreator,\n\t\tdebug: options.debug,\n\t});\n}\n","import { pipeline, Readable } from 'node:stream';\nimport prism from 'prism-media';\nimport { AudioPlayer, SILENCE_FRAME } from './AudioPlayer';\nimport { Edge, findPipeline, StreamType, TransformerType } from './TransformerGraph';\nimport { noop } from '../util/util';\n\n/**\n * Options that are set when creating a new audio resource.\n *\n * @template T - the type for the metadata (if any) of the audio resource\n */\nexport interface CreateAudioResourceOptions {\n\t/**\n\t * The type of the input stream. Defaults to `StreamType.Arbitrary`.\n\t */\n\tinputType?: StreamType;\n\n\t/**\n\t * Optional metadata that can be attached to the resource (e.g. track title, random id).\n\t * This is useful for identification purposes when the resource is passed around in events.\n\t * See {@link AudioResource.metadata}\n\t */\n\tmetadata?: T;\n\n\t/**\n\t * Whether or not inline volume should be enabled. If enabled, you will be able to change the volume\n\t * of the stream on-the-fly. However, this also increases the performance cost of playback. Defaults to `false`.\n\t */\n\tinlineVolume?: boolean;\n\n\t/**\n\t * The number of silence frames to append to the end of the resource's audio stream, to prevent interpolation glitches.\n\t * Defaults to 5.\n\t */\n\tsilencePaddingFrames?: number;\n}\n\n/**\n * Represents an audio resource that can be played by an audio player.\n *\n * @template T - the type for the metadata (if any) of the audio resource\n */\nexport class AudioResource {\n\t/**\n\t * An object-mode Readable stream that emits Opus packets. This is what is played by audio players.\n\t */\n\tpublic readonly playStream: Readable;\n\n\t/**\n\t * The pipeline used to convert the input stream into a playable format. For example, this may\n\t * contain an FFmpeg component for arbitrary inputs, and it may contain a VolumeTransformer component\n\t * for resources with inline volume transformation enabled.\n\t */\n\tpublic readonly edges: readonly Edge[];\n\n\t/**\n\t * Optional metadata that can be used to identify the resource.\n\t */\n\tpublic metadata: T;\n\n\t/**\n\t * If the resource was created with inline volume transformation enabled, then this will be a\n\t * prism-media VolumeTransformer. You can use this to alter the volume of the stream.\n\t */\n\tpublic readonly volume?: prism.VolumeTransformer;\n\n\t/**\n\t * If using an Opus encoder to create this audio resource, then this will be a prism-media opus.Encoder.\n\t * You can use this to control settings such as bitrate, FEC, PLP.\n\t */\n\tpublic readonly encoder?: prism.opus.Encoder;\n\n\t/**\n\t * The audio player that the resource is subscribed to, if any.\n\t */\n\tpublic audioPlayer?: AudioPlayer;\n\n\t/**\n\t * The playback duration of this audio resource, given in milliseconds.\n\t */\n\tpublic playbackDuration = 0;\n\n\t/**\n\t * Whether or not the stream for this resource has started (data has become readable)\n\t */\n\tpublic started = false;\n\n\t/**\n\t * The number of silence frames to append to the end of the resource's audio stream, to prevent interpolation glitches.\n\t */\n\tpublic readonly silencePaddingFrames: number;\n\n\t/**\n\t * The number of remaining silence frames to play. If -1, the frames have not yet started playing.\n\t */\n\tpublic silenceRemaining = -1;\n\n\tpublic constructor(edges: readonly Edge[], streams: readonly Readable[], metadata: T, silencePaddingFrames: number) {\n\t\tthis.edges = edges;\n\t\tthis.playStream = streams.length > 1 ? (pipeline(streams, noop) as any as Readable) : streams[0]!;\n\t\tthis.metadata = metadata;\n\t\tthis.silencePaddingFrames = silencePaddingFrames;\n\n\t\tfor (const stream of streams) {\n\t\t\tif (stream instanceof prism.VolumeTransformer) {\n\t\t\t\tthis.volume = stream;\n\t\t\t} else if (stream instanceof prism.opus.Encoder) {\n\t\t\t\tthis.encoder = stream;\n\t\t\t}\n\t\t}\n\n\t\tthis.playStream.once('readable', () => (this.started = true));\n\t}\n\n\t/**\n\t * Whether this resource is readable. If the underlying resource is no longer readable, this will still return true\n\t * while there are silence padding frames left to play.\n\t */\n\tpublic get readable() {\n\t\tif (this.silenceRemaining === 0) return false;\n\t\tconst real = this.playStream.readable;\n\t\tif (!real) {\n\t\t\tif (this.silenceRemaining === -1) this.silenceRemaining = this.silencePaddingFrames;\n\t\t\treturn this.silenceRemaining !== 0;\n\t\t}\n\t\treturn real;\n\t}\n\n\t/**\n\t * Whether this resource has ended or not.\n\t */\n\tpublic get ended() {\n\t\treturn this.playStream.readableEnded || this.playStream.destroyed || this.silenceRemaining === 0;\n\t}\n\n\t/**\n\t * Attempts to read an Opus packet from the audio resource. If a packet is available, the playbackDuration\n\t * is incremented.\n\t *\n\t * @remarks\n\t * It is advisable to check that the playStream is readable before calling this method. While no runtime\n\t * errors will be thrown, you should check that the resource is still available before attempting to\n\t * read from it.\n\t *\n\t * @internal\n\t */\n\tpublic read(): Buffer | null {\n\t\tif (this.silenceRemaining === 0) {\n\t\t\treturn null;\n\t\t} else if (this.silenceRemaining > 0) {\n\t\t\tthis.silenceRemaining--;\n\t\t\treturn SILENCE_FRAME;\n\t\t}\n\t\tconst packet = this.playStream.read() as Buffer | null;\n\t\tif (packet) {\n\t\t\tthis.playbackDuration += 20;\n\t\t}\n\t\treturn packet;\n\t}\n}\n\n/**\n * Ensures that a path contains at least one volume transforming component.\n *\n * @param path - The path to validate constraints on\n */\nexport const VOLUME_CONSTRAINT = (path: Edge[]) => path.some((edge) => edge.type === TransformerType.InlineVolume);\n\nexport const NO_CONSTRAINT = () => true;\n\n/**\n * Tries to infer the type of a stream to aid with transcoder pipelining.\n *\n * @param stream - The stream to infer the type of\n */\nexport function inferStreamType(stream: Readable): {\n\tstreamType: StreamType;\n\thasVolume: boolean;\n} {\n\tif (stream instanceof prism.opus.Encoder) {\n\t\treturn { streamType: StreamType.Opus, hasVolume: false };\n\t} else if (stream instanceof prism.opus.Decoder) {\n\t\treturn { streamType: StreamType.Raw, hasVolume: false };\n\t} else if (stream instanceof prism.VolumeTransformer) {\n\t\treturn { streamType: StreamType.Raw, hasVolume: true };\n\t} else if (stream instanceof prism.opus.OggDemuxer) {\n\t\treturn { streamType: StreamType.Opus, hasVolume: false };\n\t} else if (stream instanceof prism.opus.WebmDemuxer) {\n\t\treturn { streamType: StreamType.Opus, hasVolume: false };\n\t}\n\treturn { streamType: StreamType.Arbitrary, hasVolume: false };\n}\n\n/**\n * Creates an audio resource that can be played by audio players.\n *\n * @remarks\n * If the input is given as a string, then the inputType option will be overridden and FFmpeg will be used.\n *\n * If the input is not in the correct format, then a pipeline of transcoders and transformers will be created\n * to ensure that the resultant stream is in the correct format for playback. This could involve using FFmpeg,\n * Opus transcoders, and Ogg/WebM demuxers.\n *\n * @param input - The resource to play\n * @param options - Configurable options for creating the resource\n *\n * @template T - the type for the metadata (if any) of the audio resource\n */\nexport function createAudioResource(\n\tinput: string | Readable,\n\toptions: CreateAudioResourceOptions &\n\t\tPick<\n\t\t\tT extends null | undefined ? CreateAudioResourceOptions : Required>,\n\t\t\t'metadata'\n\t\t>,\n): AudioResource;\n\n/**\n * Creates an audio resource that can be played by audio players.\n *\n * @remarks\n * If the input is given as a string, then the inputType option will be overridden and FFmpeg will be used.\n *\n * If the input is not in the correct format, then a pipeline of transcoders and transformers will be created\n * to ensure that the resultant stream is in the correct format for playback. This could involve using FFmpeg,\n * Opus transcoders, and Ogg/WebM demuxers.\n *\n * @param input - The resource to play\n * @param options - Configurable options for creating the resource\n *\n * @template T - the type for the metadata (if any) of the audio resource\n */\nexport function createAudioResource(\n\tinput: string | Readable,\n\toptions?: Omit, 'metadata'>,\n): AudioResource;\n\n/**\n * Creates an audio resource that can be played by audio players.\n *\n * @remarks\n * If the input is given as a string, then the inputType option will be overridden and FFmpeg will be used.\n *\n * If the input is not in the correct format, then a pipeline of transcoders and transformers will be created\n * to ensure that the resultant stream is in the correct format for playback. This could involve using FFmpeg,\n * Opus transcoders, and Ogg/WebM demuxers.\n *\n * @param input - The resource to play\n * @param options - Configurable options for creating the resource\n *\n * @template T - the type for the metadata (if any) of the audio resource\n */\nexport function createAudioResource(\n\tinput: string | Readable,\n\toptions: CreateAudioResourceOptions = {},\n): AudioResource {\n\tlet inputType = options.inputType;\n\tlet needsInlineVolume = Boolean(options.inlineVolume);\n\n\t// string inputs can only be used with FFmpeg\n\tif (typeof input === 'string') {\n\t\tinputType = StreamType.Arbitrary;\n\t} else if (typeof inputType === 'undefined') {\n\t\tconst analysis = inferStreamType(input);\n\t\tinputType = analysis.streamType;\n\t\tneedsInlineVolume = needsInlineVolume && !analysis.hasVolume;\n\t}\n\n\tconst transformerPipeline = findPipeline(inputType, needsInlineVolume ? VOLUME_CONSTRAINT : NO_CONSTRAINT);\n\n\tif (transformerPipeline.length === 0) {\n\t\tif (typeof input === 'string') throw new Error(`Invalid pipeline constructed for string resource '${input}'`);\n\t\t// No adjustments required\n\t\treturn new AudioResource([], [input], (options.metadata ?? null) as T, options.silencePaddingFrames ?? 5);\n\t}\n\tconst streams = transformerPipeline.map((edge) => edge.transformer(input));\n\tif (typeof input !== 'string') streams.unshift(input);\n\n\treturn new AudioResource(\n\t\ttransformerPipeline,\n\t\tstreams,\n\t\t(options.metadata ?? null) as T,\n\t\toptions.silencePaddingFrames ?? 5,\n\t);\n}\n","import type { Readable } from 'node:stream';\nimport prism from 'prism-media';\n\n/**\n * This module creates a Transformer Graph to figure out what the most efficient way\n * of transforming the input stream into something playable would be.\n */\n\nconst FFMPEG_PCM_ARGUMENTS = ['-analyzeduration', '0', '-loglevel', '0', '-f', 's16le', '-ar', '48000', '-ac', '2'];\nconst FFMPEG_OPUS_ARGUMENTS = [\n\t'-analyzeduration',\n\t'0',\n\t'-loglevel',\n\t'0',\n\t'-acodec',\n\t'libopus',\n\t'-f',\n\t'opus',\n\t'-ar',\n\t'48000',\n\t'-ac',\n\t'2',\n];\n\n/**\n * The different types of stream that can exist within the pipeline.\n *\n * @remarks\n * - `Arbitrary` - the type of the stream at this point is unknown.\n * - `Raw` - the stream at this point is s16le PCM.\n * - `OggOpus` - the stream at this point is Opus audio encoded in an Ogg wrapper.\n * - `WebmOpus` - the stream at this point is Opus audio encoded in a WebM wrapper.\n * - `Opus` - the stream at this point is Opus audio, and the stream is in object-mode. This is ready to play.\n */\nexport enum StreamType {\n\tArbitrary = 'arbitrary',\n\tRaw = 'raw',\n\tOggOpus = 'ogg/opus',\n\tWebmOpus = 'webm/opus',\n\tOpus = 'opus',\n}\n\n/**\n * The different types of transformers that can exist within the pipeline.\n */\nexport enum TransformerType {\n\tFFmpegPCM = 'ffmpeg pcm',\n\tFFmpegOgg = 'ffmpeg ogg',\n\tOpusEncoder = 'opus encoder',\n\tOpusDecoder = 'opus decoder',\n\tOggOpusDemuxer = 'ogg/opus demuxer',\n\tWebmOpusDemuxer = 'webm/opus demuxer',\n\tInlineVolume = 'volume transformer',\n}\n\n/**\n * Represents a pathway from one stream type to another using a transformer.\n */\nexport interface Edge {\n\tfrom: Node;\n\tto: Node;\n\tcost: number;\n\ttransformer: (input: string | Readable) => Readable;\n\ttype: TransformerType;\n}\n\n/**\n * Represents a type of stream within the graph, e.g. an Opus stream, or a stream of raw audio.\n */\nexport class Node {\n\t/**\n\t * The outbound edges from this node.\n\t */\n\tpublic readonly edges: Edge[] = [];\n\n\t/**\n\t * The type of stream for this node.\n\t */\n\tpublic readonly type: StreamType;\n\n\tpublic constructor(type: StreamType) {\n\t\tthis.type = type;\n\t}\n\n\t/**\n\t * Creates an outbound edge from this node.\n\t *\n\t * @param edge - The edge to create\n\t */\n\tpublic addEdge(edge: Omit) {\n\t\tthis.edges.push({ ...edge, from: this });\n\t}\n}\n\n// Create a node for each stream type\nconst NODES = new Map();\nfor (const streamType of Object.values(StreamType)) {\n\tNODES.set(streamType, new Node(streamType));\n}\n\n/**\n * Gets a node from its stream type.\n *\n * @param type - The stream type of the target node\n */\nexport function getNode(type: StreamType) {\n\tconst node = NODES.get(type);\n\tif (!node) throw new Error(`Node type '${type}' does not exist!`);\n\treturn node;\n}\n\ngetNode(StreamType.Raw).addEdge({\n\ttype: TransformerType.OpusEncoder,\n\tto: getNode(StreamType.Opus),\n\tcost: 1.5,\n\ttransformer: () => new prism.opus.Encoder({ rate: 48000, channels: 2, frameSize: 960 }),\n});\n\ngetNode(StreamType.Opus).addEdge({\n\ttype: TransformerType.OpusDecoder,\n\tto: getNode(StreamType.Raw),\n\tcost: 1.5,\n\ttransformer: () => new prism.opus.Decoder({ rate: 48000, channels: 2, frameSize: 960 }),\n});\n\ngetNode(StreamType.OggOpus).addEdge({\n\ttype: TransformerType.OggOpusDemuxer,\n\tto: getNode(StreamType.Opus),\n\tcost: 1,\n\ttransformer: () => new prism.opus.OggDemuxer(),\n});\n\ngetNode(StreamType.WebmOpus).addEdge({\n\ttype: TransformerType.WebmOpusDemuxer,\n\tto: getNode(StreamType.Opus),\n\tcost: 1,\n\ttransformer: () => new prism.opus.WebmDemuxer(),\n});\n\nconst FFMPEG_PCM_EDGE: Omit = {\n\ttype: TransformerType.FFmpegPCM,\n\tto: getNode(StreamType.Raw),\n\tcost: 2,\n\ttransformer: (input) =>\n\t\tnew prism.FFmpeg({\n\t\t\targs: typeof input === 'string' ? ['-i', input, ...FFMPEG_PCM_ARGUMENTS] : FFMPEG_PCM_ARGUMENTS,\n\t\t}),\n};\n\ngetNode(StreamType.Arbitrary).addEdge(FFMPEG_PCM_EDGE);\ngetNode(StreamType.OggOpus).addEdge(FFMPEG_PCM_EDGE);\ngetNode(StreamType.WebmOpus).addEdge(FFMPEG_PCM_EDGE);\n\ngetNode(StreamType.Raw).addEdge({\n\ttype: TransformerType.InlineVolume,\n\tto: getNode(StreamType.Raw),\n\tcost: 0.5,\n\ttransformer: () => new prism.VolumeTransformer({ type: 's16le' }),\n});\n\n// Try to enable FFmpeg Ogg optimizations\nfunction canEnableFFmpegOptimizations(): boolean {\n\ttry {\n\t\treturn prism.FFmpeg.getInfo().output.includes('--enable-libopus');\n\t} catch {}\n\treturn false;\n}\n\nif (canEnableFFmpegOptimizations()) {\n\tconst FFMPEG_OGG_EDGE: Omit = {\n\t\ttype: TransformerType.FFmpegOgg,\n\t\tto: getNode(StreamType.OggOpus),\n\t\tcost: 2,\n\t\ttransformer: (input) =>\n\t\t\tnew prism.FFmpeg({\n\t\t\t\targs: typeof input === 'string' ? ['-i', input, ...FFMPEG_OPUS_ARGUMENTS] : FFMPEG_OPUS_ARGUMENTS,\n\t\t\t}),\n\t};\n\tgetNode(StreamType.Arbitrary).addEdge(FFMPEG_OGG_EDGE);\n\t// Include Ogg and WebM as well in case they have different sampling rates or are mono instead of stereo\n\t// at the moment, this will not do anything. However, if/when detection for correct Opus headers is\n\t// implemented, this will help inform the voice engine that it is able to transcode the audio.\n\tgetNode(StreamType.OggOpus).addEdge(FFMPEG_OGG_EDGE);\n\tgetNode(StreamType.WebmOpus).addEdge(FFMPEG_OGG_EDGE);\n}\n\n/**\n * Represents a step in the path from node A to node B.\n */\ninterface Step {\n\t/**\n\t * The next step.\n\t */\n\tnext?: Step;\n\n\t/**\n\t * The cost of the steps after this step.\n\t */\n\tcost: number;\n\n\t/**\n\t * The edge associated with this step.\n\t */\n\tedge?: Edge;\n}\n\n/**\n * Finds the shortest cost path from node A to node B.\n *\n * @param from - The start node\n * @param constraints - Extra validation for a potential solution. Takes a path, returns true if the path is valid\n * @param goal - The target node\n * @param path - The running path\n * @param depth - The number of remaining recursions\n */\nfunction findPath(\n\tfrom: Node,\n\tconstraints: (path: Edge[]) => boolean,\n\tgoal = getNode(StreamType.Opus),\n\tpath: Edge[] = [],\n\tdepth = 5,\n): Step {\n\tif (from === goal && constraints(path)) {\n\t\treturn { cost: 0 };\n\t} else if (depth === 0) {\n\t\treturn { cost: Infinity };\n\t}\n\n\tlet currentBest: Step | undefined = undefined;\n\tfor (const edge of from.edges) {\n\t\tif (currentBest && edge.cost > currentBest.cost) continue;\n\t\tconst next = findPath(edge.to, constraints, goal, [...path, edge], depth - 1);\n\t\tconst cost = edge.cost + next.cost;\n\t\tif (!currentBest || cost < currentBest.cost) {\n\t\t\tcurrentBest = { cost, edge, next };\n\t\t}\n\t}\n\treturn currentBest ?? { cost: Infinity };\n}\n\n/**\n * Takes the solution from findPath and assembles it into a list of edges.\n *\n * @param step - The first step of the path\n */\nfunction constructPipeline(step: Step) {\n\tconst edges = [];\n\tlet current: Step | undefined = step;\n\twhile (current?.edge) {\n\t\tedges.push(current.edge);\n\t\tcurrent = current.next;\n\t}\n\treturn edges;\n}\n\n/**\n * Finds the lowest-cost pipeline to convert the input stream type into an Opus stream.\n *\n * @param from - The stream type to start from\n * @param constraint - Extra constraints that may be imposed on potential solution\n */\nexport function findPipeline(from: StreamType, constraint: (path: Edge[]) => boolean) {\n\treturn constructPipeline(findPath(getNode(from), constraint));\n}\n","/* eslint-disable @typescript-eslint/no-var-requires */\n/* eslint-disable @typescript-eslint/no-require-imports */\nimport { resolve, dirname } from 'node:path';\nimport prism from 'prism-media';\n\n/**\n * Tries to find the package.json file for a given module.\n *\n * @param dir - The directory to look in\n * @param packageName - The name of the package to look for\n * @param depth - The maximum recursion depth\n */\nfunction findPackageJSON(\n\tdir: string,\n\tpackageName: string,\n\tdepth: number,\n): { name: string; version: string } | undefined {\n\tif (depth === 0) return undefined;\n\tconst attemptedPath = resolve(dir, './package.json');\n\ttry {\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\tconst pkg = require(attemptedPath);\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\tif (pkg.name !== packageName) throw new Error('package.json does not match');\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-return\n\t\treturn pkg;\n\t} catch (err) {\n\t\treturn findPackageJSON(resolve(dir, '..'), packageName, depth - 1);\n\t}\n}\n\n/**\n * Tries to find the version of a dependency.\n *\n * @param name - The package to find the version of\n */\nfunction version(name: string): string {\n\ttry {\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\tconst pkg =\n\t\t\tname === '@discordjs/voice'\n\t\t\t\t? require('../../package.json')\n\t\t\t\t: findPackageJSON(dirname(require.resolve(name)), name, 3);\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access\n\t\treturn pkg?.version ?? 'not found';\n\t} catch (err) {\n\t\treturn 'not found';\n\t}\n}\n\n/**\n * Generates a report of the dependencies used by the \\@discordjs/voice module.\n * Useful for debugging.\n */\nexport function generateDependencyReport() {\n\tconst report = [];\n\tconst addVersion = (name: string) => report.push(`- ${name}: ${version(name)}`);\n\t// general\n\treport.push('Core Dependencies');\n\taddVersion('@discordjs/voice');\n\taddVersion('prism-media');\n\treport.push('');\n\n\t// opus\n\treport.push('Opus Libraries');\n\taddVersion('@discordjs/opus');\n\taddVersion('opusscript');\n\treport.push('');\n\n\t// encryption\n\treport.push('Encryption Libraries');\n\taddVersion('sodium-native');\n\taddVersion('sodium');\n\taddVersion('libsodium-wrappers');\n\taddVersion('tweetnacl');\n\treport.push('');\n\n\t// ffmpeg\n\treport.push('FFmpeg');\n\ttry {\n\t\tconst info = prism.FFmpeg.getInfo();\n\t\treport.push(`- version: ${info.version}`);\n\t\treport.push(`- libopus: ${info.output.includes('--enable-libopus') ? 'yes' : 'no'}`);\n\t} catch (err) {\n\t\treport.push('- not found');\n\t}\n\n\treturn ['-'.repeat(50), ...report, '-'.repeat(50)].join('\\n');\n}\n","import EventEmitter, { once } from 'node:events';\nimport { abortAfter } from './abortAfter';\nimport type { VoiceConnection, VoiceConnectionStatus } from '../VoiceConnection';\nimport type { AudioPlayer, AudioPlayerStatus } from '../audio/AudioPlayer';\n\n/**\n * Allows a voice connection a specified amount of time to enter a given state, otherwise rejects with an error.\n *\n * @param target - The voice connection that we want to observe the state change for\n * @param status - The status that the voice connection should be in\n * @param timeoutOrSignal - The maximum time we are allowing for this to occur, or a signal that will abort the operation\n */\nexport function entersState(\n\ttarget: VoiceConnection,\n\tstatus: VoiceConnectionStatus,\n\ttimeoutOrSignal: number | AbortSignal,\n): Promise;\n\n/**\n * Allows an audio player a specified amount of time to enter a given state, otherwise rejects with an error.\n *\n * @param target - The audio player that we want to observe the state change for\n * @param status - The status that the audio player should be in\n * @param timeoutOrSignal - The maximum time we are allowing for this to occur, or a signal that will abort the operation\n */\nexport function entersState(\n\ttarget: AudioPlayer,\n\tstatus: AudioPlayerStatus,\n\ttimeoutOrSignal: number | AbortSignal,\n): Promise;\n\n/**\n * Allows a target a specified amount of time to enter a given state, otherwise rejects with an error.\n *\n * @param target - The object that we want to observe the state change for\n * @param status - The status that the target should be in\n * @param timeoutOrSignal - The maximum time we are allowing for this to occur, or a signal that will abort the operation\n */\nexport async function entersState(\n\ttarget: T,\n\tstatus: VoiceConnectionStatus | AudioPlayerStatus,\n\ttimeoutOrSignal: number | AbortSignal,\n) {\n\tif (target.state.status !== status) {\n\t\tconst [ac, signal] =\n\t\t\ttypeof timeoutOrSignal === 'number' ? abortAfter(timeoutOrSignal) : [undefined, timeoutOrSignal];\n\t\ttry {\n\t\t\tawait once(target as EventEmitter, status, { signal });\n\t\t} finally {\n\t\t\tac?.abort();\n\t\t}\n\t}\n\treturn target;\n}\n","/**\n * Creates an abort controller that aborts after the given time.\n *\n * @param delay - The time in milliseconds to wait before aborting\n */\nexport function abortAfter(delay: number): [AbortController, AbortSignal] {\n\tconst ac = new AbortController();\n\tconst timeout = setTimeout(() => ac.abort(), delay);\n\t// @ts-expect-error\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-call\n\tac.signal.addEventListener('abort', () => clearTimeout(timeout));\n\treturn [ac, ac.signal];\n}\n","import { Readable } from 'node:stream';\nimport prism from 'prism-media';\nimport { noop } from './util';\nimport { StreamType } from '..';\n\n/**\n * Takes an Opus Head, and verifies whether the associated Opus audio is suitable to play in a Discord voice channel.\n *\n * @param opusHead - The Opus Head to validate\n *\n * @returns `true` if suitable to play in a Discord voice channel, otherwise `false`\n */\nexport function validateDiscordOpusHead(opusHead: Buffer): boolean {\n\tconst channels = opusHead.readUInt8(9);\n\tconst sampleRate = opusHead.readUInt32LE(12);\n\treturn channels === 2 && sampleRate === 48000;\n}\n\n/**\n * The resulting information after probing an audio stream\n */\nexport interface ProbeInfo {\n\t/**\n\t * The readable audio stream to use. You should use this rather than the input stream, as the probing\n\t * function can sometimes read the input stream to its end and cause the stream to close.\n\t */\n\tstream: Readable;\n\n\t/**\n\t * The recommended stream type for this audio stream.\n\t */\n\ttype: StreamType;\n}\n\n/**\n * Attempt to probe a readable stream to figure out whether it can be demuxed using an Ogg or WebM Opus demuxer.\n *\n * @param stream - The readable stream to probe\n * @param probeSize - The number of bytes to attempt to read before giving up on the probe\n * @param validator - The Opus Head validator function\n *\n * @experimental\n */\nexport function demuxProbe(\n\tstream: Readable,\n\tprobeSize = 1024,\n\tvalidator = validateDiscordOpusHead,\n): Promise {\n\treturn new Promise((resolve, reject) => {\n\t\t// Preconditions\n\t\tif (stream.readableObjectMode) return reject(new Error('Cannot probe a readable stream in object mode'));\n\t\tif (stream.readableEnded) return reject(new Error('Cannot probe a stream that has ended'));\n\n\t\tlet readBuffer = Buffer.alloc(0);\n\n\t\tlet resolved: StreamType | undefined = undefined;\n\n\t\tconst finish = (type: StreamType) => {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\t\tstream.off('data', onData);\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\t\tstream.off('close', onClose);\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\t\tstream.off('end', onClose);\n\t\t\tstream.pause();\n\t\t\tresolved = type;\n\t\t\tif (stream.readableEnded) {\n\t\t\t\tresolve({\n\t\t\t\t\tstream: Readable.from(readBuffer),\n\t\t\t\t\ttype,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (readBuffer.length > 0) {\n\t\t\t\t\tstream.push(readBuffer);\n\t\t\t\t}\n\t\t\t\tresolve({\n\t\t\t\t\tstream,\n\t\t\t\t\ttype,\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\n\t\tconst foundHead = (type: StreamType) => (head: Buffer) => {\n\t\t\tif (validator(head)) {\n\t\t\t\tfinish(type);\n\t\t\t}\n\t\t};\n\n\t\tconst webm = new prism.opus.WebmDemuxer();\n\t\twebm.once('error', noop);\n\t\twebm.on('head', foundHead(StreamType.WebmOpus));\n\n\t\tconst ogg = new prism.opus.OggDemuxer();\n\t\togg.once('error', noop);\n\t\togg.on('head', foundHead(StreamType.OggOpus));\n\n\t\tconst onClose = () => {\n\t\t\tif (!resolved) {\n\t\t\t\tfinish(StreamType.Arbitrary);\n\t\t\t}\n\t\t};\n\n\t\tconst onData = (buffer: Buffer) => {\n\t\t\treadBuffer = Buffer.concat([readBuffer, buffer]);\n\n\t\t\twebm.write(buffer);\n\t\t\togg.write(buffer);\n\n\t\t\tif (readBuffer.length >= probeSize) {\n\t\t\t\tstream.off('data', onData);\n\t\t\t\tstream.pause();\n\t\t\t\tprocess.nextTick(onClose);\n\t\t\t}\n\t\t};\n\n\t\tstream.once('error', reject);\n\t\tstream.on('data', onData);\n\t\tstream.once('close', onClose);\n\t\tstream.once('end', onClose);\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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6BAAM;AACrB,UAAI,CAAC,UAAU;AACd,eAAO,2BAAoB;AAAA,MAC5B;AAAA,IACD,GAJgB;AAMhB,UAAM,SAAS,wBAAC,WAAmB;AAClC,mBAAa,OAAO,OAAO,CAAC,YAAY,MAAM,CAAC;AAE/C,WAAK,MAAM,MAAM;AACjB,UAAI,MAAM,MAAM;AAEhB,UAAI,WAAW,UAAU,WAAW;AACnC,eAAO,IAAI,QAAQ,MAAM;AACzB,eAAO,MAAM;AACb,gBAAQ,SAAS,OAAO;AAAA,MACzB;AAAA,IACD,GAXe;AAaf,WAAO,KAAK,SAAS,MAAM;AAC3B,WAAO,GAAG,QAAQ,MAAM;AACxB,WAAO,KAAK,SAAS,OAAO;AAC5B,WAAO,KAAK,OAAO,OAAO;AAAA,EAC3B,CAAC;AACF;AA7EgB;","names":[]} \ No newline at end of file +{"version":3,"sources":["../src/index.ts","../src/VoiceConnection.ts","../src/DataStore.ts","../src/networking/Networking.ts","../src/util/Secretbox.ts","../src/util/util.ts","../src/networking/VoiceUDPSocket.ts","../src/networking/VoiceWebSocket.ts","../src/receive/VoiceReceiver.ts","../src/receive/AudioReceiveStream.ts","../src/audio/AudioPlayer.ts","../src/audio/AudioPlayerError.ts","../src/audio/PlayerSubscription.ts","../src/receive/SSRCMap.ts","../src/receive/SpeakingMap.ts","../src/joinVoiceChannel.ts","../src/audio/AudioResource.ts","../src/audio/TransformerGraph.ts","../src/util/generateDependencyReport.ts","../src/util/entersState.ts","../src/util/abortAfter.ts","../src/util/demuxProbe.ts"],"sourcesContent":["export * from './joinVoiceChannel';\nexport * from './audio/index';\nexport * from './util/index';\nexport * from './receive/index';\n\nexport {\n\tVoiceConnection,\n\ttype VoiceConnectionState,\n\tVoiceConnectionStatus,\n\ttype VoiceConnectionConnectingState,\n\ttype VoiceConnectionDestroyedState,\n\ttype VoiceConnectionDisconnectedState,\n\ttype VoiceConnectionDisconnectedBaseState,\n\ttype VoiceConnectionDisconnectedOtherState,\n\ttype VoiceConnectionDisconnectedWebSocketState,\n\tVoiceConnectionDisconnectReason,\n\ttype VoiceConnectionReadyState,\n\ttype VoiceConnectionSignallingState,\n} from './VoiceConnection';\n\nexport { type JoinConfig, getVoiceConnection, getVoiceConnections, getGroups } from './DataStore';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/voice/#readme | @discordjs/voice} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\nexport const version = '0.16.0' as string;\n","/* eslint-disable @typescript-eslint/unbound-method */\nimport type { Buffer } from 'node:buffer';\nimport { EventEmitter } from 'node:events';\nimport type { GatewayVoiceServerUpdateDispatchData, GatewayVoiceStateUpdateDispatchData } from 'discord-api-types/v10';\nimport type { JoinConfig } from './DataStore';\nimport {\n\tgetVoiceConnection,\n\tcreateJoinVoiceChannelPayload,\n\ttrackVoiceConnection,\n\tuntrackVoiceConnection,\n} from './DataStore';\nimport type { AudioPlayer } from './audio/AudioPlayer';\nimport type { PlayerSubscription } from './audio/PlayerSubscription';\nimport type { VoiceWebSocket, VoiceUDPSocket } from './networking';\nimport { Networking, NetworkingStatusCode, type NetworkingState } from './networking/Networking';\nimport { VoiceReceiver } from './receive/index';\nimport type { DiscordGatewayAdapterImplementerMethods } from './util/adapter';\nimport { noop } from './util/util';\nimport type { CreateVoiceConnectionOptions } from './index';\n\n/**\n * The various status codes a voice connection can hold at any one time.\n */\nexport enum VoiceConnectionStatus {\n\t/**\n\t * The `VOICE_SERVER_UPDATE` and `VOICE_STATE_UPDATE` packets have been received, now attempting to establish a voice connection.\n\t */\n\tConnecting = 'connecting',\n\n\t/**\n\t * The voice connection has been destroyed and untracked, it cannot be reused.\n\t */\n\tDestroyed = 'destroyed',\n\n\t/**\n\t * The voice connection has either been severed or not established.\n\t */\n\tDisconnected = 'disconnected',\n\n\t/**\n\t * A voice connection has been established, and is ready to be used.\n\t */\n\tReady = 'ready',\n\n\t/**\n\t * Sending a packet to the main Discord gateway to indicate we want to change our voice state.\n\t */\n\tSignalling = 'signalling',\n}\n\n/**\n * The state that a VoiceConnection will be in when it is waiting to receive a VOICE_SERVER_UPDATE and\n * VOICE_STATE_UPDATE packet from Discord, provided by the adapter.\n */\nexport interface VoiceConnectionSignallingState {\n\tadapter: DiscordGatewayAdapterImplementerMethods;\n\tstatus: VoiceConnectionStatus.Signalling;\n\tsubscription?: PlayerSubscription | undefined;\n}\n\n/**\n * The reasons a voice connection can be in the disconnected state.\n */\nexport enum VoiceConnectionDisconnectReason {\n\t/**\n\t * When the WebSocket connection has been closed.\n\t */\n\tWebSocketClose,\n\n\t/**\n\t * When the adapter was unable to send a message requested by the VoiceConnection.\n\t */\n\tAdapterUnavailable,\n\n\t/**\n\t * When a VOICE_SERVER_UPDATE packet is received with a null endpoint, causing the connection to be severed.\n\t */\n\tEndpointRemoved,\n\n\t/**\n\t * When a manual disconnect was requested.\n\t */\n\tManual,\n}\n\n/**\n * The state that a VoiceConnection will be in when it is not connected to a Discord voice server nor is\n * it attempting to connect. You can manually attempt to reconnect using VoiceConnection#reconnect.\n */\nexport interface VoiceConnectionDisconnectedBaseState {\n\tadapter: DiscordGatewayAdapterImplementerMethods;\n\tstatus: VoiceConnectionStatus.Disconnected;\n\tsubscription?: PlayerSubscription | undefined;\n}\n\n/**\n * The state that a VoiceConnection will be in when it is not connected to a Discord voice server nor is\n * it attempting to connect. You can manually attempt to reconnect using VoiceConnection#reconnect.\n */\nexport interface VoiceConnectionDisconnectedOtherState extends VoiceConnectionDisconnectedBaseState {\n\treason: Exclude;\n}\n\n/**\n * The state that a VoiceConnection will be in when its WebSocket connection was closed.\n * You can manually attempt to reconnect using VoiceConnection#reconnect.\n */\nexport interface VoiceConnectionDisconnectedWebSocketState extends VoiceConnectionDisconnectedBaseState {\n\t/**\n\t * The close code of the WebSocket connection to the Discord voice server.\n\t */\n\tcloseCode: number;\n\n\treason: VoiceConnectionDisconnectReason.WebSocketClose;\n}\n\n/**\n * The states that a VoiceConnection can be in when it is not connected to a Discord voice server nor is\n * it attempting to connect. You can manually attempt to connect using VoiceConnection#reconnect.\n */\nexport type VoiceConnectionDisconnectedState =\n\t| VoiceConnectionDisconnectedOtherState\n\t| VoiceConnectionDisconnectedWebSocketState;\n\n/**\n * The state that a VoiceConnection will be in when it is establishing a connection to a Discord\n * voice server.\n */\nexport interface VoiceConnectionConnectingState {\n\tadapter: DiscordGatewayAdapterImplementerMethods;\n\tnetworking: Networking;\n\tstatus: VoiceConnectionStatus.Connecting;\n\tsubscription?: PlayerSubscription | undefined;\n}\n\n/**\n * The state that a VoiceConnection will be in when it has an active connection to a Discord\n * voice server.\n */\nexport interface VoiceConnectionReadyState {\n\tadapter: DiscordGatewayAdapterImplementerMethods;\n\tnetworking: Networking;\n\tstatus: VoiceConnectionStatus.Ready;\n\tsubscription?: PlayerSubscription | undefined;\n}\n\n/**\n * The state that a VoiceConnection will be in when it has been permanently been destroyed by the\n * user and untracked by the library. It cannot be reconnected, instead, a new VoiceConnection\n * needs to be established.\n */\nexport interface VoiceConnectionDestroyedState {\n\tstatus: VoiceConnectionStatus.Destroyed;\n}\n\n/**\n * The various states that a voice connection can be in.\n */\nexport type VoiceConnectionState =\n\t| VoiceConnectionConnectingState\n\t| VoiceConnectionDestroyedState\n\t| VoiceConnectionDisconnectedState\n\t| VoiceConnectionReadyState\n\t| VoiceConnectionSignallingState;\n\nexport interface VoiceConnection extends EventEmitter {\n\t/**\n\t * Emitted when there is an error emitted from the voice connection\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'error', listener: (error: Error) => void): this;\n\t/**\n\t * Emitted debugging information about the voice connection\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'debug', listener: (message: string) => void): this;\n\t/**\n\t * Emitted when the state of the voice connection changes\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'stateChange', listener: (oldState: VoiceConnectionState, newState: VoiceConnectionState) => void): this;\n\t/**\n\t * Emitted when the state of the voice connection changes to a specific status\n\t *\n\t * @eventProperty\n\t */\n\ton(\n\t\tevent: T,\n\t\tlistener: (oldState: VoiceConnectionState, newState: VoiceConnectionState & { status: T }) => void,\n\t): this;\n}\n\n/**\n * A connection to the voice server of a Guild, can be used to play audio in voice channels.\n */\nexport class VoiceConnection extends EventEmitter {\n\t/**\n\t * The number of consecutive rejoin attempts. Initially 0, and increments for each rejoin.\n\t * When a connection is successfully established, it resets to 0.\n\t */\n\tpublic rejoinAttempts: number;\n\n\t/**\n\t * The state of the voice connection.\n\t */\n\tprivate _state: VoiceConnectionState;\n\n\t/**\n\t * A configuration storing all the data needed to reconnect to a Guild's voice server.\n\t *\n\t * @internal\n\t */\n\tpublic readonly joinConfig: JoinConfig;\n\n\t/**\n\t * The two packets needed to successfully establish a voice connection. They are received\n\t * from the main Discord gateway after signalling to change the voice state.\n\t */\n\tprivate readonly packets: {\n\t\tserver: GatewayVoiceServerUpdateDispatchData | undefined;\n\t\tstate: GatewayVoiceStateUpdateDispatchData | undefined;\n\t};\n\n\t/**\n\t * The receiver of this voice connection. You should join the voice channel with `selfDeaf` set\n\t * to false for this feature to work properly.\n\t */\n\tpublic readonly receiver: VoiceReceiver;\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: ((message: string) => void) | null;\n\n\t/**\n\t * Creates a new voice connection.\n\t *\n\t * @param joinConfig - The data required to establish the voice connection\n\t * @param options - The options used to create this voice connection\n\t */\n\tpublic constructor(joinConfig: JoinConfig, options: CreateVoiceConnectionOptions) {\n\t\tsuper();\n\n\t\tthis.debug = options.debug ? (message: string) => this.emit('debug', message) : null;\n\t\tthis.rejoinAttempts = 0;\n\n\t\tthis.receiver = new VoiceReceiver(this);\n\n\t\tthis.onNetworkingClose = this.onNetworkingClose.bind(this);\n\t\tthis.onNetworkingStateChange = this.onNetworkingStateChange.bind(this);\n\t\tthis.onNetworkingError = this.onNetworkingError.bind(this);\n\t\tthis.onNetworkingDebug = this.onNetworkingDebug.bind(this);\n\n\t\tconst adapter = options.adapterCreator({\n\t\t\tonVoiceServerUpdate: (data) => this.addServerPacket(data),\n\t\t\tonVoiceStateUpdate: (data) => this.addStatePacket(data),\n\t\t\tdestroy: () => this.destroy(false),\n\t\t});\n\n\t\tthis._state = { status: VoiceConnectionStatus.Signalling, adapter };\n\n\t\tthis.packets = {\n\t\t\tserver: undefined,\n\t\t\tstate: undefined,\n\t\t};\n\n\t\tthis.joinConfig = joinConfig;\n\t}\n\n\t/**\n\t * The current state of the voice connection.\n\t */\n\tpublic get state() {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * Updates the state of the voice connection, performing clean-up operations where necessary.\n\t */\n\tpublic set state(newState: VoiceConnectionState) {\n\t\tconst oldState = this._state;\n\t\tconst oldNetworking = Reflect.get(oldState, 'networking') as Networking | undefined;\n\t\tconst newNetworking = Reflect.get(newState, 'networking') as Networking | undefined;\n\n\t\tconst oldSubscription = Reflect.get(oldState, 'subscription') as PlayerSubscription | undefined;\n\t\tconst newSubscription = Reflect.get(newState, 'subscription') as PlayerSubscription | undefined;\n\n\t\tif (oldNetworking !== newNetworking) {\n\t\t\tif (oldNetworking) {\n\t\t\t\toldNetworking.on('error', noop);\n\t\t\t\toldNetworking.off('debug', this.onNetworkingDebug);\n\t\t\t\toldNetworking.off('error', this.onNetworkingError);\n\t\t\t\toldNetworking.off('close', this.onNetworkingClose);\n\t\t\t\toldNetworking.off('stateChange', this.onNetworkingStateChange);\n\t\t\t\toldNetworking.destroy();\n\t\t\t}\n\n\t\t\tif (newNetworking) this.updateReceiveBindings(newNetworking.state, oldNetworking?.state);\n\t\t}\n\n\t\tif (newState.status === VoiceConnectionStatus.Ready) {\n\t\t\tthis.rejoinAttempts = 0;\n\t\t} else if (newState.status === VoiceConnectionStatus.Destroyed) {\n\t\t\tfor (const stream of this.receiver.subscriptions.values()) {\n\t\t\t\tif (!stream.destroyed) stream.destroy();\n\t\t\t}\n\t\t}\n\n\t\t// If destroyed, the adapter can also be destroyed so it can be cleaned up by the user\n\t\tif (oldState.status !== VoiceConnectionStatus.Destroyed && newState.status === VoiceConnectionStatus.Destroyed) {\n\t\t\toldState.adapter.destroy();\n\t\t}\n\n\t\tthis._state = newState;\n\n\t\tif (oldSubscription && oldSubscription !== newSubscription) {\n\t\t\toldSubscription.unsubscribe();\n\t\t}\n\n\t\tthis.emit('stateChange', oldState, newState);\n\t\tif (oldState.status !== newState.status) {\n\t\t\tthis.emit(newState.status, oldState, newState as any);\n\t\t}\n\t}\n\n\t/**\n\t * Registers a `VOICE_SERVER_UPDATE` packet to the voice connection. This will cause it to reconnect using the\n\t * new data provided in the packet.\n\t *\n\t * @param packet - The received `VOICE_SERVER_UPDATE` packet\n\t */\n\tprivate addServerPacket(packet: GatewayVoiceServerUpdateDispatchData) {\n\t\tthis.packets.server = packet;\n\t\tif (packet.endpoint) {\n\t\t\tthis.configureNetworking();\n\t\t} else if (this.state.status !== VoiceConnectionStatus.Destroyed) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.EndpointRemoved,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Registers a `VOICE_STATE_UPDATE` packet to the voice connection. Most importantly, it stores the id of the\n\t * channel that the client is connected to.\n\t *\n\t * @param packet - The received `VOICE_STATE_UPDATE` packet\n\t */\n\tprivate addStatePacket(packet: GatewayVoiceStateUpdateDispatchData) {\n\t\tthis.packets.state = packet;\n\n\t\tif (packet.self_deaf !== undefined) this.joinConfig.selfDeaf = packet.self_deaf;\n\t\tif (packet.self_mute !== undefined) this.joinConfig.selfMute = packet.self_mute;\n\t\tif (packet.channel_id) this.joinConfig.channelId = packet.channel_id;\n\t\t/*\n\t\t\tthe channel_id being null doesn't necessarily mean it was intended for the client to leave the voice channel\n\t\t\tas it may have disconnected due to network failure. This will be gracefully handled once the voice websocket\n\t\t\tdies, and then it is up to the user to decide how they wish to handle this.\n\t\t*/\n\t}\n\n\t/**\n\t * Called when the networking state changes, and the new ws/udp packet/message handlers need to be rebound\n\t * to the new instances.\n\t *\n\t * @param newState - The new networking state\n\t * @param oldState - The old networking state, if there is one\n\t */\n\tprivate updateReceiveBindings(newState: NetworkingState, oldState?: NetworkingState) {\n\t\tconst oldWs = Reflect.get(oldState ?? {}, 'ws') as VoiceWebSocket | undefined;\n\t\tconst newWs = Reflect.get(newState, 'ws') as VoiceWebSocket | undefined;\n\t\tconst oldUdp = Reflect.get(oldState ?? {}, 'udp') as VoiceUDPSocket | undefined;\n\t\tconst newUdp = Reflect.get(newState, 'udp') as VoiceUDPSocket | undefined;\n\n\t\tif (oldWs !== newWs) {\n\t\t\toldWs?.off('packet', this.receiver.onWsPacket);\n\t\t\tnewWs?.on('packet', this.receiver.onWsPacket);\n\t\t}\n\n\t\tif (oldUdp !== newUdp) {\n\t\t\toldUdp?.off('message', this.receiver.onUdpMessage);\n\t\t\tnewUdp?.on('message', this.receiver.onUdpMessage);\n\t\t}\n\n\t\tthis.receiver.connectionData = Reflect.get(newState, 'connectionData') ?? {};\n\t}\n\n\t/**\n\t * Attempts to configure a networking instance for this voice connection using the received packets.\n\t * Both packets are required, and any existing networking instance will be destroyed.\n\t *\n\t * @remarks\n\t * This is called when the voice server of the connection changes, e.g. if the bot is moved into a\n\t * different channel in the same guild but has a different voice server. In this instance, the connection\n\t * needs to be re-established to the new voice server.\n\t *\n\t * The connection will transition to the Connecting state when this is called.\n\t */\n\tpublic configureNetworking() {\n\t\tconst { server, state } = this.packets;\n\t\tif (!server || !state || this.state.status === VoiceConnectionStatus.Destroyed || !server.endpoint) return;\n\n\t\tconst networking = new Networking(\n\t\t\t{\n\t\t\t\tendpoint: server.endpoint,\n\t\t\t\tserverId: server.guild_id,\n\t\t\t\ttoken: server.token,\n\t\t\t\tsessionId: state.session_id,\n\t\t\t\tuserId: state.user_id,\n\t\t\t},\n\t\t\tBoolean(this.debug),\n\t\t);\n\n\t\tnetworking.once('close', this.onNetworkingClose);\n\t\tnetworking.on('stateChange', this.onNetworkingStateChange);\n\t\tnetworking.on('error', this.onNetworkingError);\n\t\tnetworking.on('debug', this.onNetworkingDebug);\n\n\t\tthis.state = {\n\t\t\t...this.state,\n\t\t\tstatus: VoiceConnectionStatus.Connecting,\n\t\t\tnetworking,\n\t\t};\n\t}\n\n\t/**\n\t * Called when the networking instance for this connection closes. If the close code is 4014 (do not reconnect),\n\t * the voice connection will transition to the Disconnected state which will store the close code. You can\n\t * decide whether or not to reconnect when this occurs by listening for the state change and calling reconnect().\n\t *\n\t * @remarks\n\t * If the close code was anything other than 4014, it is likely that the closing was not intended, and so the\n\t * VoiceConnection will signal to Discord that it would like to rejoin the channel. This automatically attempts\n\t * to re-establish the connection. This would be seen as a transition from the Ready state to the Signalling state.\n\t * @param code - The close code\n\t */\n\tprivate onNetworkingClose(code: number) {\n\t\tif (this.state.status === VoiceConnectionStatus.Destroyed) return;\n\t\t// If networking closes, try to connect to the voice channel again.\n\t\tif (code === 4_014) {\n\t\t\t// Disconnected - networking is already destroyed here\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.WebSocketClose,\n\t\t\t\tcloseCode: code,\n\t\t\t};\n\t\t} else {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Signalling,\n\t\t\t};\n\t\t\tthis.rejoinAttempts++;\n\t\t\tif (!this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) {\n\t\t\t\tthis.state = {\n\t\t\t\t\t...this.state,\n\t\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Called when the state of the networking instance changes. This is used to derive the state of the voice connection.\n\t *\n\t * @param oldState - The previous state\n\t * @param newState - The new state\n\t */\n\tprivate onNetworkingStateChange(oldState: NetworkingState, newState: NetworkingState) {\n\t\tthis.updateReceiveBindings(newState, oldState);\n\t\tif (oldState.code === newState.code) return;\n\t\tif (this.state.status !== VoiceConnectionStatus.Connecting && this.state.status !== VoiceConnectionStatus.Ready)\n\t\t\treturn;\n\n\t\tif (newState.code === NetworkingStatusCode.Ready) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Ready,\n\t\t\t};\n\t\t} else if (newState.code !== NetworkingStatusCode.Closed) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Connecting,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Propagates errors from the underlying network instance.\n\t *\n\t * @param error - The error to propagate\n\t */\n\tprivate onNetworkingError(error: Error) {\n\t\tthis.emit('error', error);\n\t}\n\n\t/**\n\t * Propagates debug messages from the underlying network instance.\n\t *\n\t * @param message - The debug message to propagate\n\t */\n\tprivate onNetworkingDebug(message: string) {\n\t\tthis.debug?.(`[NW] ${message}`);\n\t}\n\n\t/**\n\t * Prepares an audio packet for dispatch.\n\t *\n\t * @param buffer - The Opus packet to prepare\n\t */\n\tpublic prepareAudioPacket(buffer: Buffer) {\n\t\tconst state = this.state;\n\t\tif (state.status !== VoiceConnectionStatus.Ready) return;\n\t\treturn state.networking.prepareAudioPacket(buffer);\n\t}\n\n\t/**\n\t * Dispatches the previously prepared audio packet (if any)\n\t */\n\tpublic dispatchAudio() {\n\t\tconst state = this.state;\n\t\tif (state.status !== VoiceConnectionStatus.Ready) return;\n\t\treturn state.networking.dispatchAudio();\n\t}\n\n\t/**\n\t * Prepares an audio packet and dispatches it immediately.\n\t *\n\t * @param buffer - The Opus packet to play\n\t */\n\tpublic playOpusPacket(buffer: Buffer) {\n\t\tconst state = this.state;\n\t\tif (state.status !== VoiceConnectionStatus.Ready) return;\n\t\tstate.networking.prepareAudioPacket(buffer);\n\t\treturn state.networking.dispatchAudio();\n\t}\n\n\t/**\n\t * Destroys the VoiceConnection, preventing it from connecting to voice again.\n\t * This method should be called when you no longer require the VoiceConnection to\n\t * prevent memory leaks.\n\t *\n\t * @param adapterAvailable - Whether the adapter can be used\n\t */\n\tpublic destroy(adapterAvailable = true) {\n\t\tif (this.state.status === VoiceConnectionStatus.Destroyed) {\n\t\t\tthrow new Error('Cannot destroy VoiceConnection - it has already been destroyed');\n\t\t}\n\n\t\tif (getVoiceConnection(this.joinConfig.guildId, this.joinConfig.group) === this) {\n\t\t\tuntrackVoiceConnection(this);\n\t\t}\n\n\t\tif (adapterAvailable) {\n\t\t\tthis.state.adapter.sendPayload(createJoinVoiceChannelPayload({ ...this.joinConfig, channelId: null }));\n\t\t}\n\n\t\tthis.state = {\n\t\t\tstatus: VoiceConnectionStatus.Destroyed,\n\t\t};\n\t}\n\n\t/**\n\t * Disconnects the VoiceConnection, allowing the possibility of rejoining later on.\n\t *\n\t * @returns `true` if the connection was successfully disconnected\n\t */\n\tpublic disconnect() {\n\t\tif (\n\t\t\tthis.state.status === VoiceConnectionStatus.Destroyed ||\n\t\t\tthis.state.status === VoiceConnectionStatus.Signalling\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\n\t\tthis.joinConfig.channelId = null;\n\t\tif (!this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) {\n\t\t\tthis.state = {\n\t\t\t\tadapter: this.state.adapter,\n\t\t\t\tsubscription: this.state.subscription,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t\t};\n\t\t\treturn false;\n\t\t}\n\n\t\tthis.state = {\n\t\t\tadapter: this.state.adapter,\n\t\t\treason: VoiceConnectionDisconnectReason.Manual,\n\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t};\n\t\treturn true;\n\t}\n\n\t/**\n\t * Attempts to rejoin (better explanation soon:tm:)\n\t *\n\t * @remarks\n\t * Calling this method successfully will automatically increment the `rejoinAttempts` counter,\n\t * which you can use to inform whether or not you'd like to keep attempting to reconnect your\n\t * voice connection.\n\t *\n\t * A state transition from Disconnected to Signalling will be observed when this is called.\n\t */\n\tpublic rejoin(joinConfig?: Omit) {\n\t\tif (this.state.status === VoiceConnectionStatus.Destroyed) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst notReady = this.state.status !== VoiceConnectionStatus.Ready;\n\n\t\tif (notReady) this.rejoinAttempts++;\n\t\tObject.assign(this.joinConfig, joinConfig);\n\t\tif (this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) {\n\t\t\tif (notReady) {\n\t\t\t\tthis.state = {\n\t\t\t\t\t...this.state,\n\t\t\t\t\tstatus: VoiceConnectionStatus.Signalling,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\tthis.state = {\n\t\t\tadapter: this.state.adapter,\n\t\t\tsubscription: this.state.subscription,\n\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t};\n\t\treturn false;\n\t}\n\n\t/**\n\t * Updates the speaking status of the voice connection. This is used when audio players are done playing audio,\n\t * and need to signal that the connection is no longer playing audio.\n\t *\n\t * @param enabled - Whether or not to show as speaking\n\t */\n\tpublic setSpeaking(enabled: boolean) {\n\t\tif (this.state.status !== VoiceConnectionStatus.Ready) return false;\n\t\t// eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n\t\treturn this.state.networking.setSpeaking(enabled);\n\t}\n\n\t/**\n\t * Subscribes to an audio player, allowing the player to play audio on this voice connection.\n\t *\n\t * @param player - The audio player to subscribe to\n\t * @returns The created subscription\n\t */\n\tpublic subscribe(player: AudioPlayer) {\n\t\tif (this.state.status === VoiceConnectionStatus.Destroyed) return;\n\n\t\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\t\tconst subscription = player['subscribe'](this);\n\n\t\tthis.state = {\n\t\t\t...this.state,\n\t\t\tsubscription,\n\t\t};\n\n\t\treturn subscription;\n\t}\n\n\t/**\n\t * The latest ping (in milliseconds) for the WebSocket connection and audio playback for this voice\n\t * connection, if this data is available.\n\t *\n\t * @remarks\n\t * For this data to be available, the VoiceConnection must be in the Ready state, and its underlying\n\t * WebSocket connection and UDP socket must have had at least one ping-pong exchange.\n\t */\n\tpublic get ping() {\n\t\tif (\n\t\t\tthis.state.status === VoiceConnectionStatus.Ready &&\n\t\t\tthis.state.networking.state.code === NetworkingStatusCode.Ready\n\t\t) {\n\t\t\treturn {\n\t\t\t\tws: this.state.networking.state.ws.ping,\n\t\t\t\tudp: this.state.networking.state.udp.ping,\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tws: undefined,\n\t\t\tudp: undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Called when a subscription of this voice connection to an audio player is removed.\n\t *\n\t * @param subscription - The removed subscription\n\t */\n\tprotected onSubscriptionRemoved(subscription: PlayerSubscription) {\n\t\tif (this.state.status !== VoiceConnectionStatus.Destroyed && this.state.subscription === subscription) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tsubscription: undefined,\n\t\t\t};\n\t\t}\n\t}\n}\n\n/**\n * Creates a new voice connection.\n *\n * @param joinConfig - The data required to establish the voice connection\n * @param options - The options to use when joining the voice channel\n */\nexport function createVoiceConnection(joinConfig: JoinConfig, options: CreateVoiceConnectionOptions) {\n\tconst payload = createJoinVoiceChannelPayload(joinConfig);\n\tconst existing = getVoiceConnection(joinConfig.guildId, joinConfig.group);\n\tif (existing && existing.state.status !== VoiceConnectionStatus.Destroyed) {\n\t\tif (existing.state.status === VoiceConnectionStatus.Disconnected) {\n\t\t\texisting.rejoin({\n\t\t\t\tchannelId: joinConfig.channelId,\n\t\t\t\tselfDeaf: joinConfig.selfDeaf,\n\t\t\t\tselfMute: joinConfig.selfMute,\n\t\t\t});\n\t\t} else if (!existing.state.adapter.sendPayload(payload)) {\n\t\t\texisting.state = {\n\t\t\t\t...existing.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t\t};\n\t\t}\n\n\t\treturn existing;\n\t}\n\n\tconst voiceConnection = new VoiceConnection(joinConfig, options);\n\ttrackVoiceConnection(voiceConnection);\n\tif (\n\t\tvoiceConnection.state.status !== VoiceConnectionStatus.Destroyed &&\n\t\t!voiceConnection.state.adapter.sendPayload(payload)\n\t) {\n\t\tvoiceConnection.state = {\n\t\t\t...voiceConnection.state,\n\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t};\n\t}\n\n\treturn voiceConnection;\n}\n","import { GatewayOpcodes } from 'discord-api-types/v10';\nimport type { VoiceConnection } from './VoiceConnection';\nimport type { AudioPlayer } from './audio/index';\n\nexport interface JoinConfig {\n\tchannelId: string | null;\n\tgroup: string;\n\tguildId: string;\n\tselfDeaf: boolean;\n\tselfMute: boolean;\n}\n\n/**\n * Sends a voice state update to the main websocket shard of a guild, to indicate joining/leaving/moving across\n * voice channels.\n *\n * @param config - The configuration to use when joining the voice channel\n */\nexport function createJoinVoiceChannelPayload(config: JoinConfig) {\n\treturn {\n\t\top: GatewayOpcodes.VoiceStateUpdate,\n\t\t// eslint-disable-next-line id-length\n\t\td: {\n\t\t\tguild_id: config.guildId,\n\t\t\tchannel_id: config.channelId,\n\t\t\tself_deaf: config.selfDeaf,\n\t\t\tself_mute: config.selfMute,\n\t\t},\n\t};\n}\n\n// Voice Connections\nconst groups = new Map>();\ngroups.set('default', new Map());\n\nfunction getOrCreateGroup(group: string) {\n\tconst existing = groups.get(group);\n\tif (existing) return existing;\n\tconst map = new Map();\n\tgroups.set(group, map);\n\treturn map;\n}\n\n/**\n * Retrieves the map of group names to maps of voice connections. By default, all voice connections\n * are created under the 'default' group.\n *\n * @returns The group map\n */\nexport function getGroups() {\n\treturn groups;\n}\n\n/**\n * Retrieves all the voice connections under the 'default' group.\n *\n * @param group - The group to look up\n * @returns The map of voice connections\n */\nexport function getVoiceConnections(group?: 'default'): Map;\n\n/**\n * Retrieves all the voice connections under the given group name.\n *\n * @param group - The group to look up\n * @returns The map of voice connections\n */\nexport function getVoiceConnections(group: string): Map | undefined;\n\n/**\n * Retrieves all the voice connections under the given group name. Defaults to the 'default' group.\n *\n * @param group - The group to look up\n * @returns The map of voice connections\n */\nexport function getVoiceConnections(group = 'default') {\n\treturn groups.get(group);\n}\n\n/**\n * Finds a voice connection with the given guild id and group. Defaults to the 'default' group.\n *\n * @param guildId - The guild id of the voice connection\n * @param group - the group that the voice connection was registered with\n * @returns The voice connection, if it exists\n */\nexport function getVoiceConnection(guildId: string, group = 'default') {\n\treturn getVoiceConnections(group)?.get(guildId);\n}\n\nexport function untrackVoiceConnection(voiceConnection: VoiceConnection) {\n\treturn getVoiceConnections(voiceConnection.joinConfig.group)?.delete(voiceConnection.joinConfig.guildId);\n}\n\nexport function trackVoiceConnection(voiceConnection: VoiceConnection) {\n\treturn getOrCreateGroup(voiceConnection.joinConfig.group).set(voiceConnection.joinConfig.guildId, voiceConnection);\n}\n\n// Audio Players\n\n// Each audio packet is 20ms long\nconst FRAME_LENGTH = 20;\n\nlet audioCycleInterval: NodeJS.Timeout | undefined;\nlet nextTime = -1;\n\n/**\n * A list of created audio players that are still active and haven't been destroyed.\n */\nconst audioPlayers: AudioPlayer[] = [];\n\n/**\n * Called roughly every 20 milliseconds. Dispatches audio from all players, and then gets the players to prepare\n * the next audio frame.\n */\nfunction audioCycleStep() {\n\tif (nextTime === -1) return;\n\n\tnextTime += FRAME_LENGTH;\n\tconst available = audioPlayers.filter((player) => player.checkPlayable());\n\n\tfor (const player of available) {\n\t\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\t\tplayer['_stepDispatch']();\n\t}\n\n\tprepareNextAudioFrame(available);\n}\n\n/**\n * Recursively gets the players that have been passed as parameters to prepare audio frames that can be played\n * at the start of the next cycle.\n */\nfunction prepareNextAudioFrame(players: AudioPlayer[]) {\n\tconst nextPlayer = players.shift();\n\n\tif (!nextPlayer) {\n\t\tif (nextTime !== -1) {\n\t\t\taudioCycleInterval = setTimeout(() => audioCycleStep(), nextTime - Date.now());\n\t\t}\n\n\t\treturn;\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\tnextPlayer['_stepPrepare']();\n\n\t// setImmediate to avoid long audio player chains blocking other scheduled tasks\n\tsetImmediate(() => prepareNextAudioFrame(players));\n}\n\n/**\n * Checks whether or not the given audio player is being driven by the data store clock.\n *\n * @param target - The target to test for\n * @returns `true` if it is being tracked, `false` otherwise\n */\nexport function hasAudioPlayer(target: AudioPlayer) {\n\treturn audioPlayers.includes(target);\n}\n\n/**\n * Adds an audio player to the data store tracking list, if it isn't already there.\n *\n * @param player - The player to track\n */\nexport function addAudioPlayer(player: AudioPlayer) {\n\tif (hasAudioPlayer(player)) return player;\n\taudioPlayers.push(player);\n\tif (audioPlayers.length === 1) {\n\t\tnextTime = Date.now();\n\t\tsetImmediate(() => audioCycleStep());\n\t}\n\n\treturn player;\n}\n\n/**\n * Removes an audio player from the data store tracking list, if it is present there.\n */\nexport function deleteAudioPlayer(player: AudioPlayer) {\n\tconst index = audioPlayers.indexOf(player);\n\tif (index === -1) return;\n\taudioPlayers.splice(index, 1);\n\tif (audioPlayers.length === 0) {\n\t\tnextTime = -1;\n\t\tif (audioCycleInterval !== undefined) clearTimeout(audioCycleInterval);\n\t}\n}\n","/* eslint-disable jsdoc/check-param-names */\n/* eslint-disable id-length */\n/* eslint-disable @typescript-eslint/unbound-method */\nimport { Buffer } from 'node:buffer';\nimport { EventEmitter } from 'node:events';\nimport { VoiceOpcodes } from 'discord-api-types/voice/v4';\nimport type { CloseEvent } from 'ws';\nimport * as secretbox from '../util/Secretbox';\nimport { noop } from '../util/util';\nimport { VoiceUDPSocket } from './VoiceUDPSocket';\nimport { VoiceWebSocket } from './VoiceWebSocket';\n\n// The number of audio channels required by Discord\nconst CHANNELS = 2;\nconst TIMESTAMP_INC = (48_000 / 100) * CHANNELS;\nconst MAX_NONCE_SIZE = 2 ** 32 - 1;\n\nexport const SUPPORTED_ENCRYPTION_MODES = ['xsalsa20_poly1305_lite', 'xsalsa20_poly1305_suffix', 'xsalsa20_poly1305'];\n\n/**\n * The different statuses that a networking instance can hold. The order\n * of the states between OpeningWs and Ready is chronological (first the\n * instance enters OpeningWs, then it enters Identifying etc.)\n */\nexport enum NetworkingStatusCode {\n\tOpeningWs,\n\tIdentifying,\n\tUdpHandshaking,\n\tSelectingProtocol,\n\tReady,\n\tResuming,\n\tClosed,\n}\n\n/**\n * The initial Networking state. Instances will be in this state when a WebSocket connection to a Discord\n * voice gateway is being opened.\n */\nexport interface NetworkingOpeningWsState {\n\tcode: NetworkingStatusCode.OpeningWs;\n\tconnectionOptions: ConnectionOptions;\n\tws: VoiceWebSocket;\n}\n\n/**\n * The state that a Networking instance will be in when it is attempting to authorize itself.\n */\nexport interface NetworkingIdentifyingState {\n\tcode: NetworkingStatusCode.Identifying;\n\tconnectionOptions: ConnectionOptions;\n\tws: VoiceWebSocket;\n}\n\n/**\n * The state that a Networking instance will be in when opening a UDP connection to the IP and port provided\n * by Discord, as well as performing IP discovery.\n */\nexport interface NetworkingUdpHandshakingState {\n\tcode: NetworkingStatusCode.UdpHandshaking;\n\tconnectionData: Pick;\n\tconnectionOptions: ConnectionOptions;\n\tudp: VoiceUDPSocket;\n\tws: VoiceWebSocket;\n}\n\n/**\n * The state that a Networking instance will be in when selecting an encryption protocol for audio packets.\n */\nexport interface NetworkingSelectingProtocolState {\n\tcode: NetworkingStatusCode.SelectingProtocol;\n\tconnectionData: Pick;\n\tconnectionOptions: ConnectionOptions;\n\tudp: VoiceUDPSocket;\n\tws: VoiceWebSocket;\n}\n\n/**\n * The state that a Networking instance will be in when it has a fully established connection to a Discord\n * voice server.\n */\nexport interface NetworkingReadyState {\n\tcode: NetworkingStatusCode.Ready;\n\tconnectionData: ConnectionData;\n\tconnectionOptions: ConnectionOptions;\n\tpreparedPacket?: Buffer | undefined;\n\tudp: VoiceUDPSocket;\n\tws: VoiceWebSocket;\n}\n\n/**\n * The state that a Networking instance will be in when its connection has been dropped unexpectedly, and it\n * is attempting to resume an existing session.\n */\nexport interface NetworkingResumingState {\n\tcode: NetworkingStatusCode.Resuming;\n\tconnectionData: ConnectionData;\n\tconnectionOptions: ConnectionOptions;\n\tpreparedPacket?: Buffer | undefined;\n\tudp: VoiceUDPSocket;\n\tws: VoiceWebSocket;\n}\n\n/**\n * The state that a Networking instance will be in when it has been destroyed. It cannot be recovered from this\n * state.\n */\nexport interface NetworkingClosedState {\n\tcode: NetworkingStatusCode.Closed;\n}\n\n/**\n * The various states that a networking instance can be in.\n */\nexport type NetworkingState =\n\t| NetworkingClosedState\n\t| NetworkingIdentifyingState\n\t| NetworkingOpeningWsState\n\t| NetworkingReadyState\n\t| NetworkingResumingState\n\t| NetworkingSelectingProtocolState\n\t| NetworkingUdpHandshakingState;\n\n/**\n * Details required to connect to the Discord voice gateway. These details\n * are first received on the main bot gateway, in the form of VOICE_SERVER_UPDATE\n * and VOICE_STATE_UPDATE packets.\n */\ninterface ConnectionOptions {\n\tendpoint: string;\n\tserverId: string;\n\tsessionId: string;\n\ttoken: string;\n\tuserId: string;\n}\n\n/**\n * Information about the current connection, e.g. which encryption mode is to be used on\n * the connection, timing information for playback of streams.\n */\nexport interface ConnectionData {\n\tencryptionMode: string;\n\tnonce: number;\n\tnonceBuffer: Buffer;\n\tpacketsPlayed: number;\n\tsecretKey: Uint8Array;\n\tsequence: number;\n\tspeaking: boolean;\n\tssrc: number;\n\ttimestamp: number;\n}\n\n/**\n * An empty buffer that is reused in packet encryption by many different networking instances.\n */\nconst nonce = Buffer.alloc(24);\n\nexport interface Networking extends EventEmitter {\n\t/**\n\t * Debug event for Networking.\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'debug', listener: (message: string) => void): this;\n\ton(event: 'error', listener: (error: Error) => void): this;\n\ton(event: 'stateChange', listener: (oldState: NetworkingState, newState: NetworkingState) => void): this;\n\ton(event: 'close', listener: (code: number) => void): this;\n}\n\n/**\n * Stringifies a NetworkingState.\n *\n * @param state - The state to stringify\n */\nfunction stringifyState(state: NetworkingState) {\n\treturn JSON.stringify({\n\t\t...state,\n\t\tws: Reflect.has(state, 'ws'),\n\t\tudp: Reflect.has(state, 'udp'),\n\t});\n}\n\n/**\n * Chooses an encryption mode from a list of given options. Chooses the most preferred option.\n *\n * @param options - The available encryption options\n */\nfunction chooseEncryptionMode(options: string[]): string {\n\tconst option = options.find((option) => SUPPORTED_ENCRYPTION_MODES.includes(option));\n\tif (!option) {\n\t\tthrow new Error(`No compatible encryption modes. Available include: ${options.join(', ')}`);\n\t}\n\n\treturn option;\n}\n\n/**\n * Returns a random number that is in the range of n bits.\n *\n * @param numberOfBits - The number of bits\n */\nfunction randomNBit(numberOfBits: number) {\n\treturn Math.floor(Math.random() * 2 ** numberOfBits);\n}\n\n/**\n * Manages the networking required to maintain a voice connection and dispatch audio packets\n */\nexport class Networking extends EventEmitter {\n\tprivate _state: NetworkingState;\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: ((message: string) => void) | null;\n\n\t/**\n\t * Creates a new Networking instance.\n\t */\n\tpublic constructor(options: ConnectionOptions, debug: boolean) {\n\t\tsuper();\n\n\t\tthis.onWsOpen = this.onWsOpen.bind(this);\n\t\tthis.onChildError = this.onChildError.bind(this);\n\t\tthis.onWsPacket = this.onWsPacket.bind(this);\n\t\tthis.onWsClose = this.onWsClose.bind(this);\n\t\tthis.onWsDebug = this.onWsDebug.bind(this);\n\t\tthis.onUdpDebug = this.onUdpDebug.bind(this);\n\t\tthis.onUdpClose = this.onUdpClose.bind(this);\n\n\t\tthis.debug = debug ? (message: string) => this.emit('debug', message) : null;\n\n\t\tthis._state = {\n\t\t\tcode: NetworkingStatusCode.OpeningWs,\n\t\t\tws: this.createWebSocket(options.endpoint),\n\t\t\tconnectionOptions: options,\n\t\t};\n\t}\n\n\t/**\n\t * Destroys the Networking instance, transitioning it into the Closed state.\n\t */\n\tpublic destroy() {\n\t\tthis.state = {\n\t\t\tcode: NetworkingStatusCode.Closed,\n\t\t};\n\t}\n\n\t/**\n\t * The current state of the networking instance.\n\t */\n\tpublic get state(): NetworkingState {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * Sets a new state for the networking instance, performing clean-up operations where necessary.\n\t */\n\tpublic set state(newState: NetworkingState) {\n\t\tconst oldWs = Reflect.get(this._state, 'ws') as VoiceWebSocket | undefined;\n\t\tconst newWs = Reflect.get(newState, 'ws') as VoiceWebSocket | undefined;\n\t\tif (oldWs && oldWs !== newWs) {\n\t\t\t// The old WebSocket is being freed - remove all handlers from it\n\t\t\toldWs.off('debug', this.onWsDebug);\n\t\t\toldWs.on('error', noop);\n\t\t\toldWs.off('error', this.onChildError);\n\t\t\toldWs.off('open', this.onWsOpen);\n\t\t\toldWs.off('packet', this.onWsPacket);\n\t\t\toldWs.off('close', this.onWsClose);\n\t\t\toldWs.destroy();\n\t\t}\n\n\t\tconst oldUdp = Reflect.get(this._state, 'udp') as VoiceUDPSocket | undefined;\n\t\tconst newUdp = Reflect.get(newState, 'udp') as VoiceUDPSocket | undefined;\n\n\t\tif (oldUdp && oldUdp !== newUdp) {\n\t\t\toldUdp.on('error', noop);\n\t\t\toldUdp.off('error', this.onChildError);\n\t\t\toldUdp.off('close', this.onUdpClose);\n\t\t\toldUdp.off('debug', this.onUdpDebug);\n\t\t\toldUdp.destroy();\n\t\t}\n\n\t\tconst oldState = this._state;\n\t\tthis._state = newState;\n\t\tthis.emit('stateChange', oldState, newState);\n\n\t\tthis.debug?.(`state change:\\nfrom ${stringifyState(oldState)}\\nto ${stringifyState(newState)}`);\n\t}\n\n\t/**\n\t * Creates a new WebSocket to a Discord Voice gateway.\n\t *\n\t * @param endpoint - The endpoint to connect to\n\t */\n\tprivate createWebSocket(endpoint: string) {\n\t\tconst ws = new VoiceWebSocket(`wss://${endpoint}?v=4`, Boolean(this.debug));\n\n\t\tws.on('error', this.onChildError);\n\t\tws.once('open', this.onWsOpen);\n\t\tws.on('packet', this.onWsPacket);\n\t\tws.once('close', this.onWsClose);\n\t\tws.on('debug', this.onWsDebug);\n\n\t\treturn ws;\n\t}\n\n\t/**\n\t * Propagates errors from the children VoiceWebSocket and VoiceUDPSocket.\n\t *\n\t * @param error - The error that was emitted by a child\n\t */\n\tprivate onChildError(error: Error) {\n\t\tthis.emit('error', error);\n\t}\n\n\t/**\n\t * Called when the WebSocket opens. Depending on the state that the instance is in,\n\t * it will either identify with a new session, or it will attempt to resume an existing session.\n\t */\n\tprivate onWsOpen() {\n\t\tif (this.state.code === NetworkingStatusCode.OpeningWs) {\n\t\t\tconst packet = {\n\t\t\t\top: VoiceOpcodes.Identify,\n\t\t\t\td: {\n\t\t\t\t\tserver_id: this.state.connectionOptions.serverId,\n\t\t\t\t\tuser_id: this.state.connectionOptions.userId,\n\t\t\t\t\tsession_id: this.state.connectionOptions.sessionId,\n\t\t\t\t\ttoken: this.state.connectionOptions.token,\n\t\t\t\t},\n\t\t\t};\n\t\t\tthis.state.ws.sendPacket(packet);\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Identifying,\n\t\t\t};\n\t\t} else if (this.state.code === NetworkingStatusCode.Resuming) {\n\t\t\tconst packet = {\n\t\t\t\top: VoiceOpcodes.Resume,\n\t\t\t\td: {\n\t\t\t\t\tserver_id: this.state.connectionOptions.serverId,\n\t\t\t\t\tsession_id: this.state.connectionOptions.sessionId,\n\t\t\t\t\ttoken: this.state.connectionOptions.token,\n\t\t\t\t},\n\t\t\t};\n\t\t\tthis.state.ws.sendPacket(packet);\n\t\t}\n\t}\n\n\t/**\n\t * Called when the WebSocket closes. Based on the reason for closing (given by the code parameter),\n\t * the instance will either attempt to resume, or enter the closed state and emit a 'close' event\n\t * with the close code, allowing the user to decide whether or not they would like to reconnect.\n\t *\n\t * @param code - The close code\n\t */\n\tprivate onWsClose({ code }: CloseEvent) {\n\t\tconst canResume = code === 4_015 || code < 4_000;\n\t\tif (canResume && this.state.code === NetworkingStatusCode.Ready) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Resuming,\n\t\t\t\tws: this.createWebSocket(this.state.connectionOptions.endpoint),\n\t\t\t};\n\t\t} else if (this.state.code !== NetworkingStatusCode.Closed) {\n\t\t\tthis.destroy();\n\t\t\tthis.emit('close', code);\n\t\t}\n\t}\n\n\t/**\n\t * Called when the UDP socket has closed itself if it has stopped receiving replies from Discord.\n\t */\n\tprivate onUdpClose() {\n\t\tif (this.state.code === NetworkingStatusCode.Ready) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Resuming,\n\t\t\t\tws: this.createWebSocket(this.state.connectionOptions.endpoint),\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Called when a packet is received on the connection's WebSocket.\n\t *\n\t * @param packet - The received packet\n\t */\n\tprivate onWsPacket(packet: any) {\n\t\tif (packet.op === VoiceOpcodes.Hello && this.state.code !== NetworkingStatusCode.Closed) {\n\t\t\tthis.state.ws.setHeartbeatInterval(packet.d.heartbeat_interval);\n\t\t} else if (packet.op === VoiceOpcodes.Ready && this.state.code === NetworkingStatusCode.Identifying) {\n\t\t\tconst { ip, port, ssrc, modes } = packet.d;\n\n\t\t\tconst udp = new VoiceUDPSocket({ ip, port });\n\t\t\tudp.on('error', this.onChildError);\n\t\t\tudp.on('debug', this.onUdpDebug);\n\t\t\tudp.once('close', this.onUdpClose);\n\t\t\tudp\n\t\t\t\t.performIPDiscovery(ssrc)\n\t\t\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\t\t\t.then((localConfig) => {\n\t\t\t\t\tif (this.state.code !== NetworkingStatusCode.UdpHandshaking) return;\n\t\t\t\t\tthis.state.ws.sendPacket({\n\t\t\t\t\t\top: VoiceOpcodes.SelectProtocol,\n\t\t\t\t\t\td: {\n\t\t\t\t\t\t\tprotocol: 'udp',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\taddress: localConfig.ip,\n\t\t\t\t\t\t\t\tport: localConfig.port,\n\t\t\t\t\t\t\t\tmode: chooseEncryptionMode(modes),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tthis.state = {\n\t\t\t\t\t\t...this.state,\n\t\t\t\t\t\tcode: NetworkingStatusCode.SelectingProtocol,\n\t\t\t\t\t};\n\t\t\t\t})\n\t\t\t\t// eslint-disable-next-line promise/prefer-await-to-then, promise/prefer-await-to-callbacks\n\t\t\t\t.catch((error: Error) => this.emit('error', error));\n\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.UdpHandshaking,\n\t\t\t\tudp,\n\t\t\t\tconnectionData: {\n\t\t\t\t\tssrc,\n\t\t\t\t},\n\t\t\t};\n\t\t} else if (\n\t\t\tpacket.op === VoiceOpcodes.SessionDescription &&\n\t\t\tthis.state.code === NetworkingStatusCode.SelectingProtocol\n\t\t) {\n\t\t\tconst { mode: encryptionMode, secret_key: secretKey } = packet.d;\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Ready,\n\t\t\t\tconnectionData: {\n\t\t\t\t\t...this.state.connectionData,\n\t\t\t\t\tencryptionMode,\n\t\t\t\t\tsecretKey: new Uint8Array(secretKey),\n\t\t\t\t\tsequence: randomNBit(16),\n\t\t\t\t\ttimestamp: randomNBit(32),\n\t\t\t\t\tnonce: 0,\n\t\t\t\t\tnonceBuffer: Buffer.alloc(24),\n\t\t\t\t\tspeaking: false,\n\t\t\t\t\tpacketsPlayed: 0,\n\t\t\t\t},\n\t\t\t};\n\t\t} else if (packet.op === VoiceOpcodes.Resumed && this.state.code === NetworkingStatusCode.Resuming) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Ready,\n\t\t\t};\n\t\t\tthis.state.connectionData.speaking = false;\n\t\t}\n\t}\n\n\t/**\n\t * Propagates debug messages from the child WebSocket.\n\t *\n\t * @param message - The emitted debug message\n\t */\n\tprivate onWsDebug(message: string) {\n\t\tthis.debug?.(`[WS] ${message}`);\n\t}\n\n\t/**\n\t * Propagates debug messages from the child UDPSocket.\n\t *\n\t * @param message - The emitted debug message\n\t */\n\tprivate onUdpDebug(message: string) {\n\t\tthis.debug?.(`[UDP] ${message}`);\n\t}\n\n\t/**\n\t * Prepares an Opus packet for playback. This includes attaching metadata to it and encrypting it.\n\t * It will be stored within the instance, and can be played by dispatchAudio()\n\t *\n\t * @remarks\n\t * Calling this method while there is already a prepared audio packet that has not yet been dispatched\n\t * will overwrite the existing audio packet. This should be avoided.\n\t * @param opusPacket - The Opus packet to encrypt\n\t * @returns The audio packet that was prepared\n\t */\n\tpublic prepareAudioPacket(opusPacket: Buffer) {\n\t\tconst state = this.state;\n\t\tif (state.code !== NetworkingStatusCode.Ready) return;\n\t\tstate.preparedPacket = this.createAudioPacket(opusPacket, state.connectionData);\n\t\treturn state.preparedPacket;\n\t}\n\n\t/**\n\t * Dispatches the audio packet previously prepared by prepareAudioPacket(opusPacket). The audio packet\n\t * is consumed and cannot be dispatched again.\n\t */\n\tpublic dispatchAudio() {\n\t\tconst state = this.state;\n\t\tif (state.code !== NetworkingStatusCode.Ready) return false;\n\t\tif (state.preparedPacket !== undefined) {\n\t\t\tthis.playAudioPacket(state.preparedPacket);\n\t\t\tstate.preparedPacket = undefined;\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Plays an audio packet, updating timing metadata used for playback.\n\t *\n\t * @param audioPacket - The audio packet to play\n\t */\n\tprivate playAudioPacket(audioPacket: Buffer) {\n\t\tconst state = this.state;\n\t\tif (state.code !== NetworkingStatusCode.Ready) return;\n\t\tconst { connectionData } = state;\n\t\tconnectionData.packetsPlayed++;\n\t\tconnectionData.sequence++;\n\t\tconnectionData.timestamp += TIMESTAMP_INC;\n\t\tif (connectionData.sequence >= 2 ** 16) connectionData.sequence = 0;\n\t\tif (connectionData.timestamp >= 2 ** 32) connectionData.timestamp = 0;\n\t\tthis.setSpeaking(true);\n\t\tstate.udp.send(audioPacket);\n\t}\n\n\t/**\n\t * Sends a packet to the voice gateway indicating that the client has start/stopped sending\n\t * audio.\n\t *\n\t * @param speaking - Whether or not the client should be shown as speaking\n\t */\n\tpublic setSpeaking(speaking: boolean) {\n\t\tconst state = this.state;\n\t\tif (state.code !== NetworkingStatusCode.Ready) return;\n\t\tif (state.connectionData.speaking === speaking) return;\n\t\tstate.connectionData.speaking = speaking;\n\t\tstate.ws.sendPacket({\n\t\t\top: VoiceOpcodes.Speaking,\n\t\t\td: {\n\t\t\t\tspeaking: speaking ? 1 : 0,\n\t\t\t\tdelay: 0,\n\t\t\t\tssrc: state.connectionData.ssrc,\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Creates a new audio packet from an Opus packet. This involves encrypting the packet,\n\t * then prepending a header that includes metadata.\n\t *\n\t * @param opusPacket - The Opus packet to prepare\n\t * @param connectionData - The current connection data of the instance\n\t */\n\tprivate createAudioPacket(opusPacket: Buffer, connectionData: ConnectionData) {\n\t\tconst packetBuffer = Buffer.alloc(12);\n\t\tpacketBuffer[0] = 0x80;\n\t\tpacketBuffer[1] = 0x78;\n\n\t\tconst { sequence, timestamp, ssrc } = connectionData;\n\n\t\tpacketBuffer.writeUIntBE(sequence, 2, 2);\n\t\tpacketBuffer.writeUIntBE(timestamp, 4, 4);\n\t\tpacketBuffer.writeUIntBE(ssrc, 8, 4);\n\n\t\tpacketBuffer.copy(nonce, 0, 0, 12);\n\t\treturn Buffer.concat([packetBuffer, ...this.encryptOpusPacket(opusPacket, connectionData)]);\n\t}\n\n\t/**\n\t * Encrypts an Opus packet using the format agreed upon by the instance and Discord.\n\t *\n\t * @param opusPacket - The Opus packet to encrypt\n\t * @param connectionData - The current connection data of the instance\n\t */\n\tprivate encryptOpusPacket(opusPacket: Buffer, connectionData: ConnectionData) {\n\t\tconst { secretKey, encryptionMode } = connectionData;\n\n\t\tif (encryptionMode === 'xsalsa20_poly1305_lite') {\n\t\t\tconnectionData.nonce++;\n\t\t\tif (connectionData.nonce > MAX_NONCE_SIZE) connectionData.nonce = 0;\n\t\t\tconnectionData.nonceBuffer.writeUInt32BE(connectionData.nonce, 0);\n\t\t\treturn [\n\t\t\t\tsecretbox.methods.close(opusPacket, connectionData.nonceBuffer, secretKey),\n\t\t\t\tconnectionData.nonceBuffer.slice(0, 4),\n\t\t\t];\n\t\t} else if (encryptionMode === 'xsalsa20_poly1305_suffix') {\n\t\t\tconst random = secretbox.methods.random(24, connectionData.nonceBuffer);\n\t\t\treturn [secretbox.methods.close(opusPacket, random, secretKey), random];\n\t\t}\n\n\t\treturn [secretbox.methods.close(opusPacket, nonce, secretKey)];\n\t}\n}\n","import { Buffer } from 'node:buffer';\n\ninterface Methods {\n\tclose(opusPacket: Buffer, nonce: Buffer, secretKey: Uint8Array): Buffer;\n\topen(buffer: Buffer, nonce: Buffer, secretKey: Uint8Array): Buffer | null;\n\trandom(bytes: number, nonce: Buffer): Buffer;\n}\n\nconst libs = {\n\t'sodium-native': (sodium: any): Methods => ({\n\t\topen: (buffer: Buffer, nonce: Buffer, secretKey: Uint8Array) => {\n\t\t\tif (buffer) {\n\t\t\t\tconst output = Buffer.allocUnsafe(buffer.length - sodium.crypto_box_MACBYTES);\n\t\t\t\tif (sodium.crypto_secretbox_open_easy(output, buffer, nonce, secretKey)) return output;\n\t\t\t}\n\n\t\t\treturn null;\n\t\t},\n\t\tclose: (opusPacket: Buffer, nonce: Buffer, secretKey: Uint8Array) => {\n\t\t\t// eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n\t\t\tconst output = Buffer.allocUnsafe(opusPacket.length + sodium.crypto_box_MACBYTES);\n\t\t\tsodium.crypto_secretbox_easy(output, opusPacket, nonce, secretKey);\n\t\t\treturn output;\n\t\t},\n\t\trandom: (num: number, buffer: Buffer = Buffer.allocUnsafe(num)) => {\n\t\t\tsodium.randombytes_buf(buffer);\n\t\t\treturn buffer;\n\t\t},\n\t}),\n\tsodium: (sodium: any): Methods => ({\n\t\topen: sodium.api.crypto_secretbox_open_easy,\n\t\tclose: sodium.api.crypto_secretbox_easy,\n\t\trandom: (num: number, buffer: Buffer = Buffer.allocUnsafe(num)) => {\n\t\t\tsodium.api.randombytes_buf(buffer);\n\t\t\treturn buffer;\n\t\t},\n\t}),\n\t'libsodium-wrappers': (sodium: any): Methods => ({\n\t\topen: sodium.crypto_secretbox_open_easy,\n\t\tclose: sodium.crypto_secretbox_easy,\n\t\trandom: sodium.randombytes_buf,\n\t}),\n\ttweetnacl: (tweetnacl: any): Methods => ({\n\t\topen: tweetnacl.secretbox.open,\n\t\tclose: tweetnacl.secretbox,\n\t\trandom: tweetnacl.randomBytes,\n\t}),\n} as const;\n\nconst fallbackError = () => {\n\tthrow new Error(\n\t\t`Cannot play audio as no valid encryption package is installed.\n- Install sodium, libsodium-wrappers, or tweetnacl.\n- Use the generateDependencyReport() function for more information.\\n`,\n\t);\n};\n\nconst methods: Methods = {\n\topen: fallbackError,\n\tclose: fallbackError,\n\trandom: fallbackError,\n};\n\nvoid (async () => {\n\tfor (const libName of Object.keys(libs) as (keyof typeof libs)[]) {\n\t\ttry {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n\t\t\tconst lib = require(libName);\n\t\t\tif (libName === 'libsodium-wrappers' && lib.ready) await lib.ready;\n\t\t\tObject.assign(methods, libs[libName](lib));\n\t\t\tbreak;\n\t\t} catch {}\n\t}\n})();\n\nexport { methods };\n","export const noop = () => {};\n","import { Buffer } from 'node:buffer';\nimport { createSocket, type Socket } from 'node:dgram';\nimport { EventEmitter } from 'node:events';\nimport { isIPv4 } from 'node:net';\n\n/**\n * Stores an IP address and port. Used to store socket details for the local client as well as\n * for Discord.\n */\nexport interface SocketConfig {\n\tip: string;\n\tport: number;\n}\n\n/**\n * Parses the response from Discord to aid with local IP discovery.\n *\n * @param message - The received message\n */\nexport function parseLocalPacket(message: Buffer): SocketConfig {\n\tconst packet = Buffer.from(message);\n\n\tconst ip = packet.slice(8, packet.indexOf(0, 8)).toString('utf8');\n\n\tif (!isIPv4(ip)) {\n\t\tthrow new Error('Malformed IP address');\n\t}\n\n\tconst port = packet.readUInt16BE(packet.length - 2);\n\n\treturn { ip, port };\n}\n\n/**\n * The interval in milliseconds at which keep alive datagrams are sent.\n */\nconst KEEP_ALIVE_INTERVAL = 5e3;\n\n/**\n * The maximum value of the keep alive counter.\n */\nconst MAX_COUNTER_VALUE = 2 ** 32 - 1;\n\nexport interface VoiceUDPSocket extends EventEmitter {\n\ton(event: 'error', listener: (error: Error) => void): this;\n\ton(event: 'close', listener: () => void): this;\n\ton(event: 'debug', listener: (message: string) => void): this;\n\ton(event: 'message', listener: (message: Buffer) => void): this;\n}\n\n/**\n * Manages the UDP networking for a voice connection.\n */\nexport class VoiceUDPSocket extends EventEmitter {\n\t/**\n\t * The underlying network Socket for the VoiceUDPSocket.\n\t */\n\tprivate readonly socket: Socket;\n\n\t/**\n\t * The socket details for Discord (remote)\n\t */\n\tprivate readonly remote: SocketConfig;\n\n\t/**\n\t * The counter used in the keep alive mechanism.\n\t */\n\tprivate keepAliveCounter = 0;\n\n\t/**\n\t * The buffer used to write the keep alive counter into.\n\t */\n\tprivate readonly keepAliveBuffer: Buffer;\n\n\t/**\n\t * The Node.js interval for the keep-alive mechanism.\n\t */\n\tprivate readonly keepAliveInterval: NodeJS.Timeout;\n\n\t/**\n\t * The time taken to receive a response to keep alive messages.\n\t *\n\t * @deprecated This field is no longer updated as keep alive messages are no longer tracked.\n\t */\n\tpublic ping?: number;\n\n\t/**\n\t * Creates a new VoiceUDPSocket.\n\t *\n\t * @param remote - Details of the remote socket\n\t */\n\tpublic constructor(remote: SocketConfig) {\n\t\tsuper();\n\t\tthis.socket = createSocket('udp4');\n\t\tthis.socket.on('error', (error: Error) => this.emit('error', error));\n\t\tthis.socket.on('message', (buffer: Buffer) => this.onMessage(buffer));\n\t\tthis.socket.on('close', () => this.emit('close'));\n\t\tthis.remote = remote;\n\t\tthis.keepAliveBuffer = Buffer.alloc(8);\n\t\tthis.keepAliveInterval = setInterval(() => this.keepAlive(), KEEP_ALIVE_INTERVAL);\n\t\tsetImmediate(() => this.keepAlive());\n\t}\n\n\t/**\n\t * Called when a message is received on the UDP socket.\n\t *\n\t * @param buffer - The received buffer\n\t */\n\tprivate onMessage(buffer: Buffer): void {\n\t\t// Propagate the message\n\t\tthis.emit('message', buffer);\n\t}\n\n\t/**\n\t * Called at a regular interval to check whether we are still able to send datagrams to Discord.\n\t */\n\tprivate keepAlive() {\n\t\tthis.keepAliveBuffer.writeUInt32LE(this.keepAliveCounter, 0);\n\t\tthis.send(this.keepAliveBuffer);\n\t\tthis.keepAliveCounter++;\n\t\tif (this.keepAliveCounter > MAX_COUNTER_VALUE) {\n\t\t\tthis.keepAliveCounter = 0;\n\t\t}\n\t}\n\n\t/**\n\t * Sends a buffer to Discord.\n\t *\n\t * @param buffer - The buffer to send\n\t */\n\tpublic send(buffer: Buffer) {\n\t\tthis.socket.send(buffer, this.remote.port, this.remote.ip);\n\t}\n\n\t/**\n\t * Closes the socket, the instance will not be able to be reused.\n\t */\n\tpublic destroy() {\n\t\ttry {\n\t\t\tthis.socket.close();\n\t\t} catch {}\n\n\t\tclearInterval(this.keepAliveInterval);\n\t}\n\n\t/**\n\t * Performs IP discovery to discover the local address and port to be used for the voice connection.\n\t *\n\t * @param ssrc - The SSRC received from Discord\n\t */\n\tpublic async performIPDiscovery(ssrc: number): Promise {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst listener = (message: Buffer) => {\n\t\t\t\ttry {\n\t\t\t\t\tif (message.readUInt16BE(0) !== 2) return;\n\t\t\t\t\tconst packet = parseLocalPacket(message);\n\t\t\t\t\tthis.socket.off('message', listener);\n\t\t\t\t\tresolve(packet);\n\t\t\t\t} catch {}\n\t\t\t};\n\n\t\t\tthis.socket.on('message', listener);\n\t\t\tthis.socket.once('close', () => reject(new Error('Cannot perform IP discovery - socket closed')));\n\n\t\t\tconst discoveryBuffer = Buffer.alloc(74);\n\n\t\t\tdiscoveryBuffer.writeUInt16BE(1, 0);\n\t\t\tdiscoveryBuffer.writeUInt16BE(70, 2);\n\t\t\tdiscoveryBuffer.writeUInt32BE(ssrc, 4);\n\t\t\tthis.send(discoveryBuffer);\n\t\t});\n\t}\n}\n","import { EventEmitter } from 'node:events';\nimport { VoiceOpcodes } from 'discord-api-types/voice/v4';\nimport WebSocket, { type MessageEvent } from 'ws';\n\nexport interface VoiceWebSocket extends EventEmitter {\n\ton(event: 'error', listener: (error: Error) => void): this;\n\ton(event: 'open', listener: (event: WebSocket.Event) => void): this;\n\ton(event: 'close', listener: (event: WebSocket.CloseEvent) => void): this;\n\t/**\n\t * Debug event for VoiceWebSocket.\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'debug', listener: (message: string) => void): this;\n\t/**\n\t * Packet event.\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'packet', listener: (packet: any) => void): this;\n}\n\n/**\n * An extension of the WebSocket class to provide helper functionality when interacting\n * with the Discord Voice gateway.\n */\nexport class VoiceWebSocket extends EventEmitter {\n\t/**\n\t * The current heartbeat interval, if any.\n\t */\n\tprivate heartbeatInterval?: NodeJS.Timeout;\n\n\t/**\n\t * The time (milliseconds since UNIX epoch) that the last heartbeat acknowledgement packet was received.\n\t * This is set to 0 if an acknowledgement packet hasn't been received yet.\n\t */\n\tprivate lastHeartbeatAck: number;\n\n\t/**\n\t * The time (milliseconds since UNIX epoch) that the last heartbeat was sent. This is set to 0 if a heartbeat\n\t * hasn't been sent yet.\n\t */\n\tprivate lastHeartbeatSend: number;\n\n\t/**\n\t * The number of consecutively missed heartbeats.\n\t */\n\tprivate missedHeartbeats = 0;\n\n\t/**\n\t * The last recorded ping.\n\t */\n\tpublic ping?: number;\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: ((message: string) => void) | null;\n\n\t/**\n\t * The underlying WebSocket of this wrapper.\n\t */\n\tprivate readonly ws: WebSocket;\n\n\t/**\n\t * Creates a new VoiceWebSocket.\n\t *\n\t * @param address - The address to connect to\n\t */\n\tpublic constructor(address: string, debug: boolean) {\n\t\tsuper();\n\t\tthis.ws = new WebSocket(address);\n\t\tthis.ws.onmessage = (err) => this.onMessage(err);\n\t\tthis.ws.onopen = (err) => this.emit('open', err);\n\t\tthis.ws.onerror = (err: Error | WebSocket.ErrorEvent) => this.emit('error', err instanceof Error ? err : err.error);\n\t\tthis.ws.onclose = (err) => this.emit('close', err);\n\n\t\tthis.lastHeartbeatAck = 0;\n\t\tthis.lastHeartbeatSend = 0;\n\n\t\tthis.debug = debug ? (message: string) => this.emit('debug', message) : null;\n\t}\n\n\t/**\n\t * Destroys the VoiceWebSocket. The heartbeat interval is cleared, and the connection is closed.\n\t */\n\tpublic destroy() {\n\t\ttry {\n\t\t\tthis.debug?.('destroyed');\n\t\t\tthis.setHeartbeatInterval(-1);\n\t\t\tthis.ws.close(1_000);\n\t\t} catch (error) {\n\t\t\tconst err = error as Error;\n\t\t\tthis.emit('error', err);\n\t\t}\n\t}\n\n\t/**\n\t * Handles message events on the WebSocket. Attempts to JSON parse the messages and emit them\n\t * as packets.\n\t *\n\t * @param event - The message event\n\t */\n\tpublic onMessage(event: MessageEvent) {\n\t\tif (typeof event.data !== 'string') return;\n\n\t\tthis.debug?.(`<< ${event.data}`);\n\n\t\tlet packet: any;\n\t\ttry {\n\t\t\tpacket = JSON.parse(event.data);\n\t\t} catch (error) {\n\t\t\tconst err = error as Error;\n\t\t\tthis.emit('error', err);\n\t\t\treturn;\n\t\t}\n\n\t\tif (packet.op === VoiceOpcodes.HeartbeatAck) {\n\t\t\tthis.lastHeartbeatAck = Date.now();\n\t\t\tthis.missedHeartbeats = 0;\n\t\t\tthis.ping = this.lastHeartbeatAck - this.lastHeartbeatSend;\n\t\t}\n\n\t\tthis.emit('packet', packet);\n\t}\n\n\t/**\n\t * Sends a JSON-stringifiable packet over the WebSocket.\n\t *\n\t * @param packet - The packet to send\n\t */\n\tpublic sendPacket(packet: any) {\n\t\ttry {\n\t\t\tconst stringified = JSON.stringify(packet);\n\t\t\tthis.debug?.(`>> ${stringified}`);\n\t\t\tthis.ws.send(stringified);\n\t\t\treturn;\n\t\t} catch (error) {\n\t\t\tconst err = error as Error;\n\t\t\tthis.emit('error', err);\n\t\t}\n\t}\n\n\t/**\n\t * Sends a heartbeat over the WebSocket.\n\t */\n\tprivate sendHeartbeat() {\n\t\tthis.lastHeartbeatSend = Date.now();\n\t\tthis.missedHeartbeats++;\n\t\tconst nonce = this.lastHeartbeatSend;\n\t\tthis.sendPacket({\n\t\t\top: VoiceOpcodes.Heartbeat,\n\t\t\t// eslint-disable-next-line id-length\n\t\t\td: nonce,\n\t\t});\n\t}\n\n\t/**\n\t * Sets/clears an interval to send heartbeats over the WebSocket.\n\t *\n\t * @param ms - The interval in milliseconds. If negative, the interval will be unset\n\t */\n\tpublic setHeartbeatInterval(ms: number) {\n\t\tif (this.heartbeatInterval !== undefined) clearInterval(this.heartbeatInterval);\n\t\tif (ms > 0) {\n\t\t\tthis.heartbeatInterval = setInterval(() => {\n\t\t\t\tif (this.lastHeartbeatSend !== 0 && this.missedHeartbeats >= 3) {\n\t\t\t\t\t// Missed too many heartbeats - disconnect\n\t\t\t\t\tthis.ws.close();\n\t\t\t\t\tthis.setHeartbeatInterval(-1);\n\t\t\t\t}\n\n\t\t\t\tthis.sendHeartbeat();\n\t\t\t}, ms);\n\t\t}\n\t}\n}\n","/* eslint-disable jsdoc/check-param-names */\nimport { Buffer } from 'node:buffer';\nimport { VoiceOpcodes } from 'discord-api-types/voice/v4';\nimport type { VoiceConnection } from '../VoiceConnection';\nimport type { ConnectionData } from '../networking/Networking';\nimport { methods } from '../util/Secretbox';\nimport {\n\tAudioReceiveStream,\n\tcreateDefaultAudioReceiveStreamOptions,\n\ttype AudioReceiveStreamOptions,\n} from './AudioReceiveStream';\nimport { SSRCMap } from './SSRCMap';\nimport { SpeakingMap } from './SpeakingMap';\n\n/**\n * Attaches to a VoiceConnection, allowing you to receive audio packets from other\n * users that are speaking.\n *\n * @beta\n */\nexport class VoiceReceiver {\n\t/**\n\t * The attached connection of this receiver.\n\t */\n\tpublic readonly voiceConnection;\n\n\t/**\n\t * Maps SSRCs to Discord user ids.\n\t */\n\tpublic readonly ssrcMap: SSRCMap;\n\n\t/**\n\t * The current audio subscriptions of this receiver.\n\t */\n\tpublic readonly subscriptions: Map;\n\n\t/**\n\t * The connection data of the receiver.\n\t *\n\t * @internal\n\t */\n\tpublic connectionData: Partial;\n\n\t/**\n\t * The speaking map of the receiver.\n\t */\n\tpublic readonly speaking: SpeakingMap;\n\n\tpublic constructor(voiceConnection: VoiceConnection) {\n\t\tthis.voiceConnection = voiceConnection;\n\t\tthis.ssrcMap = new SSRCMap();\n\t\tthis.speaking = new SpeakingMap();\n\t\tthis.subscriptions = new Map();\n\t\tthis.connectionData = {};\n\n\t\tthis.onWsPacket = this.onWsPacket.bind(this);\n\t\tthis.onUdpMessage = this.onUdpMessage.bind(this);\n\t}\n\n\t/**\n\t * Called when a packet is received on the attached connection's WebSocket.\n\t *\n\t * @param packet - The received packet\n\t * @internal\n\t */\n\tpublic onWsPacket(packet: any) {\n\t\tif (packet.op === VoiceOpcodes.ClientDisconnect && typeof packet.d?.user_id === 'string') {\n\t\t\tthis.ssrcMap.delete(packet.d.user_id);\n\t\t} else if (\n\t\t\tpacket.op === VoiceOpcodes.Speaking &&\n\t\t\ttypeof packet.d?.user_id === 'string' &&\n\t\t\ttypeof packet.d?.ssrc === 'number'\n\t\t) {\n\t\t\tthis.ssrcMap.update({ userId: packet.d.user_id, audioSSRC: packet.d.ssrc });\n\t\t} else if (\n\t\t\tpacket.op === VoiceOpcodes.ClientConnect &&\n\t\t\ttypeof packet.d?.user_id === 'string' &&\n\t\t\ttypeof packet.d?.audio_ssrc === 'number'\n\t\t) {\n\t\t\tthis.ssrcMap.update({\n\t\t\t\tuserId: packet.d.user_id,\n\t\t\t\taudioSSRC: packet.d.audio_ssrc,\n\t\t\t\tvideoSSRC: packet.d.video_ssrc === 0 ? undefined : packet.d.video_ssrc,\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate decrypt(buffer: Buffer, mode: string, nonce: Buffer, secretKey: Uint8Array) {\n\t\t// Choose correct nonce depending on encryption\n\t\tlet end;\n\t\tif (mode === 'xsalsa20_poly1305_lite') {\n\t\t\tbuffer.copy(nonce, 0, buffer.length - 4);\n\t\t\tend = buffer.length - 4;\n\t\t} else if (mode === 'xsalsa20_poly1305_suffix') {\n\t\t\tbuffer.copy(nonce, 0, buffer.length - 24);\n\t\t\tend = buffer.length - 24;\n\t\t} else {\n\t\t\tbuffer.copy(nonce, 0, 0, 12);\n\t\t}\n\n\t\t// Open packet\n\t\tconst decrypted = methods.open(buffer.slice(12, end), nonce, secretKey);\n\t\tif (!decrypted) return;\n\t\treturn Buffer.from(decrypted);\n\t}\n\n\t/**\n\t * Parses an audio packet, decrypting it to yield an Opus packet.\n\t *\n\t * @param buffer - The buffer to parse\n\t * @param mode - The encryption mode\n\t * @param nonce - The nonce buffer used by the connection for encryption\n\t * @param secretKey - The secret key used by the connection for encryption\n\t * @returns The parsed Opus packet\n\t */\n\tprivate parsePacket(buffer: Buffer, mode: string, nonce: Buffer, secretKey: Uint8Array) {\n\t\tlet packet = this.decrypt(buffer, mode, nonce, secretKey);\n\t\tif (!packet) return;\n\n\t\t// Strip RTP Header Extensions (one-byte only)\n\t\tif (packet[0] === 0xbe && packet[1] === 0xde) {\n\t\t\tconst headerExtensionLength = packet.readUInt16BE(2);\n\t\t\tpacket = packet.subarray(4 + 4 * headerExtensionLength);\n\t\t}\n\n\t\treturn packet;\n\t}\n\n\t/**\n\t * Called when the UDP socket of the attached connection receives a message.\n\t *\n\t * @param msg - The received message\n\t * @internal\n\t */\n\tpublic onUdpMessage(msg: Buffer) {\n\t\tif (msg.length <= 8) return;\n\t\tconst ssrc = msg.readUInt32BE(8);\n\n\t\tconst userData = this.ssrcMap.get(ssrc);\n\t\tif (!userData) return;\n\n\t\tthis.speaking.onPacket(userData.userId);\n\n\t\tconst stream = this.subscriptions.get(userData.userId);\n\t\tif (!stream) return;\n\n\t\tif (this.connectionData.encryptionMode && this.connectionData.nonceBuffer && this.connectionData.secretKey) {\n\t\t\tconst packet = this.parsePacket(\n\t\t\t\tmsg,\n\t\t\t\tthis.connectionData.encryptionMode,\n\t\t\t\tthis.connectionData.nonceBuffer,\n\t\t\t\tthis.connectionData.secretKey,\n\t\t\t);\n\t\t\tif (packet) {\n\t\t\t\tstream.push(packet);\n\t\t\t} else {\n\t\t\t\tstream.destroy(new Error('Failed to parse packet'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Creates a subscription for the given user id.\n\t *\n\t * @param target - The id of the user to subscribe to\n\t * @returns A readable stream of Opus packets received from the target\n\t */\n\tpublic subscribe(userId: string, options?: Partial) {\n\t\tconst existing = this.subscriptions.get(userId);\n\t\tif (existing) return existing;\n\n\t\tconst stream = new AudioReceiveStream({\n\t\t\t...createDefaultAudioReceiveStreamOptions(),\n\t\t\t...options,\n\t\t});\n\n\t\tstream.once('close', () => this.subscriptions.delete(userId));\n\t\tthis.subscriptions.set(userId, stream);\n\t\treturn stream;\n\t}\n}\n","import type { Buffer } from 'node:buffer';\nimport { Readable, type ReadableOptions } from 'node:stream';\nimport { SILENCE_FRAME } from '../audio/AudioPlayer';\n\n/**\n * The different behaviors an audio receive stream can have for deciding when to end.\n */\nexport enum EndBehaviorType {\n\t/**\n\t * The stream will only end when manually destroyed.\n\t */\n\tManual,\n\n\t/**\n\t * The stream will end after a given time period of silence/no audio packets.\n\t */\n\tAfterSilence,\n\n\t/**\n\t * The stream will end after a given time period of no audio packets.\n\t */\n\tAfterInactivity,\n}\n\nexport type EndBehavior =\n\t| {\n\t\t\tbehavior: EndBehaviorType.AfterInactivity | EndBehaviorType.AfterSilence;\n\t\t\tduration: number;\n\t }\n\t| {\n\t\t\tbehavior: EndBehaviorType.Manual;\n\t };\n\nexport interface AudioReceiveStreamOptions extends ReadableOptions {\n\tend: EndBehavior;\n}\n\nexport function createDefaultAudioReceiveStreamOptions(): AudioReceiveStreamOptions {\n\treturn {\n\t\tend: {\n\t\t\tbehavior: EndBehaviorType.Manual,\n\t\t},\n\t};\n}\n\n/**\n * A readable stream of Opus packets received from a specific entity\n * in a Discord voice connection.\n */\nexport class AudioReceiveStream extends Readable {\n\t/**\n\t * The end behavior of the receive stream.\n\t */\n\tpublic readonly end: EndBehavior;\n\n\tprivate endTimeout?: NodeJS.Timeout;\n\n\tpublic constructor({ end, ...options }: AudioReceiveStreamOptions) {\n\t\tsuper({\n\t\t\t...options,\n\t\t\tobjectMode: true,\n\t\t});\n\n\t\tthis.end = end;\n\t}\n\n\tpublic override push(buffer: Buffer | null) {\n\t\tif (\n\t\t\tbuffer &&\n\t\t\t(this.end.behavior === EndBehaviorType.AfterInactivity ||\n\t\t\t\t(this.end.behavior === EndBehaviorType.AfterSilence &&\n\t\t\t\t\t(buffer.compare(SILENCE_FRAME) !== 0 || this.endTimeout === undefined)))\n\t\t) {\n\t\t\tthis.renewEndTimeout(this.end);\n\t\t}\n\n\t\treturn super.push(buffer);\n\t}\n\n\tprivate renewEndTimeout(end: EndBehavior & { duration: number }) {\n\t\tif (this.endTimeout) {\n\t\t\tclearTimeout(this.endTimeout);\n\t\t}\n\n\t\tthis.endTimeout = setTimeout(() => this.push(null), end.duration);\n\t}\n\n\tpublic override _read() {}\n}\n","/* eslint-disable @typescript-eslint/prefer-ts-expect-error, @typescript-eslint/method-signature-style */\nimport { Buffer } from 'node:buffer';\nimport { EventEmitter } from 'node:events';\nimport { addAudioPlayer, deleteAudioPlayer } from '../DataStore';\nimport { VoiceConnectionStatus, type VoiceConnection } from '../VoiceConnection';\nimport { noop } from '../util/util';\nimport { AudioPlayerError } from './AudioPlayerError';\nimport type { AudioResource } from './AudioResource';\nimport { PlayerSubscription } from './PlayerSubscription';\n\n// The Opus \"silent\" frame\nexport const SILENCE_FRAME = Buffer.from([0xf8, 0xff, 0xfe]);\n\n/**\n * Describes the behavior of the player when an audio packet is played but there are no available\n * voice connections to play to.\n */\nexport enum NoSubscriberBehavior {\n\t/**\n\t * Pauses playing the stream until a voice connection becomes available.\n\t */\n\tPause = 'pause',\n\n\t/**\n\t * Continues to play through the resource regardless.\n\t */\n\tPlay = 'play',\n\n\t/**\n\t * The player stops and enters the Idle state.\n\t */\n\tStop = 'stop',\n}\n\nexport enum AudioPlayerStatus {\n\t/**\n\t * When the player has paused itself. Only possible with the \"pause\" no subscriber behavior.\n\t */\n\tAutoPaused = 'autopaused',\n\n\t/**\n\t * When the player is waiting for an audio resource to become readable before transitioning to Playing.\n\t */\n\tBuffering = 'buffering',\n\n\t/**\n\t * When there is currently no resource for the player to be playing.\n\t */\n\tIdle = 'idle',\n\n\t/**\n\t * When the player has been manually paused.\n\t */\n\tPaused = 'paused',\n\n\t/**\n\t * When the player is actively playing an audio resource.\n\t */\n\tPlaying = 'playing',\n}\n\n/**\n * Options that can be passed when creating an audio player, used to specify its behavior.\n */\nexport interface CreateAudioPlayerOptions {\n\tbehaviors?: {\n\t\tmaxMissedFrames?: number;\n\t\tnoSubscriber?: NoSubscriberBehavior;\n\t};\n\tdebug?: boolean;\n}\n\n/**\n * The state that an AudioPlayer is in when it has no resource to play. This is the starting state.\n */\nexport interface AudioPlayerIdleState {\n\tstatus: AudioPlayerStatus.Idle;\n}\n\n/**\n * The state that an AudioPlayer is in when it is waiting for a resource to become readable. Once this\n * happens, the AudioPlayer will enter the Playing state. If the resource ends/errors before this, then\n * it will re-enter the Idle state.\n */\nexport interface AudioPlayerBufferingState {\n\tonFailureCallback: () => void;\n\tonReadableCallback: () => void;\n\tonStreamError: (error: Error) => void;\n\t/**\n\t * The resource that the AudioPlayer is waiting for\n\t */\n\tresource: AudioResource;\n\tstatus: AudioPlayerStatus.Buffering;\n}\n\n/**\n * The state that an AudioPlayer is in when it is actively playing an AudioResource. When playback ends,\n * it will enter the Idle state.\n */\nexport interface AudioPlayerPlayingState {\n\t/**\n\t * The number of consecutive times that the audio resource has been unable to provide an Opus frame.\n\t */\n\tmissedFrames: number;\n\tonStreamError: (error: Error) => void;\n\n\t/**\n\t * The playback duration in milliseconds of the current audio resource. This includes filler silence packets\n\t * that have been played when the resource was buffering.\n\t */\n\tplaybackDuration: number;\n\n\t/**\n\t * The resource that is being played.\n\t */\n\tresource: AudioResource;\n\n\tstatus: AudioPlayerStatus.Playing;\n}\n\n/**\n * The state that an AudioPlayer is in when it has either been explicitly paused by the user, or done\n * automatically by the AudioPlayer itself if there are no available subscribers.\n */\nexport interface AudioPlayerPausedState {\n\tonStreamError: (error: Error) => void;\n\t/**\n\t * The playback duration in milliseconds of the current audio resource. This includes filler silence packets\n\t * that have been played when the resource was buffering.\n\t */\n\tplaybackDuration: number;\n\n\t/**\n\t * The current resource of the audio player.\n\t */\n\tresource: AudioResource;\n\n\t/**\n\t * How many silence packets still need to be played to avoid audio interpolation due to the stream suddenly pausing.\n\t */\n\tsilencePacketsRemaining: number;\n\n\tstatus: AudioPlayerStatus.AutoPaused | AudioPlayerStatus.Paused;\n}\n\n/**\n * The various states that the player can be in.\n */\nexport type AudioPlayerState =\n\t| AudioPlayerBufferingState\n\t| AudioPlayerIdleState\n\t| AudioPlayerPausedState\n\t| AudioPlayerPlayingState;\n\nexport interface AudioPlayer extends EventEmitter {\n\t/**\n\t * Emitted when there is an error emitted from the audio resource played by the audio player\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'error', listener: (error: AudioPlayerError) => void): this;\n\t/**\n\t * Emitted debugging information about the audio player\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'debug', listener: (message: string) => void): this;\n\t/**\n\t * Emitted when the state of the audio player changes\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'stateChange', listener: (oldState: AudioPlayerState, newState: AudioPlayerState) => void): this;\n\t/**\n\t * Emitted when the audio player is subscribed to a voice connection\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'subscribe' | 'unsubscribe', listener: (subscription: PlayerSubscription) => void): this;\n\t/**\n\t * Emitted when the status of state changes to a specific status\n\t *\n\t * @eventProperty\n\t */\n\ton(\n\t\tevent: T,\n\t\tlistener: (oldState: AudioPlayerState, newState: AudioPlayerState & { status: T }) => void,\n\t): this;\n}\n\n/**\n * Stringifies an AudioPlayerState instance.\n *\n * @param state - The state to stringify\n */\nfunction stringifyState(state: AudioPlayerState) {\n\treturn JSON.stringify({\n\t\t...state,\n\t\tresource: Reflect.has(state, 'resource'),\n\t\tstepTimeout: Reflect.has(state, 'stepTimeout'),\n\t});\n}\n\n/**\n * Used to play audio resources (i.e. tracks, streams) to voice connections.\n *\n * @remarks\n * Audio players are designed to be re-used - even if a resource has finished playing, the player itself\n * can still be used.\n *\n * The AudioPlayer drives the timing of playback, and therefore is unaffected by voice connections\n * becoming unavailable. Its behavior in these scenarios can be configured.\n */\nexport class AudioPlayer extends EventEmitter {\n\t/**\n\t * The state that the AudioPlayer is in.\n\t */\n\tprivate _state: AudioPlayerState;\n\n\t/**\n\t * A list of VoiceConnections that are registered to this AudioPlayer. The player will attempt to play audio\n\t * to the streams in this list.\n\t */\n\tprivate readonly subscribers: PlayerSubscription[] = [];\n\n\t/**\n\t * The behavior that the player should follow when it enters certain situations.\n\t */\n\tprivate readonly behaviors: {\n\t\tmaxMissedFrames: number;\n\t\tnoSubscriber: NoSubscriberBehavior;\n\t};\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: ((message: string) => void) | null;\n\n\t/**\n\t * Creates a new AudioPlayer.\n\t */\n\tpublic constructor(options: CreateAudioPlayerOptions = {}) {\n\t\tsuper();\n\t\tthis._state = { status: AudioPlayerStatus.Idle };\n\t\tthis.behaviors = {\n\t\t\tnoSubscriber: NoSubscriberBehavior.Pause,\n\t\t\tmaxMissedFrames: 5,\n\t\t\t...options.behaviors,\n\t\t};\n\t\tthis.debug = options.debug === false ? null : (message: string) => this.emit('debug', message);\n\t}\n\n\t/**\n\t * A list of subscribed voice connections that can currently receive audio to play.\n\t */\n\tpublic get playable() {\n\t\treturn this.subscribers\n\t\t\t.filter(({ connection }) => connection.state.status === VoiceConnectionStatus.Ready)\n\t\t\t.map(({ connection }) => connection);\n\t}\n\n\t/**\n\t * Subscribes a VoiceConnection to the audio player's play list. If the VoiceConnection is already subscribed,\n\t * then the existing subscription is used.\n\t *\n\t * @remarks\n\t * This method should not be directly called. Instead, use VoiceConnection#subscribe.\n\t * @param connection - The connection to subscribe\n\t * @returns The new subscription if the voice connection is not yet subscribed, otherwise the existing subscription\n\t */\n\t// @ts-ignore\n\tprivate subscribe(connection: VoiceConnection) {\n\t\tconst existingSubscription = this.subscribers.find((subscription) => subscription.connection === connection);\n\t\tif (!existingSubscription) {\n\t\t\tconst subscription = new PlayerSubscription(connection, this);\n\t\t\tthis.subscribers.push(subscription);\n\t\t\tsetImmediate(() => this.emit('subscribe', subscription));\n\t\t\treturn subscription;\n\t\t}\n\n\t\treturn existingSubscription;\n\t}\n\n\t/**\n\t * Unsubscribes a subscription - i.e. removes a voice connection from the play list of the audio player.\n\t *\n\t * @remarks\n\t * This method should not be directly called. Instead, use PlayerSubscription#unsubscribe.\n\t * @param subscription - The subscription to remove\n\t * @returns Whether or not the subscription existed on the player and was removed\n\t */\n\t// @ts-ignore\n\tprivate unsubscribe(subscription: PlayerSubscription) {\n\t\tconst index = this.subscribers.indexOf(subscription);\n\t\tconst exists = index !== -1;\n\t\tif (exists) {\n\t\t\tthis.subscribers.splice(index, 1);\n\t\t\tsubscription.connection.setSpeaking(false);\n\t\t\tthis.emit('unsubscribe', subscription);\n\t\t}\n\n\t\treturn exists;\n\t}\n\n\t/**\n\t * The state that the player is in.\n\t */\n\tpublic get state() {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * Sets a new state for the player, performing clean-up operations where necessary.\n\t */\n\tpublic set state(newState: AudioPlayerState) {\n\t\tconst oldState = this._state;\n\t\tconst newResource = Reflect.get(newState, 'resource') as AudioResource | undefined;\n\n\t\tif (oldState.status !== AudioPlayerStatus.Idle && oldState.resource !== newResource) {\n\t\t\toldState.resource.playStream.on('error', noop);\n\t\t\toldState.resource.playStream.off('error', oldState.onStreamError);\n\t\t\toldState.resource.audioPlayer = undefined;\n\t\t\toldState.resource.playStream.destroy();\n\t\t\toldState.resource.playStream.read(); // required to ensure buffered data is drained, prevents memory leak\n\t\t}\n\n\t\t// When leaving the Buffering state (or buffering a new resource), then remove the event listeners from it\n\t\tif (\n\t\t\toldState.status === AudioPlayerStatus.Buffering &&\n\t\t\t(newState.status !== AudioPlayerStatus.Buffering || newState.resource !== oldState.resource)\n\t\t) {\n\t\t\toldState.resource.playStream.off('end', oldState.onFailureCallback);\n\t\t\toldState.resource.playStream.off('close', oldState.onFailureCallback);\n\t\t\toldState.resource.playStream.off('finish', oldState.onFailureCallback);\n\t\t\toldState.resource.playStream.off('readable', oldState.onReadableCallback);\n\t\t}\n\n\t\t// transitioning into an idle should ensure that connections stop speaking\n\t\tif (newState.status === AudioPlayerStatus.Idle) {\n\t\t\tthis._signalStopSpeaking();\n\t\t\tdeleteAudioPlayer(this);\n\t\t}\n\n\t\t// attach to the global audio player timer\n\t\tif (newResource) {\n\t\t\taddAudioPlayer(this);\n\t\t}\n\n\t\t// playing -> playing state changes should still transition if a resource changed (seems like it would be useful!)\n\t\tconst didChangeResources =\n\t\t\toldState.status !== AudioPlayerStatus.Idle &&\n\t\t\tnewState.status === AudioPlayerStatus.Playing &&\n\t\t\toldState.resource !== newState.resource;\n\n\t\tthis._state = newState;\n\n\t\tthis.emit('stateChange', oldState, this._state);\n\t\tif (oldState.status !== newState.status || didChangeResources) {\n\t\t\tthis.emit(newState.status, oldState, this._state as any);\n\t\t}\n\n\t\tthis.debug?.(`state change:\\nfrom ${stringifyState(oldState)}\\nto ${stringifyState(newState)}`);\n\t}\n\n\t/**\n\t * Plays a new resource on the player. If the player is already playing a resource, the existing resource is destroyed\n\t * (it cannot be reused, even in another player) and is replaced with the new resource.\n\t *\n\t * @remarks\n\t * The player will transition to the Playing state once playback begins, and will return to the Idle state once\n\t * playback is ended.\n\t *\n\t * If the player was previously playing a resource and this method is called, the player will not transition to the\n\t * Idle state during the swap over.\n\t * @param resource - The resource to play\n\t * @throws Will throw if attempting to play an audio resource that has already ended, or is being played by another player\n\t */\n\tpublic play(resource: AudioResource) {\n\t\tif (resource.ended) {\n\t\t\tthrow new Error('Cannot play a resource that has already ended.');\n\t\t}\n\n\t\tif (resource.audioPlayer) {\n\t\t\tif (resource.audioPlayer === this) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error('Resource is already being played by another audio player.');\n\t\t}\n\n\t\tresource.audioPlayer = this;\n\n\t\t// Attach error listeners to the stream that will propagate the error and then return to the Idle\n\t\t// state if the resource is still being used.\n\t\tconst onStreamError = (error: Error) => {\n\t\t\tif (this.state.status !== AudioPlayerStatus.Idle) {\n\t\t\t\tthis.emit('error', new AudioPlayerError(error, this.state.resource));\n\t\t\t}\n\n\t\t\tif (this.state.status !== AudioPlayerStatus.Idle && this.state.resource === resource) {\n\t\t\t\tthis.state = {\n\t\t\t\t\tstatus: AudioPlayerStatus.Idle,\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\n\t\tresource.playStream.once('error', onStreamError);\n\n\t\tif (resource.started) {\n\t\t\tthis.state = {\n\t\t\t\tstatus: AudioPlayerStatus.Playing,\n\t\t\t\tmissedFrames: 0,\n\t\t\t\tplaybackDuration: 0,\n\t\t\t\tresource,\n\t\t\t\tonStreamError,\n\t\t\t};\n\t\t} else {\n\t\t\tconst onReadableCallback = () => {\n\t\t\t\tif (this.state.status === AudioPlayerStatus.Buffering && this.state.resource === resource) {\n\t\t\t\t\tthis.state = {\n\t\t\t\t\t\tstatus: AudioPlayerStatus.Playing,\n\t\t\t\t\t\tmissedFrames: 0,\n\t\t\t\t\t\tplaybackDuration: 0,\n\t\t\t\t\t\tresource,\n\t\t\t\t\t\tonStreamError,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst onFailureCallback = () => {\n\t\t\t\tif (this.state.status === AudioPlayerStatus.Buffering && this.state.resource === resource) {\n\t\t\t\t\tthis.state = {\n\t\t\t\t\t\tstatus: AudioPlayerStatus.Idle,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tresource.playStream.once('readable', onReadableCallback);\n\n\t\t\tresource.playStream.once('end', onFailureCallback);\n\t\t\tresource.playStream.once('close', onFailureCallback);\n\t\t\tresource.playStream.once('finish', onFailureCallback);\n\n\t\t\tthis.state = {\n\t\t\t\tstatus: AudioPlayerStatus.Buffering,\n\t\t\t\tresource,\n\t\t\t\tonReadableCallback,\n\t\t\t\tonFailureCallback,\n\t\t\t\tonStreamError,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Pauses playback of the current resource, if any.\n\t *\n\t * @param interpolateSilence - If true, the player will play 5 packets of silence after pausing to prevent audio glitches\n\t * @returns `true` if the player was successfully paused, otherwise `false`\n\t */\n\tpublic pause(interpolateSilence = true) {\n\t\tif (this.state.status !== AudioPlayerStatus.Playing) return false;\n\t\tthis.state = {\n\t\t\t...this.state,\n\t\t\tstatus: AudioPlayerStatus.Paused,\n\t\t\tsilencePacketsRemaining: interpolateSilence ? 5 : 0,\n\t\t};\n\t\treturn true;\n\t}\n\n\t/**\n\t * Unpauses playback of the current resource, if any.\n\t *\n\t * @returns `true` if the player was successfully unpaused, otherwise `false`\n\t */\n\tpublic unpause() {\n\t\tif (this.state.status !== AudioPlayerStatus.Paused) return false;\n\t\tthis.state = {\n\t\t\t...this.state,\n\t\t\tstatus: AudioPlayerStatus.Playing,\n\t\t\tmissedFrames: 0,\n\t\t};\n\t\treturn true;\n\t}\n\n\t/**\n\t * Stops playback of the current resource and destroys the resource. The player will either transition to the Idle state,\n\t * or remain in its current state until the silence padding frames of the resource have been played.\n\t *\n\t * @param force - If true, will force the player to enter the Idle state even if the resource has silence padding frames\n\t * @returns `true` if the player will come to a stop, otherwise `false`\n\t */\n\tpublic stop(force = false) {\n\t\tif (this.state.status === AudioPlayerStatus.Idle) return false;\n\t\tif (force || this.state.resource.silencePaddingFrames === 0) {\n\t\t\tthis.state = {\n\t\t\t\tstatus: AudioPlayerStatus.Idle,\n\t\t\t};\n\t\t} else if (this.state.resource.silenceRemaining === -1) {\n\t\t\tthis.state.resource.silenceRemaining = this.state.resource.silencePaddingFrames;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks whether the underlying resource (if any) is playable (readable)\n\t *\n\t * @returns `true` if the resource is playable, otherwise `false`\n\t */\n\tpublic checkPlayable() {\n\t\tconst state = this._state;\n\t\tif (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) return false;\n\n\t\t// If the stream has been destroyed or is no longer readable, then transition to the Idle state.\n\t\tif (!state.resource.readable) {\n\t\t\tthis.state = {\n\t\t\t\tstatus: AudioPlayerStatus.Idle,\n\t\t\t};\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Called roughly every 20ms by the global audio player timer. Dispatches any audio packets that are buffered\n\t * by the active connections of this audio player.\n\t */\n\t// @ts-ignore\n\tprivate _stepDispatch() {\n\t\tconst state = this._state;\n\n\t\t// Guard against the Idle state\n\t\tif (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) return;\n\n\t\t// Dispatch any audio packets that were prepared in the previous cycle\n\t\tfor (const connection of this.playable) {\n\t\t\tconnection.dispatchAudio();\n\t\t}\n\t}\n\n\t/**\n\t * Called roughly every 20ms by the global audio player timer. Attempts to read an audio packet from the\n\t * underlying resource of the stream, and then has all the active connections of the audio player prepare it\n\t * (encrypt it, append header data) so that it is ready to play at the start of the next cycle.\n\t */\n\t// @ts-ignore\n\tprivate _stepPrepare() {\n\t\tconst state = this._state;\n\n\t\t// Guard against the Idle state\n\t\tif (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) return;\n\n\t\t// List of connections that can receive the packet\n\t\tconst playable = this.playable;\n\n\t\t/* If the player was previously in the AutoPaused state, check to see whether there are newly available\n\t\t connections, allowing us to transition out of the AutoPaused state back into the Playing state */\n\t\tif (state.status === AudioPlayerStatus.AutoPaused && playable.length > 0) {\n\t\t\tthis.state = {\n\t\t\t\t...state,\n\t\t\t\tstatus: AudioPlayerStatus.Playing,\n\t\t\t\tmissedFrames: 0,\n\t\t\t};\n\t\t}\n\n\t\t/* If the player is (auto)paused, check to see whether silence packets should be played and\n\t\t set a timeout to begin the next cycle, ending the current cycle here. */\n\t\tif (state.status === AudioPlayerStatus.Paused || state.status === AudioPlayerStatus.AutoPaused) {\n\t\t\tif (state.silencePacketsRemaining > 0) {\n\t\t\t\tstate.silencePacketsRemaining--;\n\t\t\t\tthis._preparePacket(SILENCE_FRAME, playable, state);\n\t\t\t\tif (state.silencePacketsRemaining === 0) {\n\t\t\t\t\tthis._signalStopSpeaking();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\t// If there are no available connections in this cycle, observe the configured \"no subscriber\" behavior.\n\t\tif (playable.length === 0) {\n\t\t\tif (this.behaviors.noSubscriber === NoSubscriberBehavior.Pause) {\n\t\t\t\tthis.state = {\n\t\t\t\t\t...state,\n\t\t\t\t\tstatus: AudioPlayerStatus.AutoPaused,\n\t\t\t\t\tsilencePacketsRemaining: 5,\n\t\t\t\t};\n\t\t\t\treturn;\n\t\t\t} else if (this.behaviors.noSubscriber === NoSubscriberBehavior.Stop) {\n\t\t\t\tthis.stop(true);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Attempt to read an Opus packet from the resource. If there isn't an available packet,\n\t\t * play a silence packet. If there are 5 consecutive cycles with failed reads, then the\n\t\t * playback will end.\n\t\t */\n\t\tconst packet: Buffer | null = state.resource.read();\n\n\t\tif (state.status === AudioPlayerStatus.Playing) {\n\t\t\tif (packet) {\n\t\t\t\tthis._preparePacket(packet, playable, state);\n\t\t\t\tstate.missedFrames = 0;\n\t\t\t} else {\n\t\t\t\tthis._preparePacket(SILENCE_FRAME, playable, state);\n\t\t\t\tstate.missedFrames++;\n\t\t\t\tif (state.missedFrames >= this.behaviors.maxMissedFrames) {\n\t\t\t\t\tthis.stop();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Signals to all the subscribed connections that they should send a packet to Discord indicating\n\t * they are no longer speaking. Called once playback of a resource ends.\n\t */\n\tprivate _signalStopSpeaking() {\n\t\tfor (const { connection } of this.subscribers) {\n\t\t\tconnection.setSpeaking(false);\n\t\t}\n\t}\n\n\t/**\n\t * Instructs the given connections to each prepare this packet to be played at the start of the\n\t * next cycle.\n\t *\n\t * @param packet - The Opus packet to be prepared by each receiver\n\t * @param receivers - The connections that should play this packet\n\t */\n\tprivate _preparePacket(\n\t\tpacket: Buffer,\n\t\treceivers: VoiceConnection[],\n\t\tstate: AudioPlayerPausedState | AudioPlayerPlayingState,\n\t) {\n\t\tstate.playbackDuration += 20;\n\t\tfor (const connection of receivers) {\n\t\t\tconnection.prepareAudioPacket(packet);\n\t\t}\n\t}\n}\n\n/**\n * Creates a new AudioPlayer to be used.\n */\nexport function createAudioPlayer(options?: CreateAudioPlayerOptions) {\n\treturn new AudioPlayer(options);\n}\n","import type { AudioResource } from './AudioResource';\n\n/**\n * An error emitted by an AudioPlayer. Contains an attached resource to aid with\n * debugging and identifying where the error came from.\n */\nexport class AudioPlayerError extends Error {\n\t/**\n\t * The resource associated with the audio player at the time the error was thrown.\n\t */\n\tpublic readonly resource: AudioResource;\n\n\tpublic constructor(error: Error, resource: AudioResource) {\n\t\tsuper(error.message);\n\t\tthis.resource = resource;\n\t\tthis.name = error.name;\n\t\tthis.stack = error.stack!;\n\t}\n}\n","/* eslint-disable @typescript-eslint/dot-notation */\nimport type { VoiceConnection } from '../VoiceConnection';\nimport type { AudioPlayer } from './AudioPlayer';\n\n/**\n * Represents a subscription of a voice connection to an audio player, allowing\n * the audio player to play audio on the voice connection.\n */\nexport class PlayerSubscription {\n\t/**\n\t * The voice connection of this subscription.\n\t */\n\tpublic readonly connection: VoiceConnection;\n\n\t/**\n\t * The audio player of this subscription.\n\t */\n\tpublic readonly player: AudioPlayer;\n\n\tpublic constructor(connection: VoiceConnection, player: AudioPlayer) {\n\t\tthis.connection = connection;\n\t\tthis.player = player;\n\t}\n\n\t/**\n\t * Unsubscribes the connection from the audio player, meaning that the\n\t * audio player cannot stream audio to it until a new subscription is made.\n\t */\n\tpublic unsubscribe() {\n\t\tthis.connection['onSubscriptionRemoved'](this);\n\t\tthis.player['unsubscribe'](this);\n\t}\n}\n","import { EventEmitter } from 'node:events';\n\n/**\n * The known data for a user in a Discord voice connection.\n */\nexport interface VoiceUserData {\n\t/**\n\t * The SSRC of the user's audio stream.\n\t */\n\taudioSSRC: number;\n\n\t/**\n\t * The Discord user id of the user.\n\t */\n\tuserId: string;\n\n\t/**\n\t * The SSRC of the user's video stream (if one exists)\n\t * Cannot be 0. If undefined, the user has no video stream.\n\t */\n\tvideoSSRC?: number;\n}\n\nexport interface SSRCMap extends EventEmitter {\n\ton(event: 'create', listener: (newData: VoiceUserData) => void): this;\n\ton(event: 'update', listener: (oldData: VoiceUserData | undefined, newData: VoiceUserData) => void): this;\n\ton(event: 'delete', listener: (deletedData: VoiceUserData) => void): this;\n}\n\n/**\n * Maps audio SSRCs to data of users in voice connections.\n */\nexport class SSRCMap extends EventEmitter {\n\t/**\n\t * The underlying map.\n\t */\n\tprivate readonly map: Map;\n\n\tpublic constructor() {\n\t\tsuper();\n\t\tthis.map = new Map();\n\t}\n\n\t/**\n\t * Updates the map with new user data\n\t *\n\t * @param data - The data to update with\n\t */\n\tpublic update(data: VoiceUserData) {\n\t\tconst existing = this.map.get(data.audioSSRC);\n\n\t\tconst newValue = {\n\t\t\t...this.map.get(data.audioSSRC),\n\t\t\t...data,\n\t\t};\n\n\t\tthis.map.set(data.audioSSRC, newValue);\n\t\tif (!existing) this.emit('create', newValue);\n\t\tthis.emit('update', existing, newValue);\n\t}\n\n\t/**\n\t * Gets the stored voice data of a user.\n\t *\n\t * @param target - The target, either their user id or audio SSRC\n\t */\n\tpublic get(target: number | string) {\n\t\tif (typeof target === 'number') {\n\t\t\treturn this.map.get(target);\n\t\t}\n\n\t\tfor (const data of this.map.values()) {\n\t\t\tif (data.userId === target) {\n\t\t\t\treturn data;\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Deletes the stored voice data about a user.\n\t *\n\t * @param target - The target of the delete operation, either their audio SSRC or user id\n\t * @returns The data that was deleted, if any\n\t */\n\tpublic delete(target: number | string) {\n\t\tif (typeof target === 'number') {\n\t\t\tconst existing = this.map.get(target);\n\t\t\tif (existing) {\n\t\t\t\tthis.map.delete(target);\n\t\t\t\tthis.emit('delete', existing);\n\t\t\t}\n\n\t\t\treturn existing;\n\t\t}\n\n\t\tfor (const [audioSSRC, data] of this.map.entries()) {\n\t\t\tif (data.userId === target) {\n\t\t\t\tthis.map.delete(audioSSRC);\n\t\t\t\tthis.emit('delete', data);\n\t\t\t\treturn data;\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n}\n","/* eslint-disable @typescript-eslint/unified-signatures */\nimport { EventEmitter } from 'node:events';\n\nexport interface SpeakingMap extends EventEmitter {\n\t/**\n\t * Emitted when a user starts speaking.\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'start', listener: (userId: string) => void): this;\n\n\t/**\n\t * Emitted when a user ends speaking.\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'end', listener: (userId: string) => void): this;\n}\n\n/**\n * Tracks the speaking states of users in a voice channel.\n */\nexport class SpeakingMap extends EventEmitter {\n\t/**\n\t * The delay after a packet is received from a user until they're marked as not speaking anymore.\n\t */\n\tpublic static readonly DELAY = 100;\n\n\t/**\n\t * The currently speaking users, mapped to the milliseconds since UNIX epoch at which they started speaking.\n\t */\n\tpublic readonly users: Map;\n\n\tprivate readonly speakingTimeouts: Map;\n\n\tpublic constructor() {\n\t\tsuper();\n\t\tthis.users = new Map();\n\t\tthis.speakingTimeouts = new Map();\n\t}\n\n\tpublic onPacket(userId: string) {\n\t\tconst timeout = this.speakingTimeouts.get(userId);\n\t\tif (timeout) {\n\t\t\tclearTimeout(timeout);\n\t\t} else {\n\t\t\tthis.users.set(userId, Date.now());\n\t\t\tthis.emit('start', userId);\n\t\t}\n\n\t\tthis.startTimeout(userId);\n\t}\n\n\tprivate startTimeout(userId: string) {\n\t\tthis.speakingTimeouts.set(\n\t\t\tuserId,\n\t\t\tsetTimeout(() => {\n\t\t\t\tthis.emit('end', userId);\n\t\t\t\tthis.speakingTimeouts.delete(userId);\n\t\t\t\tthis.users.delete(userId);\n\t\t\t}, SpeakingMap.DELAY),\n\t\t);\n\t}\n}\n","import type { JoinConfig } from './DataStore';\nimport { createVoiceConnection } from './VoiceConnection';\nimport type { DiscordGatewayAdapterCreator } from './util/adapter';\n\n/**\n * The options that can be given when creating a voice connection.\n */\nexport interface CreateVoiceConnectionOptions {\n\tadapterCreator: DiscordGatewayAdapterCreator;\n\n\t/**\n\t * If true, debug messages will be enabled for the voice connection and its\n\t * related components. Defaults to false.\n\t */\n\tdebug?: boolean | undefined;\n}\n\n/**\n * The options that can be given when joining a voice channel.\n */\nexport interface JoinVoiceChannelOptions {\n\t/**\n\t * The id of the Discord voice channel to join.\n\t */\n\tchannelId: string;\n\n\t/**\n\t * An optional group identifier for the voice connection.\n\t */\n\tgroup?: string;\n\n\t/**\n\t * The id of the guild that the voice channel belongs to.\n\t */\n\tguildId: string;\n\n\t/**\n\t * Whether to join the channel deafened (defaults to true)\n\t */\n\tselfDeaf?: boolean;\n\n\t/**\n\t * Whether to join the channel muted (defaults to true)\n\t */\n\tselfMute?: boolean;\n}\n\n/**\n * Creates a VoiceConnection to a Discord voice channel.\n *\n * @param options - the options for joining the voice channel\n */\nexport function joinVoiceChannel(options: CreateVoiceConnectionOptions & JoinVoiceChannelOptions) {\n\tconst joinConfig: JoinConfig = {\n\t\tselfDeaf: true,\n\t\tselfMute: false,\n\t\tgroup: 'default',\n\t\t...options,\n\t};\n\n\treturn createVoiceConnection(joinConfig, {\n\t\tadapterCreator: options.adapterCreator,\n\t\tdebug: options.debug,\n\t});\n}\n","import type { Buffer } from 'node:buffer';\nimport { pipeline, type Readable } from 'node:stream';\nimport prism from 'prism-media';\nimport { noop } from '../util/util';\nimport { SILENCE_FRAME, type AudioPlayer } from './AudioPlayer';\nimport { findPipeline, StreamType, TransformerType, type Edge } from './TransformerGraph';\n\n/**\n * Options that are set when creating a new audio resource.\n *\n * @typeParam T - the type for the metadata (if any) of the audio resource\n */\nexport interface CreateAudioResourceOptions {\n\t/**\n\t * Whether or not inline volume should be enabled. If enabled, you will be able to change the volume\n\t * of the stream on-the-fly. However, this also increases the performance cost of playback. Defaults to `false`.\n\t */\n\tinlineVolume?: boolean;\n\n\t/**\n\t * The type of the input stream. Defaults to `StreamType.Arbitrary`.\n\t */\n\tinputType?: StreamType;\n\n\t/**\n\t * Optional metadata that can be attached to the resource (e.g. track title, random id).\n\t * This is useful for identification purposes when the resource is passed around in events.\n\t * See {@link AudioResource.metadata}\n\t */\n\tmetadata?: T;\n\n\t/**\n\t * The number of silence frames to append to the end of the resource's audio stream, to prevent interpolation glitches.\n\t * Defaults to 5.\n\t */\n\tsilencePaddingFrames?: number;\n}\n\n/**\n * Represents an audio resource that can be played by an audio player.\n *\n * @typeParam T - the type for the metadata (if any) of the audio resource\n */\nexport class AudioResource {\n\t/**\n\t * An object-mode Readable stream that emits Opus packets. This is what is played by audio players.\n\t */\n\tpublic readonly playStream: Readable;\n\n\t/**\n\t * The pipeline used to convert the input stream into a playable format. For example, this may\n\t * contain an FFmpeg component for arbitrary inputs, and it may contain a VolumeTransformer component\n\t * for resources with inline volume transformation enabled.\n\t */\n\tpublic readonly edges: readonly Edge[];\n\n\t/**\n\t * Optional metadata that can be used to identify the resource.\n\t */\n\tpublic metadata: T;\n\n\t/**\n\t * If the resource was created with inline volume transformation enabled, then this will be a\n\t * prism-media VolumeTransformer. You can use this to alter the volume of the stream.\n\t */\n\tpublic readonly volume?: prism.VolumeTransformer;\n\n\t/**\n\t * If using an Opus encoder to create this audio resource, then this will be a prism-media opus.Encoder.\n\t * You can use this to control settings such as bitrate, FEC, PLP.\n\t */\n\tpublic readonly encoder?: prism.opus.Encoder;\n\n\t/**\n\t * The audio player that the resource is subscribed to, if any.\n\t */\n\tpublic audioPlayer?: AudioPlayer | undefined;\n\n\t/**\n\t * The playback duration of this audio resource, given in milliseconds.\n\t */\n\tpublic playbackDuration = 0;\n\n\t/**\n\t * Whether or not the stream for this resource has started (data has become readable)\n\t */\n\tpublic started = false;\n\n\t/**\n\t * The number of silence frames to append to the end of the resource's audio stream, to prevent interpolation glitches.\n\t */\n\tpublic readonly silencePaddingFrames: number;\n\n\t/**\n\t * The number of remaining silence frames to play. If -1, the frames have not yet started playing.\n\t */\n\tpublic silenceRemaining = -1;\n\n\tpublic constructor(edges: readonly Edge[], streams: readonly Readable[], metadata: T, silencePaddingFrames: number) {\n\t\tthis.edges = edges;\n\t\tthis.playStream = streams.length > 1 ? (pipeline(streams, noop) as any as Readable) : streams[0]!;\n\t\tthis.metadata = metadata;\n\t\tthis.silencePaddingFrames = silencePaddingFrames;\n\n\t\tfor (const stream of streams) {\n\t\t\tif (stream instanceof prism.VolumeTransformer) {\n\t\t\t\tthis.volume = stream;\n\t\t\t} else if (stream instanceof prism.opus.Encoder) {\n\t\t\t\tthis.encoder = stream;\n\t\t\t}\n\t\t}\n\n\t\tthis.playStream.once('readable', () => (this.started = true));\n\t}\n\n\t/**\n\t * Whether this resource is readable. If the underlying resource is no longer readable, this will still return true\n\t * while there are silence padding frames left to play.\n\t */\n\tpublic get readable() {\n\t\tif (this.silenceRemaining === 0) return false;\n\t\tconst real = this.playStream.readable;\n\t\tif (!real) {\n\t\t\tif (this.silenceRemaining === -1) this.silenceRemaining = this.silencePaddingFrames;\n\t\t\treturn this.silenceRemaining !== 0;\n\t\t}\n\n\t\treturn real;\n\t}\n\n\t/**\n\t * Whether this resource has ended or not.\n\t */\n\tpublic get ended() {\n\t\treturn this.playStream.readableEnded || this.playStream.destroyed || this.silenceRemaining === 0;\n\t}\n\n\t/**\n\t * Attempts to read an Opus packet from the audio resource. If a packet is available, the playbackDuration\n\t * is incremented.\n\t *\n\t * @remarks\n\t * It is advisable to check that the playStream is readable before calling this method. While no runtime\n\t * errors will be thrown, you should check that the resource is still available before attempting to\n\t * read from it.\n\t * @internal\n\t */\n\tpublic read(): Buffer | null {\n\t\tif (this.silenceRemaining === 0) {\n\t\t\treturn null;\n\t\t} else if (this.silenceRemaining > 0) {\n\t\t\tthis.silenceRemaining--;\n\t\t\treturn SILENCE_FRAME;\n\t\t}\n\n\t\tconst packet = this.playStream.read() as Buffer | null;\n\t\tif (packet) {\n\t\t\tthis.playbackDuration += 20;\n\t\t}\n\n\t\treturn packet;\n\t}\n}\n\n/**\n * Ensures that a path contains at least one volume transforming component.\n *\n * @param path - The path to validate constraints on\n */\nexport const VOLUME_CONSTRAINT = (path: Edge[]) => path.some((edge) => edge.type === TransformerType.InlineVolume);\n\nexport const NO_CONSTRAINT = () => true;\n\n/**\n * Tries to infer the type of a stream to aid with transcoder pipelining.\n *\n * @param stream - The stream to infer the type of\n */\nexport function inferStreamType(stream: Readable): {\n\thasVolume: boolean;\n\tstreamType: StreamType;\n} {\n\tif (stream instanceof prism.opus.Encoder) {\n\t\treturn { streamType: StreamType.Opus, hasVolume: false };\n\t} else if (stream instanceof prism.opus.Decoder) {\n\t\treturn { streamType: StreamType.Raw, hasVolume: false };\n\t} else if (stream instanceof prism.VolumeTransformer) {\n\t\treturn { streamType: StreamType.Raw, hasVolume: true };\n\t} else if (stream instanceof prism.opus.OggDemuxer) {\n\t\treturn { streamType: StreamType.Opus, hasVolume: false };\n\t} else if (stream instanceof prism.opus.WebmDemuxer) {\n\t\treturn { streamType: StreamType.Opus, hasVolume: false };\n\t}\n\n\treturn { streamType: StreamType.Arbitrary, hasVolume: false };\n}\n\n/**\n * Creates an audio resource that can be played by audio players.\n *\n * @remarks\n * If the input is given as a string, then the inputType option will be overridden and FFmpeg will be used.\n *\n * If the input is not in the correct format, then a pipeline of transcoders and transformers will be created\n * to ensure that the resultant stream is in the correct format for playback. This could involve using FFmpeg,\n * Opus transcoders, and Ogg/WebM demuxers.\n * @param input - The resource to play\n * @param options - Configurable options for creating the resource\n * @typeParam T - the type for the metadata (if any) of the audio resource\n */\nexport function createAudioResource(\n\tinput: Readable | string,\n\toptions: CreateAudioResourceOptions &\n\t\tPick<\n\t\t\tT extends null | undefined ? CreateAudioResourceOptions : Required>,\n\t\t\t'metadata'\n\t\t>,\n): AudioResource;\n\n/**\n * Creates an audio resource that can be played by audio players.\n *\n * @remarks\n * If the input is given as a string, then the inputType option will be overridden and FFmpeg will be used.\n *\n * If the input is not in the correct format, then a pipeline of transcoders and transformers will be created\n * to ensure that the resultant stream is in the correct format for playback. This could involve using FFmpeg,\n * Opus transcoders, and Ogg/WebM demuxers.\n * @param input - The resource to play\n * @param options - Configurable options for creating the resource\n * @typeParam T - the type for the metadata (if any) of the audio resource\n */\nexport function createAudioResource(\n\tinput: Readable | string,\n\toptions?: Omit, 'metadata'>,\n): AudioResource;\n\n/**\n * Creates an audio resource that can be played by audio players.\n *\n * @remarks\n * If the input is given as a string, then the inputType option will be overridden and FFmpeg will be used.\n *\n * If the input is not in the correct format, then a pipeline of transcoders and transformers will be created\n * to ensure that the resultant stream is in the correct format for playback. This could involve using FFmpeg,\n * Opus transcoders, and Ogg/WebM demuxers.\n * @param input - The resource to play\n * @param options - Configurable options for creating the resource\n * @typeParam T - the type for the metadata (if any) of the audio resource\n */\nexport function createAudioResource(\n\tinput: Readable | string,\n\toptions: CreateAudioResourceOptions = {},\n): AudioResource {\n\tlet inputType = options.inputType;\n\tlet needsInlineVolume = Boolean(options.inlineVolume);\n\n\t// string inputs can only be used with FFmpeg\n\tif (typeof input === 'string') {\n\t\tinputType = StreamType.Arbitrary;\n\t} else if (inputType === undefined) {\n\t\tconst analysis = inferStreamType(input);\n\t\tinputType = analysis.streamType;\n\t\tneedsInlineVolume = needsInlineVolume && !analysis.hasVolume;\n\t}\n\n\tconst transformerPipeline = findPipeline(inputType, needsInlineVolume ? VOLUME_CONSTRAINT : NO_CONSTRAINT);\n\n\tif (transformerPipeline.length === 0) {\n\t\tif (typeof input === 'string') throw new Error(`Invalid pipeline constructed for string resource '${input}'`);\n\t\t// No adjustments required\n\t\treturn new AudioResource([], [input], (options.metadata ?? null) as T, options.silencePaddingFrames ?? 5);\n\t}\n\n\tconst streams = transformerPipeline.map((edge) => edge.transformer(input));\n\tif (typeof input !== 'string') streams.unshift(input);\n\n\treturn new AudioResource(\n\t\ttransformerPipeline,\n\t\tstreams,\n\t\t(options.metadata ?? null) as T,\n\t\toptions.silencePaddingFrames ?? 5,\n\t);\n}\n","import type { Readable } from 'node:stream';\nimport prism from 'prism-media';\n\n/**\n * This module creates a Transformer Graph to figure out what the most efficient way\n * of transforming the input stream into something playable would be.\n */\n\nconst FFMPEG_PCM_ARGUMENTS = ['-analyzeduration', '0', '-loglevel', '0', '-f', 's16le', '-ar', '48000', '-ac', '2'];\nconst FFMPEG_OPUS_ARGUMENTS = [\n\t'-analyzeduration',\n\t'0',\n\t'-loglevel',\n\t'0',\n\t'-acodec',\n\t'libopus',\n\t'-f',\n\t'opus',\n\t'-ar',\n\t'48000',\n\t'-ac',\n\t'2',\n];\n\n/**\n * The different types of stream that can exist within the pipeline.\n *\n * @remarks\n * - `Arbitrary` - the type of the stream at this point is unknown.\n * - `Raw` - the stream at this point is s16le PCM.\n * - `OggOpus` - the stream at this point is Opus audio encoded in an Ogg wrapper.\n * - `WebmOpus` - the stream at this point is Opus audio encoded in a WebM wrapper.\n * - `Opus` - the stream at this point is Opus audio, and the stream is in object-mode. This is ready to play.\n */\nexport enum StreamType {\n\tArbitrary = 'arbitrary',\n\tOggOpus = 'ogg/opus',\n\tOpus = 'opus',\n\tRaw = 'raw',\n\tWebmOpus = 'webm/opus',\n}\n\n/**\n * The different types of transformers that can exist within the pipeline.\n */\nexport enum TransformerType {\n\tFFmpegOgg = 'ffmpeg ogg',\n\tFFmpegPCM = 'ffmpeg pcm',\n\tInlineVolume = 'volume transformer',\n\tOggOpusDemuxer = 'ogg/opus demuxer',\n\tOpusDecoder = 'opus decoder',\n\tOpusEncoder = 'opus encoder',\n\tWebmOpusDemuxer = 'webm/opus demuxer',\n}\n\n/**\n * Represents a pathway from one stream type to another using a transformer.\n */\nexport interface Edge {\n\tcost: number;\n\tfrom: Node;\n\tto: Node;\n\ttransformer(input: Readable | string): Readable;\n\ttype: TransformerType;\n}\n\n/**\n * Represents a type of stream within the graph, e.g. an Opus stream, or a stream of raw audio.\n */\nexport class Node {\n\t/**\n\t * The outbound edges from this node.\n\t */\n\tpublic readonly edges: Edge[] = [];\n\n\t/**\n\t * The type of stream for this node.\n\t */\n\tpublic readonly type: StreamType;\n\n\tpublic constructor(type: StreamType) {\n\t\tthis.type = type;\n\t}\n\n\t/**\n\t * Creates an outbound edge from this node.\n\t *\n\t * @param edge - The edge to create\n\t */\n\tpublic addEdge(edge: Omit) {\n\t\tthis.edges.push({ ...edge, from: this });\n\t}\n}\n\n// Create a node for each stream type\nconst NODES = new Map();\nfor (const streamType of Object.values(StreamType)) {\n\tNODES.set(streamType, new Node(streamType));\n}\n\n/**\n * Gets a node from its stream type.\n *\n * @param type - The stream type of the target node\n */\nexport function getNode(type: StreamType) {\n\tconst node = NODES.get(type);\n\tif (!node) throw new Error(`Node type '${type}' does not exist!`);\n\treturn node;\n}\n\ngetNode(StreamType.Raw).addEdge({\n\ttype: TransformerType.OpusEncoder,\n\tto: getNode(StreamType.Opus),\n\tcost: 1.5,\n\ttransformer: () => new prism.opus.Encoder({ rate: 48_000, channels: 2, frameSize: 960 }),\n});\n\ngetNode(StreamType.Opus).addEdge({\n\ttype: TransformerType.OpusDecoder,\n\tto: getNode(StreamType.Raw),\n\tcost: 1.5,\n\ttransformer: () => new prism.opus.Decoder({ rate: 48_000, channels: 2, frameSize: 960 }),\n});\n\ngetNode(StreamType.OggOpus).addEdge({\n\ttype: TransformerType.OggOpusDemuxer,\n\tto: getNode(StreamType.Opus),\n\tcost: 1,\n\ttransformer: () => new prism.opus.OggDemuxer(),\n});\n\ngetNode(StreamType.WebmOpus).addEdge({\n\ttype: TransformerType.WebmOpusDemuxer,\n\tto: getNode(StreamType.Opus),\n\tcost: 1,\n\ttransformer: () => new prism.opus.WebmDemuxer(),\n});\n\nconst FFMPEG_PCM_EDGE: Omit = {\n\ttype: TransformerType.FFmpegPCM,\n\tto: getNode(StreamType.Raw),\n\tcost: 2,\n\ttransformer: (input) =>\n\t\tnew prism.FFmpeg({\n\t\t\targs: typeof input === 'string' ? ['-i', input, ...FFMPEG_PCM_ARGUMENTS] : FFMPEG_PCM_ARGUMENTS,\n\t\t}),\n};\n\ngetNode(StreamType.Arbitrary).addEdge(FFMPEG_PCM_EDGE);\ngetNode(StreamType.OggOpus).addEdge(FFMPEG_PCM_EDGE);\ngetNode(StreamType.WebmOpus).addEdge(FFMPEG_PCM_EDGE);\n\ngetNode(StreamType.Raw).addEdge({\n\ttype: TransformerType.InlineVolume,\n\tto: getNode(StreamType.Raw),\n\tcost: 0.5,\n\ttransformer: () => new prism.VolumeTransformer({ type: 's16le' }),\n});\n\n// Try to enable FFmpeg Ogg optimizations\nfunction canEnableFFmpegOptimizations(): boolean {\n\ttry {\n\t\treturn prism.FFmpeg.getInfo().output.includes('--enable-libopus');\n\t} catch {}\n\n\treturn false;\n}\n\nif (canEnableFFmpegOptimizations()) {\n\tconst FFMPEG_OGG_EDGE: Omit = {\n\t\ttype: TransformerType.FFmpegOgg,\n\t\tto: getNode(StreamType.OggOpus),\n\t\tcost: 2,\n\t\ttransformer: (input) =>\n\t\t\tnew prism.FFmpeg({\n\t\t\t\targs: typeof input === 'string' ? ['-i', input, ...FFMPEG_OPUS_ARGUMENTS] : FFMPEG_OPUS_ARGUMENTS,\n\t\t\t}),\n\t};\n\tgetNode(StreamType.Arbitrary).addEdge(FFMPEG_OGG_EDGE);\n\t// Include Ogg and WebM as well in case they have different sampling rates or are mono instead of stereo\n\t// at the moment, this will not do anything. However, if/when detection for correct Opus headers is\n\t// implemented, this will help inform the voice engine that it is able to transcode the audio.\n\tgetNode(StreamType.OggOpus).addEdge(FFMPEG_OGG_EDGE);\n\tgetNode(StreamType.WebmOpus).addEdge(FFMPEG_OGG_EDGE);\n}\n\n/**\n * Represents a step in the path from node A to node B.\n */\ninterface Step {\n\t/**\n\t * The cost of the steps after this step.\n\t */\n\tcost: number;\n\n\t/**\n\t * The edge associated with this step.\n\t */\n\tedge?: Edge;\n\n\t/**\n\t * The next step.\n\t */\n\tnext?: Step;\n}\n\n/**\n * Finds the shortest cost path from node A to node B.\n *\n * @param from - The start node\n * @param constraints - Extra validation for a potential solution. Takes a path, returns true if the path is valid\n * @param goal - The target node\n * @param path - The running path\n * @param depth - The number of remaining recursions\n */\nfunction findPath(\n\tfrom: Node,\n\tconstraints: (path: Edge[]) => boolean,\n\tgoal = getNode(StreamType.Opus),\n\tpath: Edge[] = [],\n\tdepth = 5,\n): Step {\n\tif (from === goal && constraints(path)) {\n\t\treturn { cost: 0 };\n\t} else if (depth === 0) {\n\t\treturn { cost: Number.POSITIVE_INFINITY };\n\t}\n\n\tlet currentBest: Step | undefined;\n\tfor (const edge of from.edges) {\n\t\tif (currentBest && edge.cost > currentBest.cost) continue;\n\t\tconst next = findPath(edge.to, constraints, goal, [...path, edge], depth - 1);\n\t\tconst cost = edge.cost + next.cost;\n\t\tif (!currentBest || cost < currentBest.cost) {\n\t\t\tcurrentBest = { cost, edge, next };\n\t\t}\n\t}\n\n\treturn currentBest ?? { cost: Number.POSITIVE_INFINITY };\n}\n\n/**\n * Takes the solution from findPath and assembles it into a list of edges.\n *\n * @param step - The first step of the path\n */\nfunction constructPipeline(step: Step) {\n\tconst edges = [];\n\tlet current: Step | undefined = step;\n\twhile (current?.edge) {\n\t\tedges.push(current.edge);\n\t\tcurrent = current.next;\n\t}\n\n\treturn edges;\n}\n\n/**\n * Finds the lowest-cost pipeline to convert the input stream type into an Opus stream.\n *\n * @param from - The stream type to start from\n * @param constraint - Extra constraints that may be imposed on potential solution\n */\nexport function findPipeline(from: StreamType, constraint: (path: Edge[]) => boolean) {\n\treturn constructPipeline(findPath(getNode(from), constraint));\n}\n","/* eslint-disable @typescript-eslint/no-var-requires */\n/* eslint-disable @typescript-eslint/no-require-imports */\nimport { resolve, dirname } from 'node:path';\nimport prism from 'prism-media';\n\n/**\n * Tries to find the package.json file for a given module.\n *\n * @param dir - The directory to look in\n * @param packageName - The name of the package to look for\n * @param depth - The maximum recursion depth\n */\nfunction findPackageJSON(\n\tdir: string,\n\tpackageName: string,\n\tdepth: number,\n): { name: string; version: string } | undefined {\n\tif (depth === 0) return undefined;\n\tconst attemptedPath = resolve(dir, './package.json');\n\ttry {\n\t\tconst pkg = require(attemptedPath);\n\t\tif (pkg.name !== packageName) throw new Error('package.json does not match');\n\t\treturn pkg;\n\t} catch {\n\t\treturn findPackageJSON(resolve(dir, '..'), packageName, depth - 1);\n\t}\n}\n\n/**\n * Tries to find the version of a dependency.\n *\n * @param name - The package to find the version of\n */\nfunction version(name: string): string {\n\ttry {\n\t\tif (name === '@discordjs/voice') {\n\t\t\treturn '0.16.0';\n\t\t}\n\n\t\tconst pkg = findPackageJSON(dirname(require.resolve(name)), name, 3);\n\t\treturn pkg?.version ?? 'not found';\n\t} catch {\n\t\treturn 'not found';\n\t}\n}\n\n/**\n * Generates a report of the dependencies used by the \\@discordjs/voice module.\n * Useful for debugging.\n */\nexport function generateDependencyReport() {\n\tconst report = [];\n\tconst addVersion = (name: string) => report.push(`- ${name}: ${version(name)}`);\n\t// general\n\treport.push('Core Dependencies');\n\taddVersion('@discordjs/voice');\n\taddVersion('prism-media');\n\treport.push('');\n\n\t// opus\n\treport.push('Opus Libraries');\n\taddVersion('@discordjs/opus');\n\taddVersion('opusscript');\n\treport.push('');\n\n\t// encryption\n\treport.push('Encryption Libraries');\n\taddVersion('sodium-native');\n\taddVersion('sodium');\n\taddVersion('libsodium-wrappers');\n\taddVersion('tweetnacl');\n\treport.push('');\n\n\t// ffmpeg\n\treport.push('FFmpeg');\n\ttry {\n\t\tconst info = prism.FFmpeg.getInfo();\n\t\treport.push(`- version: ${info.version}`);\n\t\treport.push(`- libopus: ${info.output.includes('--enable-libopus') ? 'yes' : 'no'}`);\n\t} catch {\n\t\treport.push('- not found');\n\t}\n\n\treturn ['-'.repeat(50), ...report, '-'.repeat(50)].join('\\n');\n}\n","import { type EventEmitter, once } from 'node:events';\nimport type { VoiceConnection, VoiceConnectionStatus } from '../VoiceConnection';\nimport type { AudioPlayer, AudioPlayerStatus } from '../audio/AudioPlayer';\nimport { abortAfter } from './abortAfter';\n\n/**\n * Allows a voice connection a specified amount of time to enter a given state, otherwise rejects with an error.\n *\n * @param target - The voice connection that we want to observe the state change for\n * @param status - The status that the voice connection should be in\n * @param timeoutOrSignal - The maximum time we are allowing for this to occur, or a signal that will abort the operation\n */\nexport function entersState(\n\ttarget: VoiceConnection,\n\tstatus: VoiceConnectionStatus,\n\ttimeoutOrSignal: AbortSignal | number,\n): Promise;\n\n/**\n * Allows an audio player a specified amount of time to enter a given state, otherwise rejects with an error.\n *\n * @param target - The audio player that we want to observe the state change for\n * @param status - The status that the audio player should be in\n * @param timeoutOrSignal - The maximum time we are allowing for this to occur, or a signal that will abort the operation\n */\nexport function entersState(\n\ttarget: AudioPlayer,\n\tstatus: AudioPlayerStatus,\n\ttimeoutOrSignal: AbortSignal | number,\n): Promise;\n\n/**\n * Allows a target a specified amount of time to enter a given state, otherwise rejects with an error.\n *\n * @param target - The object that we want to observe the state change for\n * @param status - The status that the target should be in\n * @param timeoutOrSignal - The maximum time we are allowing for this to occur, or a signal that will abort the operation\n */\nexport async function entersState(\n\ttarget: T,\n\tstatus: AudioPlayerStatus | VoiceConnectionStatus,\n\ttimeoutOrSignal: AbortSignal | number,\n) {\n\tif (target.state.status !== status) {\n\t\tconst [ac, signal] =\n\t\t\ttypeof timeoutOrSignal === 'number' ? abortAfter(timeoutOrSignal) : [undefined, timeoutOrSignal];\n\t\ttry {\n\t\t\tawait once(target as EventEmitter, status, { signal });\n\t\t} finally {\n\t\t\tac?.abort();\n\t\t}\n\t}\n\n\treturn target;\n}\n","/**\n * Creates an abort controller that aborts after the given time.\n *\n * @param delay - The time in milliseconds to wait before aborting\n */\nexport function abortAfter(delay: number): [AbortController, AbortSignal] {\n\tconst ac = new AbortController();\n\tconst timeout = setTimeout(() => ac.abort(), delay);\n\t// @ts-expect-error: No type for timeout\n\tac.signal.addEventListener('abort', () => clearTimeout(timeout));\n\treturn [ac, ac.signal];\n}\n","import { Buffer } from 'node:buffer';\nimport process from 'node:process';\nimport { Readable } from 'node:stream';\nimport prism from 'prism-media';\nimport { StreamType } from '..';\nimport { noop } from './util';\n\n/**\n * Takes an Opus Head, and verifies whether the associated Opus audio is suitable to play in a Discord voice channel.\n *\n * @param opusHead - The Opus Head to validate\n * @returns `true` if suitable to play in a Discord voice channel, otherwise `false`\n */\nexport function validateDiscordOpusHead(opusHead: Buffer): boolean {\n\tconst channels = opusHead.readUInt8(9);\n\tconst sampleRate = opusHead.readUInt32LE(12);\n\treturn channels === 2 && sampleRate === 48_000;\n}\n\n/**\n * The resulting information after probing an audio stream\n */\nexport interface ProbeInfo {\n\t/**\n\t * The readable audio stream to use. You should use this rather than the input stream, as the probing\n\t * function can sometimes read the input stream to its end and cause the stream to close.\n\t */\n\tstream: Readable;\n\n\t/**\n\t * The recommended stream type for this audio stream.\n\t */\n\ttype: StreamType;\n}\n\n/**\n * Attempt to probe a readable stream to figure out whether it can be demuxed using an Ogg or WebM Opus demuxer.\n *\n * @param stream - The readable stream to probe\n * @param probeSize - The number of bytes to attempt to read before giving up on the probe\n * @param validator - The Opus Head validator function\n * @experimental\n */\nexport async function demuxProbe(\n\tstream: Readable,\n\tprobeSize = 1_024,\n\tvalidator = validateDiscordOpusHead,\n): Promise {\n\treturn new Promise((resolve, reject) => {\n\t\t// Preconditions\n\t\tif (stream.readableObjectMode) {\n\t\t\treject(new Error('Cannot probe a readable stream in object mode'));\n\t\t\treturn;\n\t\t}\n\n\t\tif (stream.readableEnded) {\n\t\t\treject(new Error('Cannot probe a stream that has ended'));\n\t\t\treturn;\n\t\t}\n\n\t\tlet readBuffer = Buffer.alloc(0);\n\n\t\tlet resolved: StreamType | undefined;\n\n\t\tconst finish = (type: StreamType) => {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\t\tstream.off('data', onData);\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\t\tstream.off('close', onClose);\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\t\tstream.off('end', onClose);\n\t\t\tstream.pause();\n\t\t\tresolved = type;\n\t\t\tif (stream.readableEnded) {\n\t\t\t\tresolve({\n\t\t\t\t\tstream: Readable.from(readBuffer),\n\t\t\t\t\ttype,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (readBuffer.length > 0) {\n\t\t\t\t\tstream.push(readBuffer);\n\t\t\t\t}\n\n\t\t\t\tresolve({\n\t\t\t\t\tstream,\n\t\t\t\t\ttype,\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\n\t\tconst foundHead = (type: StreamType) => (head: Buffer) => {\n\t\t\tif (validator(head)) {\n\t\t\t\tfinish(type);\n\t\t\t}\n\t\t};\n\n\t\tconst webm = new prism.opus.WebmDemuxer();\n\t\twebm.once('error', noop);\n\t\twebm.on('head', foundHead(StreamType.WebmOpus));\n\n\t\tconst ogg = new prism.opus.OggDemuxer();\n\t\togg.once('error', noop);\n\t\togg.on('head', foundHead(StreamType.OggOpus));\n\n\t\tconst onClose = () => {\n\t\t\tif (!resolved) {\n\t\t\t\tfinish(StreamType.Arbitrary);\n\t\t\t}\n\t\t};\n\n\t\tconst onData = (buffer: Buffer) => {\n\t\t\treadBuffer = Buffer.concat([readBuffer, buffer]);\n\n\t\t\twebm.write(buffer);\n\t\t\togg.write(buffer);\n\n\t\t\tif (readBuffer.length >= probeSize) {\n\t\t\t\tstream.off('data', onData);\n\t\t\t\tstream.pause();\n\t\t\t\tprocess.nextTick(onClose);\n\t\t\t}\n\t\t};\n\n\t\tstream.once('error', reject);\n\t\tstream.on('data', onData);\n\t\tstream.once('close', onClose);\n\t\tstream.once('end', onClose);\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,iBAAAA;AAAA;AAAA;;;ACEA,IAAAC,sBAA6B;;;ACF7B,iBAA+B;AAkBxB,SAAS,8BAA8B,QAAoB;AACjE,SAAO;AAAA,IACN,IAAI,0BAAe;AAAA;AAAA,IAEnB,GAAG;AAAA,MACF,UAAU,OAAO;AAAA,MACjB,YAAY,OAAO;AAAA,MACnB,WAAW,OAAO;AAAA,MAClB,WAAW,OAAO;AAAA,IACnB;AAAA,EACD;AACD;AAXgB;AAchB,IAAM,SAAS,oBAAI,IAA0C;AAC7D,OAAO,IAAI,WAAW,oBAAI,IAAI,CAAC;AAE/B,SAAS,iBAAiB,OAAe;AACxC,QAAM,WAAW,OAAO,IAAI,KAAK;AACjC,MAAI;AAAU,WAAO;AACrB,QAAM,MAAM,oBAAI,IAA6B;AAC7C,SAAO,IAAI,OAAO,GAAG;AACrB,SAAO;AACR;AANS;AAcF,SAAS,YAAY;AAC3B,SAAO;AACR;AAFgB;AA0BT,SAAS,oBAA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e;AA0Bf,UAAM,YAAY,wBAAC,SAAqB,CAAC,SAAiB;AACzD,UAAI,UAAU,IAAI,GAAG;AACpB,eAAO,IAAI;AAAA,MACZ;AAAA,IACD,GAJkB;AAMlB,UAAM,OAAO,IAAI,oBAAAC,QAAM,KAAK,YAAY;AACxC,SAAK,KAAK,SAAS,IAAI;AACvB,SAAK,GAAG,QAAQ,oCAA6B,CAAC;AAE9C,UAAM,MAAM,IAAI,oBAAAA,QAAM,KAAK,WAAW;AACtC,QAAI,KAAK,SAAS,IAAI;AACtB,QAAI,GAAG,QAAQ,kCAA4B,CAAC;AAE5C,UAAM,UAAU,6BAAM;AACrB,UAAI,CAAC,UAAU;AACd,0CAA2B;AAAA,MAC5B;AAAA,IACD,GAJgB;AAMhB,UAAM,SAAS,wBAAC,WAAmB;AAClC,mBAAa,2BAAO,OAAO,CAAC,YAAY,MAAM,CAAC;AAE/C,WAAK,MAAM,MAAM;AACjB,UAAI,MAAM,MAAM;AAEhB,UAAI,WAAW,UAAU,WAAW;AACnC,eAAO,IAAI,QAAQ,MAAM;AACzB,eAAO,MAAM;AACb,4BAAAC,QAAQ,SAAS,OAAO;AAAA,MACzB;AAAA,IACD,GAXe;AAaf,WAAO,KAAK,SAAS,MAAM;AAC3B,WAAO,GAAG,QAAQ,MAAM;AACxB,WAAO,KAAK,SAAS,OAAO;AAC5B,WAAO,KAAK,OAAO,OAAO;AAAA,EAC3B,CAAC;AACF;AArFsB;;;ArBhBf,IAAMC,WAAU;","names":["version","import_node_events","import_node_buffer","import_node_events","import_v4","nonce","import_node_buffer","resolve","import_node_events","WebSocket","nonce","option","import_node_buffer","import_v4","import_node_buffer","import_node_events","NoSubscriberBehavior","AudioPlayerStatus","stringifyState","EndBehaviorType","import_node_events","import_node_events","nonce","VoiceConnectionStatus","VoiceConnectionDisconnectReason","import_node_stream","import_prism_media","StreamType","prism","prism","import_prism_media","prism","import_node_events","import_node_buffer","import_node_stream","import_prism_media","resolve","prism","process","version"]} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/dist/index.mjs b/node_modules/@discordjs/voice/dist/index.mjs index a52e4c2..18e580f 100644 --- a/node_modules/@discordjs/voice/dist/index.mjs +++ b/node_modules/@discordjs/voice/dist/index.mjs @@ -1,6 +1,4 @@ -import{createRequire as topLevelCreateRequire}from"module";const require=topLevelCreateRequire(import.meta.url);"use strict"; -var __defProp = Object.defineProperty; -var __getOwnPropNames = Object.getOwnPropertyNames; +import{createRequire as topLevelCreateRequire}from"module";const require=topLevelCreateRequire(import.meta.url);var __defProp = Object.defineProperty; var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; var __name = (target, value) => __defProp(target, "name", { value, configurable: true }); var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { @@ -10,105 +8,11 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require return require.apply(this, arguments); throw new Error('Dynamic require of "' + x + '" is not supported'); }); -var __commonJS = (cb, mod) => function __require2() { - return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; -}; var __publicField = (obj, key, value) => { __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); return value; }; -// package.json -var require_package = __commonJS({ - "package.json"(exports, module) { - module.exports = { - name: "@discordjs/voice", - version: "0.11.0", - description: "Implementation of the Discord Voice API for node.js", - scripts: { - build: "tsup && node scripts/postbuild.mjs", - test: "jest --coverage", - lint: "prettier --check . && eslint src __tests__ --ext mjs,js,ts", - format: "prettier --write . && eslint src __tests__ --ext mjs,js,ts --fix", - docs: "docgen -i src/index.ts -c docs/index.json -o docs/docs.json --typescript && api-extractor run --local", - prepack: "yarn build && yarn lint && yarn test", - changelog: "git cliff --prepend ./CHANGELOG.md -u -c ./cliff.toml -r ../../ --include-path 'packages/voice/*'", - release: "cliff-jumper" - }, - main: "./dist/index.js", - module: "./dist/index.mjs", - typings: "./dist/index.d.ts", - exports: { - import: "./dist/index.mjs", - require: "./dist/index.js", - types: "./dist/index.d.ts" - }, - directories: { - lib: "src", - test: "__tests__" - }, - files: [ - "dist" - ], - contributors: [ - "Crawl ", - "Amish Shah ", - "SpaceEEC ", - "Vlad Frangu ", - "Antonio Roman " - ], - license: "Apache-2.0", - keywords: [ - "discord", - "discord.js", - "audio", - "voice", - "streaming" - ], - repository: { - type: "git", - url: "git+https://github.com/discordjs/discord.js.git" - }, - bugs: { - url: "https://github.com/discordjs/discord.js/issues" - }, - homepage: "https://discord.js.org", - dependencies: { - "@types/ws": "^8.5.3", - "discord-api-types": "^0.36.2", - "prism-media": "^1.3.4", - tslib: "^2.4.0", - ws: "^8.8.1" - }, - devDependencies: { - "@babel/core": "^7.18.6", - "@babel/preset-env": "^7.18.6", - "@babel/preset-typescript": "^7.18.6", - "@discordjs/docgen": "workspace:^", - "@discordjs/scripts": "workspace:^", - "@favware/cliff-jumper": "^1.8.5", - "@microsoft/api-extractor": "^7.28.4", - "@types/jest": "^28.1.6", - "@types/node": "^16.11.45", - eslint: "^8.20.0", - jest: "^28.1.3", - "jest-websocket-mock": "^2.3.0", - "mock-socket": "^9.1.5", - prettier: "^2.7.1", - tsup: "^6.1.3", - tweetnacl: "^1.0.3", - typescript: "^4.7.4" - }, - engines: { - node: ">=16.9.0" - }, - publishConfig: { - access: "public" - } - }; - } -}); - // src/VoiceConnection.ts import { EventEmitter as EventEmitter7 } from "node:events"; @@ -117,6 +21,7 @@ import { GatewayOpcodes } from "discord-api-types/v10"; function createJoinVoiceChannelPayload(config) { return { op: GatewayOpcodes.VoiceStateUpdate, + // eslint-disable-next-line id-length d: { guild_id: config.guildId, channel_id: config.channelId, @@ -166,7 +71,9 @@ function audioCycleStep() { return; nextTime += FRAME_LENGTH; const available = audioPlayers.filter((player) => player.checkPlayable()); - available.forEach((player) => player["_stepDispatch"]()); + for (const player of available) { + player["_stepDispatch"](); + } prepareNextAudioFrame(available); } __name(audioCycleStep, "audioCycleStep"); @@ -204,23 +111,96 @@ function deleteAudioPlayer(player) { audioPlayers.splice(index, 1); if (audioPlayers.length === 0) { nextTime = -1; - if (typeof audioCycleInterval !== "undefined") + if (audioCycleInterval !== void 0) clearTimeout(audioCycleInterval); } } __name(deleteAudioPlayer, "deleteAudioPlayer"); // src/networking/Networking.ts +import { Buffer as Buffer4 } from "node:buffer"; import { EventEmitter as EventEmitter3 } from "node:events"; import { VoiceOpcodes as VoiceOpcodes2 } from "discord-api-types/voice/v4"; +// src/util/Secretbox.ts +import { Buffer as Buffer2 } from "node:buffer"; +var libs = { + "sodium-native": (sodium) => ({ + open: (buffer, nonce2, secretKey) => { + if (buffer) { + const output = Buffer2.allocUnsafe(buffer.length - sodium.crypto_box_MACBYTES); + if (sodium.crypto_secretbox_open_easy(output, buffer, nonce2, secretKey)) + return output; + } + return null; + }, + close: (opusPacket, nonce2, secretKey) => { + const output = Buffer2.allocUnsafe(opusPacket.length + sodium.crypto_box_MACBYTES); + sodium.crypto_secretbox_easy(output, opusPacket, nonce2, secretKey); + return output; + }, + random: (num, buffer = Buffer2.allocUnsafe(num)) => { + sodium.randombytes_buf(buffer); + return buffer; + } + }), + sodium: (sodium) => ({ + open: sodium.api.crypto_secretbox_open_easy, + close: sodium.api.crypto_secretbox_easy, + random: (num, buffer = Buffer2.allocUnsafe(num)) => { + sodium.api.randombytes_buf(buffer); + return buffer; + } + }), + "libsodium-wrappers": (sodium) => ({ + open: sodium.crypto_secretbox_open_easy, + close: sodium.crypto_secretbox_easy, + random: sodium.randombytes_buf + }), + tweetnacl: (tweetnacl) => ({ + open: tweetnacl.secretbox.open, + close: tweetnacl.secretbox, + random: tweetnacl.randomBytes + }) +}; +var fallbackError = /* @__PURE__ */ __name(() => { + throw new Error( + `Cannot play audio as no valid encryption package is installed. +- Install sodium, libsodium-wrappers, or tweetnacl. +- Use the generateDependencyReport() function for more information. +` + ); +}, "fallbackError"); +var methods = { + open: fallbackError, + close: fallbackError, + random: fallbackError +}; +void (async () => { + for (const libName of Object.keys(libs)) { + try { + const lib = __require(libName); + if (libName === "libsodium-wrappers" && lib.ready) + await lib.ready; + Object.assign(methods, libs[libName](lib)); + break; + } catch { + } + } +})(); + +// src/util/util.ts +var noop = /* @__PURE__ */ __name(() => { +}, "noop"); + // src/networking/VoiceUDPSocket.ts +import { Buffer as Buffer3 } from "node:buffer"; import { createSocket } from "node:dgram"; import { EventEmitter } from "node:events"; import { isIPv4 } from "node:net"; function parseLocalPacket(message) { - const packet = Buffer.from(message); - const ip = packet.slice(8, packet.indexOf(0, 8)).toString("utf-8"); + const packet = Buffer3.from(message); + const ip = packet.slice(8, packet.indexOf(0, 8)).toString("utf8"); if (!isIPv4(ip)) { throw new Error("Malformed IP address"); } @@ -229,61 +209,80 @@ function parseLocalPacket(message) { } __name(parseLocalPacket, "parseLocalPacket"); var KEEP_ALIVE_INTERVAL = 5e3; -var KEEP_ALIVE_LIMIT = 12; var MAX_COUNTER_VALUE = 2 ** 32 - 1; var VoiceUDPSocket = class extends EventEmitter { - constructor(remote, debug = false) { + /** + * The underlying network Socket for the VoiceUDPSocket. + */ + socket; + /** + * The socket details for Discord (remote) + */ + remote; + /** + * The counter used in the keep alive mechanism. + */ + keepAliveCounter = 0; + /** + * The buffer used to write the keep alive counter into. + */ + keepAliveBuffer; + /** + * The Node.js interval for the keep-alive mechanism. + */ + keepAliveInterval; + /** + * The time taken to receive a response to keep alive messages. + * + * @deprecated This field is no longer updated as keep alive messages are no longer tracked. + */ + ping; + /** + * Creates a new VoiceUDPSocket. + * + * @param remote - Details of the remote socket + */ + constructor(remote) { super(); - __publicField(this, "socket"); - __publicField(this, "remote"); - __publicField(this, "keepAlives"); - __publicField(this, "keepAliveCounter", 0); - __publicField(this, "keepAliveBuffer"); - __publicField(this, "keepAliveInterval"); - __publicField(this, "ping"); - __publicField(this, "debug"); this.socket = createSocket("udp4"); this.socket.on("error", (error) => this.emit("error", error)); this.socket.on("message", (buffer) => this.onMessage(buffer)); this.socket.on("close", () => this.emit("close")); this.remote = remote; - this.keepAlives = []; - this.keepAliveBuffer = Buffer.alloc(8); + this.keepAliveBuffer = Buffer3.alloc(8); this.keepAliveInterval = setInterval(() => this.keepAlive(), KEEP_ALIVE_INTERVAL); setImmediate(() => this.keepAlive()); - this.debug = debug ? (message) => this.emit("debug", message) : null; } + /** + * Called when a message is received on the UDP socket. + * + * @param buffer - The received buffer + */ onMessage(buffer) { - if (buffer.length === 8) { - const counter = buffer.readUInt32LE(0); - const index = this.keepAlives.findIndex(({ value }) => value === counter); - if (index === -1) - return; - this.ping = Date.now() - this.keepAlives[index].timestamp; - this.keepAlives.splice(0, index); - } this.emit("message", buffer); } + /** + * Called at a regular interval to check whether we are still able to send datagrams to Discord. + */ keepAlive() { - if (this.keepAlives.length >= KEEP_ALIVE_LIMIT) { - this.debug?.("UDP socket has not received enough responses from Discord - closing socket"); - this.destroy(); - return; - } this.keepAliveBuffer.writeUInt32LE(this.keepAliveCounter, 0); this.send(this.keepAliveBuffer); - this.keepAlives.push({ - value: this.keepAliveCounter, - timestamp: Date.now() - }); this.keepAliveCounter++; if (this.keepAliveCounter > MAX_COUNTER_VALUE) { this.keepAliveCounter = 0; } } + /** + * Sends a buffer to Discord. + * + * @param buffer - The buffer to send + */ send(buffer) { - return this.socket.send(buffer, this.remote.port, this.remote.ip); + this.socket.send(buffer, this.remote.port, this.remote.ip); } + /** + * Closes the socket, the instance will not be able to be reused. + */ destroy() { try { this.socket.close(); @@ -291,7 +290,12 @@ var VoiceUDPSocket = class extends EventEmitter { } clearInterval(this.keepAliveInterval); } - performIPDiscovery(ssrc) { + /** + * Performs IP discovery to discover the local address and port to be used for the voice connection. + * + * @param ssrc - The SSRC received from Discord + */ + async performIPDiscovery(ssrc) { return new Promise((resolve2, reject) => { const listener = /* @__PURE__ */ __name((message) => { try { @@ -305,7 +309,7 @@ var VoiceUDPSocket = class extends EventEmitter { }, "listener"); this.socket.on("message", listener); this.socket.once("close", () => reject(new Error("Cannot perform IP discovery - socket closed"))); - const discoveryBuffer = Buffer.alloc(74); + const discoveryBuffer = Buffer3.alloc(74); discoveryBuffer.writeUInt16BE(1, 0); discoveryBuffer.writeUInt16BE(70, 2); discoveryBuffer.writeUInt32BE(ssrc, 4); @@ -320,34 +324,71 @@ import { EventEmitter as EventEmitter2 } from "node:events"; import { VoiceOpcodes } from "discord-api-types/voice/v4"; import WebSocket from "ws"; var VoiceWebSocket = class extends EventEmitter2 { + /** + * The current heartbeat interval, if any. + */ + heartbeatInterval; + /** + * The time (milliseconds since UNIX epoch) that the last heartbeat acknowledgement packet was received. + * This is set to 0 if an acknowledgement packet hasn't been received yet. + */ + lastHeartbeatAck; + /** + * The time (milliseconds since UNIX epoch) that the last heartbeat was sent. This is set to 0 if a heartbeat + * hasn't been sent yet. + */ + lastHeartbeatSend; + /** + * The number of consecutively missed heartbeats. + */ + missedHeartbeats = 0; + /** + * The last recorded ping. + */ + ping; + /** + * The debug logger function, if debugging is enabled. + */ + debug; + /** + * The underlying WebSocket of this wrapper. + */ + ws; + /** + * Creates a new VoiceWebSocket. + * + * @param address - The address to connect to + */ constructor(address, debug) { super(); - __publicField(this, "heartbeatInterval"); - __publicField(this, "lastHeartbeatAck"); - __publicField(this, "lastHeartbeatSend"); - __publicField(this, "missedHeartbeats", 0); - __publicField(this, "ping"); - __publicField(this, "debug"); - __publicField(this, "ws"); this.ws = new WebSocket(address); - this.ws.onmessage = (e) => this.onMessage(e); - this.ws.onopen = (e) => this.emit("open", e); - this.ws.onerror = (e) => this.emit("error", e instanceof Error ? e : e.error); - this.ws.onclose = (e) => this.emit("close", e); + this.ws.onmessage = (err) => this.onMessage(err); + this.ws.onopen = (err) => this.emit("open", err); + this.ws.onerror = (err) => this.emit("error", err instanceof Error ? err : err.error); + this.ws.onclose = (err) => this.emit("close", err); this.lastHeartbeatAck = 0; this.lastHeartbeatSend = 0; this.debug = debug ? (message) => this.emit("debug", message) : null; } + /** + * Destroys the VoiceWebSocket. The heartbeat interval is cleared, and the connection is closed. + */ destroy() { try { this.debug?.("destroyed"); this.setHeartbeatInterval(-1); this.ws.close(1e3); } catch (error) { - const e = error; - this.emit("error", e); + const err = error; + this.emit("error", err); } } + /** + * Handles message events on the WebSocket. Attempts to JSON parse the messages and emit them + * as packets. + * + * @param event - The message event + */ onMessage(event) { if (typeof event.data !== "string") return; @@ -356,8 +397,8 @@ var VoiceWebSocket = class extends EventEmitter2 { try { packet = JSON.parse(event.data); } catch (error) { - const e = error; - this.emit("error", e); + const err = error; + this.emit("error", err); return; } if (packet.op === VoiceOpcodes.HeartbeatAck) { @@ -367,27 +408,42 @@ var VoiceWebSocket = class extends EventEmitter2 { } this.emit("packet", packet); } + /** + * Sends a JSON-stringifiable packet over the WebSocket. + * + * @param packet - The packet to send + */ sendPacket(packet) { try { const stringified = JSON.stringify(packet); this.debug?.(`>> ${stringified}`); - return this.ws.send(stringified); + this.ws.send(stringified); + return; } catch (error) { - const e = error; - this.emit("error", e); + const err = error; + this.emit("error", err); } } + /** + * Sends a heartbeat over the WebSocket. + */ sendHeartbeat() { this.lastHeartbeatSend = Date.now(); this.missedHeartbeats++; const nonce2 = this.lastHeartbeatSend; - return this.sendPacket({ + this.sendPacket({ op: VoiceOpcodes.Heartbeat, + // eslint-disable-next-line id-length d: nonce2 }); } + /** + * Sets/clears an interval to send heartbeats over the WebSocket. + * + * @param ms - The interval in milliseconds. If negative, the interval will be unset + */ setHeartbeatInterval(ms) { - if (typeof this.heartbeatInterval !== "undefined") + if (this.heartbeatInterval !== void 0) clearInterval(this.heartbeatInterval); if (ms > 0) { this.heartbeatInterval = setInterval(() => { @@ -402,80 +458,12 @@ var VoiceWebSocket = class extends EventEmitter2 { }; __name(VoiceWebSocket, "VoiceWebSocket"); -// src/util/Secretbox.ts -var libs = { - "sodium-native": (sodium) => ({ - open: (buffer, nonce2, secretKey) => { - if (buffer) { - const output = Buffer.allocUnsafe(buffer.length - sodium.crypto_box_MACBYTES); - if (sodium.crypto_secretbox_open_easy(output, buffer, nonce2, secretKey)) - return output; - } - return null; - }, - close: (opusPacket, nonce2, secretKey) => { - const output = Buffer.allocUnsafe(opusPacket.length + sodium.crypto_box_MACBYTES); - sodium.crypto_secretbox_easy(output, opusPacket, nonce2, secretKey); - return output; - }, - random: (n, buffer = Buffer.allocUnsafe(n)) => { - sodium.randombytes_buf(buffer); - return buffer; - } - }), - sodium: (sodium) => ({ - open: sodium.api.crypto_secretbox_open_easy, - close: sodium.api.crypto_secretbox_easy, - random: (n, buffer = Buffer.allocUnsafe(n)) => { - sodium.api.randombytes_buf(buffer); - return buffer; - } - }), - "libsodium-wrappers": (sodium) => ({ - open: sodium.crypto_secretbox_open_easy, - close: sodium.crypto_secretbox_easy, - random: sodium.randombytes_buf - }), - tweetnacl: (tweetnacl) => ({ - open: tweetnacl.secretbox.open, - close: tweetnacl.secretbox, - random: tweetnacl.randomBytes - }) -}; -var fallbackError = /* @__PURE__ */ __name(() => { - throw new Error(`Cannot play audio as no valid encryption package is installed. -- Install sodium, libsodium-wrappers, or tweetnacl. -- Use the generateDependencyReport() function for more information. -`); -}, "fallbackError"); -var methods = { - open: fallbackError, - close: fallbackError, - random: fallbackError -}; -void (async () => { - for (const libName of Object.keys(libs)) { - try { - const lib = __require(libName); - if (libName === "libsodium-wrappers" && lib.ready) - await lib.ready; - Object.assign(methods, libs[libName](lib)); - break; - } catch { - } - } -})(); - -// src/util/util.ts -var noop = /* @__PURE__ */ __name(() => { -}, "noop"); - // src/networking/Networking.ts var CHANNELS = 2; var TIMESTAMP_INC = 48e3 / 100 * CHANNELS; var MAX_NONCE_SIZE = 2 ** 32 - 1; var SUPPORTED_ENCRYPTION_MODES = ["xsalsa20_poly1305_lite", "xsalsa20_poly1305_suffix", "xsalsa20_poly1305"]; -var nonce = Buffer.alloc(24); +var nonce = Buffer4.alloc(24); function stringifyState(state) { return JSON.stringify({ ...state, @@ -492,15 +480,21 @@ function chooseEncryptionMode(options) { return option; } __name(chooseEncryptionMode, "chooseEncryptionMode"); -function randomNBit(n) { - return Math.floor(Math.random() * 2 ** n); +function randomNBit(numberOfBits) { + return Math.floor(Math.random() * 2 ** numberOfBits); } __name(randomNBit, "randomNBit"); var Networking = class extends EventEmitter3 { + _state; + /** + * The debug logger function, if debugging is enabled. + */ + debug; + /** + * Creates a new Networking instance. + */ constructor(options, debug) { super(); - __publicField(this, "_state"); - __publicField(this, "debug"); this.onWsOpen = this.onWsOpen.bind(this); this.onChildError = this.onChildError.bind(this); this.onWsPacket = this.onWsPacket.bind(this); @@ -515,14 +509,23 @@ var Networking = class extends EventEmitter3 { connectionOptions: options }; } + /** + * Destroys the Networking instance, transitioning it into the Closed state. + */ destroy() { this.state = { code: 6 /* Closed */ }; } + /** + * The current state of the networking instance. + */ get state() { return this._state; } + /** + * Sets a new state for the networking instance, performing clean-up operations where necessary. + */ set state(newState) { const oldWs = Reflect.get(this._state, "ws"); const newWs = Reflect.get(newState, "ws"); @@ -551,6 +554,11 @@ var Networking = class extends EventEmitter3 { from ${stringifyState(oldState)} to ${stringifyState(newState)}`); } + /** + * Creates a new WebSocket to a Discord Voice gateway. + * + * @param endpoint - The endpoint to connect to + */ createWebSocket(endpoint) { const ws = new VoiceWebSocket(`wss://${endpoint}?v=4`, Boolean(this.debug)); ws.on("error", this.onChildError); @@ -560,9 +568,18 @@ to ${stringifyState(newState)}`); ws.on("debug", this.onWsDebug); return ws; } + /** + * Propagates errors from the children VoiceWebSocket and VoiceUDPSocket. + * + * @param error - The error that was emitted by a child + */ onChildError(error) { this.emit("error", error); } + /** + * Called when the WebSocket opens. Depending on the state that the instance is in, + * it will either identify with a new session, or it will attempt to resume an existing session. + */ onWsOpen() { if (this.state.code === 0 /* OpeningWs */) { const packet = { @@ -591,6 +608,13 @@ to ${stringifyState(newState)}`); this.state.ws.sendPacket(packet); } } + /** + * Called when the WebSocket closes. Based on the reason for closing (given by the code parameter), + * the instance will either attempt to resume, or enter the closed state and emit a 'close' event + * with the close code, allowing the user to decide whether or not they would like to reconnect. + * + * @param code - The close code + */ onWsClose({ code }) { const canResume = code === 4015 || code < 4e3; if (canResume && this.state.code === 4 /* Ready */) { @@ -604,6 +628,9 @@ to ${stringifyState(newState)}`); this.emit("close", code); } } + /** + * Called when the UDP socket has closed itself if it has stopped receiving replies from Discord. + */ onUdpClose() { if (this.state.code === 4 /* Ready */) { this.state = { @@ -613,6 +640,11 @@ to ${stringifyState(newState)}`); }; } } + /** + * Called when a packet is received on the connection's WebSocket. + * + * @param packet - The received packet + */ onWsPacket(packet) { if (packet.op === VoiceOpcodes2.Hello && this.state.code !== 6 /* Closed */) { this.state.ws.setHeartbeatInterval(packet.d.heartbeat_interval); @@ -661,7 +693,7 @@ to ${stringifyState(newState)}`); sequence: randomNBit(16), timestamp: randomNBit(32), nonce: 0, - nonceBuffer: Buffer.alloc(24), + nonceBuffer: Buffer4.alloc(24), speaking: false, packetsPlayed: 0 } @@ -674,12 +706,32 @@ to ${stringifyState(newState)}`); this.state.connectionData.speaking = false; } } + /** + * Propagates debug messages from the child WebSocket. + * + * @param message - The emitted debug message + */ onWsDebug(message) { this.debug?.(`[WS] ${message}`); } + /** + * Propagates debug messages from the child UDPSocket. + * + * @param message - The emitted debug message + */ onUdpDebug(message) { this.debug?.(`[UDP] ${message}`); } + /** + * Prepares an Opus packet for playback. This includes attaching metadata to it and encrypting it. + * It will be stored within the instance, and can be played by dispatchAudio() + * + * @remarks + * Calling this method while there is already a prepared audio packet that has not yet been dispatched + * will overwrite the existing audio packet. This should be avoided. + * @param opusPacket - The Opus packet to encrypt + * @returns The audio packet that was prepared + */ prepareAudioPacket(opusPacket) { const state = this.state; if (state.code !== 4 /* Ready */) @@ -687,17 +739,26 @@ to ${stringifyState(newState)}`); state.preparedPacket = this.createAudioPacket(opusPacket, state.connectionData); return state.preparedPacket; } + /** + * Dispatches the audio packet previously prepared by prepareAudioPacket(opusPacket). The audio packet + * is consumed and cannot be dispatched again. + */ dispatchAudio() { const state = this.state; if (state.code !== 4 /* Ready */) return false; - if (typeof state.preparedPacket !== "undefined") { + if (state.preparedPacket !== void 0) { this.playAudioPacket(state.preparedPacket); state.preparedPacket = void 0; return true; } return false; } + /** + * Plays an audio packet, updating timing metadata used for playback. + * + * @param audioPacket - The audio packet to play + */ playAudioPacket(audioPacket) { const state = this.state; if (state.code !== 4 /* Ready */) @@ -713,6 +774,12 @@ to ${stringifyState(newState)}`); this.setSpeaking(true); state.udp.send(audioPacket); } + /** + * Sends a packet to the voice gateway indicating that the client has start/stopped sending + * audio. + * + * @param speaking - Whether or not the client should be shown as speaking + */ setSpeaking(speaking) { const state = this.state; if (state.code !== 4 /* Ready */) @@ -729,8 +796,15 @@ to ${stringifyState(newState)}`); } }); } + /** + * Creates a new audio packet from an Opus packet. This involves encrypting the packet, + * then prepending a header that includes metadata. + * + * @param opusPacket - The Opus packet to prepare + * @param connectionData - The current connection data of the instance + */ createAudioPacket(opusPacket, connectionData) { - const packetBuffer = Buffer.alloc(12); + const packetBuffer = Buffer4.alloc(12); packetBuffer[0] = 128; packetBuffer[1] = 120; const { sequence, timestamp, ssrc } = connectionData; @@ -738,8 +812,14 @@ to ${stringifyState(newState)}`); packetBuffer.writeUIntBE(timestamp, 4, 4); packetBuffer.writeUIntBE(ssrc, 8, 4); packetBuffer.copy(nonce, 0, 0, 12); - return Buffer.concat([packetBuffer, ...this.encryptOpusPacket(opusPacket, connectionData)]); - } + return Buffer4.concat([packetBuffer, ...this.encryptOpusPacket(opusPacket, connectionData)]); + } + /** + * Encrypts an Opus packet using the format agreed upon by the instance and Discord. + * + * @param opusPacket - The Opus packet to encrypt + * @param connectionData - The current connection data of the instance + */ encryptOpusPacket(opusPacket, connectionData) { const { secretKey, encryptionMode } = connectionData; if (encryptionMode === "xsalsa20_poly1305_lite") { @@ -761,19 +841,24 @@ to ${stringifyState(newState)}`); __name(Networking, "Networking"); // src/receive/VoiceReceiver.ts +import { Buffer as Buffer6 } from "node:buffer"; import { VoiceOpcodes as VoiceOpcodes3 } from "discord-api-types/voice/v4"; // src/receive/AudioReceiveStream.ts import { Readable } from "node:stream"; // src/audio/AudioPlayer.ts -import EventEmitter4 from "node:events"; +import { Buffer as Buffer5 } from "node:buffer"; +import { EventEmitter as EventEmitter4 } from "node:events"; // src/audio/AudioPlayerError.ts var AudioPlayerError = class extends Error { + /** + * The resource associated with the audio player at the time the error was thrown. + */ + resource; constructor(error, resource) { super(error.message); - __publicField(this, "resource"); this.resource = resource; this.name = error.name; this.stack = error.stack; @@ -783,12 +868,22 @@ __name(AudioPlayerError, "AudioPlayerError"); // src/audio/PlayerSubscription.ts var PlayerSubscription = class { + /** + * The voice connection of this subscription. + */ + connection; + /** + * The audio player of this subscription. + */ + player; constructor(connection, player) { - __publicField(this, "connection"); - __publicField(this, "player"); this.connection = connection; this.player = player; } + /** + * Unsubscribes the connection from the audio player, meaning that the + * audio player cannot stream audio to it until a new subscription is made. + */ unsubscribe() { this.connection["onSubscriptionRemoved"](this); this.player["unsubscribe"](this); @@ -797,7 +892,7 @@ var PlayerSubscription = class { __name(PlayerSubscription, "PlayerSubscription"); // src/audio/AudioPlayer.ts -var SILENCE_FRAME = Buffer.from([248, 255, 254]); +var SILENCE_FRAME = Buffer5.from([248, 255, 254]); var NoSubscriberBehavior = /* @__PURE__ */ ((NoSubscriberBehavior2) => { NoSubscriberBehavior2["Pause"] = "pause"; NoSubscriberBehavior2["Play"] = "play"; @@ -805,11 +900,11 @@ var NoSubscriberBehavior = /* @__PURE__ */ ((NoSubscriberBehavior2) => { return NoSubscriberBehavior2; })(NoSubscriberBehavior || {}); var AudioPlayerStatus = /* @__PURE__ */ ((AudioPlayerStatus2) => { - AudioPlayerStatus2["Idle"] = "idle"; + AudioPlayerStatus2["AutoPaused"] = "autopaused"; AudioPlayerStatus2["Buffering"] = "buffering"; + AudioPlayerStatus2["Idle"] = "idle"; AudioPlayerStatus2["Paused"] = "paused"; AudioPlayerStatus2["Playing"] = "playing"; - AudioPlayerStatus2["AutoPaused"] = "autopaused"; return AudioPlayerStatus2; })(AudioPlayerStatus || {}); function stringifyState2(state) { @@ -821,12 +916,28 @@ function stringifyState2(state) { } __name(stringifyState2, "stringifyState"); var AudioPlayer = class extends EventEmitter4 { + /** + * The state that the AudioPlayer is in. + */ + _state; + /** + * A list of VoiceConnections that are registered to this AudioPlayer. The player will attempt to play audio + * to the streams in this list. + */ + subscribers = []; + /** + * The behavior that the player should follow when it enters certain situations. + */ + behaviors; + /** + * The debug logger function, if debugging is enabled. + */ + debug; + /** + * Creates a new AudioPlayer. + */ constructor(options = {}) { super(); - __publicField(this, "_state"); - __publicField(this, "subscribers", []); - __publicField(this, "behaviors"); - __publicField(this, "debug"); this._state = { status: "idle" /* Idle */ }; this.behaviors = { noSubscriber: "pause" /* Pause */, @@ -835,9 +946,22 @@ var AudioPlayer = class extends EventEmitter4 { }; this.debug = options.debug === false ? null : (message) => this.emit("debug", message); } + /** + * A list of subscribed voice connections that can currently receive audio to play. + */ get playable() { return this.subscribers.filter(({ connection }) => connection.state.status === "ready" /* Ready */).map(({ connection }) => connection); } + /** + * Subscribes a VoiceConnection to the audio player's play list. If the VoiceConnection is already subscribed, + * then the existing subscription is used. + * + * @remarks + * This method should not be directly called. Instead, use VoiceConnection#subscribe. + * @param connection - The connection to subscribe + * @returns The new subscription if the voice connection is not yet subscribed, otherwise the existing subscription + */ + // @ts-ignore subscribe(connection) { const existingSubscription = this.subscribers.find((subscription) => subscription.connection === connection); if (!existingSubscription) { @@ -848,6 +972,15 @@ var AudioPlayer = class extends EventEmitter4 { } return existingSubscription; } + /** + * Unsubscribes a subscription - i.e. removes a voice connection from the play list of the audio player. + * + * @remarks + * This method should not be directly called. Instead, use PlayerSubscription#unsubscribe. + * @param subscription - The subscription to remove + * @returns Whether or not the subscription existed on the player and was removed + */ + // @ts-ignore unsubscribe(subscription) { const index = this.subscribers.indexOf(subscription); const exists = index !== -1; @@ -858,9 +991,15 @@ var AudioPlayer = class extends EventEmitter4 { } return exists; } + /** + * The state that the player is in. + */ get state() { return this._state; } + /** + * Sets a new state for the player, performing clean-up operations where necessary. + */ set state(newState) { const oldState = this._state; const newResource = Reflect.get(newState, "resource"); @@ -894,6 +1033,19 @@ var AudioPlayer = class extends EventEmitter4 { from ${stringifyState2(oldState)} to ${stringifyState2(newState)}`); } + /** + * Plays a new resource on the player. If the player is already playing a resource, the existing resource is destroyed + * (it cannot be reused, even in another player) and is replaced with the new resource. + * + * @remarks + * The player will transition to the Playing state once playback begins, and will return to the Idle state once + * playback is ended. + * + * If the player was previously playing a resource and this method is called, the player will not transition to the + * Idle state during the swap over. + * @param resource - The resource to play + * @throws Will throw if attempting to play an audio resource that has already ended, or is being played by another player + */ play(resource) { if (resource.ended) { throw new Error("Cannot play a resource that has already ended."); @@ -956,6 +1108,12 @@ to ${stringifyState2(newState)}`); }; } } + /** + * Pauses playback of the current resource, if any. + * + * @param interpolateSilence - If true, the player will play 5 packets of silence after pausing to prevent audio glitches + * @returns `true` if the player was successfully paused, otherwise `false` + */ pause(interpolateSilence = true) { if (this.state.status !== "playing" /* Playing */) return false; @@ -966,6 +1124,11 @@ to ${stringifyState2(newState)}`); }; return true; } + /** + * Unpauses playback of the current resource, if any. + * + * @returns `true` if the player was successfully unpaused, otherwise `false` + */ unpause() { if (this.state.status !== "paused" /* Paused */) return false; @@ -976,6 +1139,13 @@ to ${stringifyState2(newState)}`); }; return true; } + /** + * Stops playback of the current resource and destroys the resource. The player will either transition to the Idle state, + * or remain in its current state until the silence padding frames of the resource have been played. + * + * @param force - If true, will force the player to enter the Idle state even if the resource has silence padding frames + * @returns `true` if the player will come to a stop, otherwise `false` + */ stop(force = false) { if (this.state.status === "idle" /* Idle */) return false; @@ -988,6 +1158,11 @@ to ${stringifyState2(newState)}`); } return true; } + /** + * Checks whether the underlying resource (if any) is playable (readable) + * + * @returns `true` if the resource is playable, otherwise `false` + */ checkPlayable() { const state = this._state; if (state.status === "idle" /* Idle */ || state.status === "buffering" /* Buffering */) @@ -1000,12 +1175,25 @@ to ${stringifyState2(newState)}`); } return true; } + /** + * Called roughly every 20ms by the global audio player timer. Dispatches any audio packets that are buffered + * by the active connections of this audio player. + */ + // @ts-ignore _stepDispatch() { const state = this._state; if (state.status === "idle" /* Idle */ || state.status === "buffering" /* Buffering */) return; - this.playable.forEach((connection) => connection.dispatchAudio()); + for (const connection of this.playable) { + connection.dispatchAudio(); + } } + /** + * Called roughly every 20ms by the global audio player timer. Attempts to read an audio packet from the + * underlying resource of the stream, and then has all the active connections of the audio player prepare it + * (encrypt it, append header data) so that it is ready to play at the start of the next cycle. + */ + // @ts-ignore _stepPrepare() { const state = this._state; if (state.status === "idle" /* Idle */ || state.status === "buffering" /* Buffering */) @@ -1054,12 +1242,27 @@ to ${stringifyState2(newState)}`); } } } + /** + * Signals to all the subscribed connections that they should send a packet to Discord indicating + * they are no longer speaking. Called once playback of a resource ends. + */ _signalStopSpeaking() { - return this.subscribers.forEach(({ connection }) => connection.setSpeaking(false)); + for (const { connection } of this.subscribers) { + connection.setSpeaking(false); + } } + /** + * Instructs the given connections to each prepare this packet to be played at the start of the + * next cycle. + * + * @param packet - The Opus packet to be prepared by each receiver + * @param receivers - The connections that should play this packet + */ _preparePacket(packet, receivers, state) { state.playbackDuration += 20; - receivers.forEach((connection) => connection.prepareAudioPacket(packet)); + for (const connection of receivers) { + connection.prepareAudioPacket(packet); + } } }; __name(AudioPlayer, "AudioPlayer"); @@ -1084,20 +1287,21 @@ function createDefaultAudioReceiveStreamOptions() { } __name(createDefaultAudioReceiveStreamOptions, "createDefaultAudioReceiveStreamOptions"); var AudioReceiveStream = class extends Readable { + /** + * The end behavior of the receive stream. + */ + end; + endTimeout; constructor({ end, ...options }) { super({ ...options, objectMode: true }); - __publicField(this, "end"); - __publicField(this, "endTimeout"); this.end = end; } push(buffer) { - if (buffer) { - if (this.end.behavior === 2 /* AfterInactivity */ || this.end.behavior === 1 /* AfterSilence */ && (buffer.compare(SILENCE_FRAME) !== 0 || typeof this.endTimeout === "undefined")) { - this.renewEndTimeout(this.end); - } + if (buffer && (this.end.behavior === 2 /* AfterInactivity */ || this.end.behavior === 1 /* AfterSilence */ && (buffer.compare(SILENCE_FRAME) !== 0 || this.endTimeout === void 0))) { + this.renewEndTimeout(this.end); } return super.push(buffer); } @@ -1115,11 +1319,19 @@ __name(AudioReceiveStream, "AudioReceiveStream"); // src/receive/SSRCMap.ts import { EventEmitter as EventEmitter5 } from "node:events"; var SSRCMap = class extends EventEmitter5 { + /** + * The underlying map. + */ + map; constructor() { super(); - __publicField(this, "map"); this.map = /* @__PURE__ */ new Map(); } + /** + * Updates the map with new user data + * + * @param data - The data to update with + */ update(data) { const existing = this.map.get(data.audioSSRC); const newValue = { @@ -1131,6 +1343,11 @@ var SSRCMap = class extends EventEmitter5 { this.emit("create", newValue); this.emit("update", existing, newValue); } + /** + * Gets the stored voice data of a user. + * + * @param target - The target, either their user id or audio SSRC + */ get(target) { if (typeof target === "number") { return this.map.get(target); @@ -1142,6 +1359,12 @@ var SSRCMap = class extends EventEmitter5 { } return void 0; } + /** + * Deletes the stored voice data about a user. + * + * @param target - The target of the delete operation, either their audio SSRC or user id + * @returns The data that was deleted, if any + */ delete(target) { if (typeof target === "number") { const existing = this.map.get(target); @@ -1166,10 +1389,13 @@ __name(SSRCMap, "SSRCMap"); // src/receive/SpeakingMap.ts import { EventEmitter as EventEmitter6 } from "node:events"; var _SpeakingMap = class extends EventEmitter6 { + /** + * The currently speaking users, mapped to the milliseconds since UNIX epoch at which they started speaking. + */ + users; + speakingTimeouts; constructor() { super(); - __publicField(this, "users"); - __publicField(this, "speakingTimeouts"); this.users = /* @__PURE__ */ new Map(); this.speakingTimeouts = /* @__PURE__ */ new Map(); } @@ -1184,25 +1410,48 @@ var _SpeakingMap = class extends EventEmitter6 { this.startTimeout(userId); } startTimeout(userId) { - this.speakingTimeouts.set(userId, setTimeout(() => { - this.emit("end", userId); - this.speakingTimeouts.delete(userId); - this.users.delete(userId); - }, _SpeakingMap.DELAY)); + this.speakingTimeouts.set( + userId, + setTimeout(() => { + this.emit("end", userId); + this.speakingTimeouts.delete(userId); + this.users.delete(userId); + }, _SpeakingMap.DELAY) + ); } }; var SpeakingMap = _SpeakingMap; __name(SpeakingMap, "SpeakingMap"); +/** + * The delay after a packet is received from a user until they're marked as not speaking anymore. + */ __publicField(SpeakingMap, "DELAY", 100); // src/receive/VoiceReceiver.ts var VoiceReceiver = class { + /** + * The attached connection of this receiver. + */ + voiceConnection; + /** + * Maps SSRCs to Discord user ids. + */ + ssrcMap; + /** + * The current audio subscriptions of this receiver. + */ + subscriptions; + /** + * The connection data of the receiver. + * + * @internal + */ + connectionData; + /** + * The speaking map of the receiver. + */ + speaking; constructor(voiceConnection) { - __publicField(this, "voiceConnection"); - __publicField(this, "ssrcMap"); - __publicField(this, "subscriptions"); - __publicField(this, "connectionData"); - __publicField(this, "speaking"); this.voiceConnection = voiceConnection; this.ssrcMap = new SSRCMap(); this.speaking = new SpeakingMap(); @@ -1211,6 +1460,12 @@ var VoiceReceiver = class { this.onWsPacket = this.onWsPacket.bind(this); this.onUdpMessage = this.onUdpMessage.bind(this); } + /** + * Called when a packet is received on the attached connection's WebSocket. + * + * @param packet - The received packet + * @internal + */ onWsPacket(packet) { if (packet.op === VoiceOpcodes3.ClientDisconnect && typeof packet.d?.user_id === "string") { this.ssrcMap.delete(packet.d.user_id); @@ -1238,8 +1493,17 @@ var VoiceReceiver = class { const decrypted = methods.open(buffer.slice(12, end), nonce2, secretKey); if (!decrypted) return; - return Buffer.from(decrypted); - } + return Buffer6.from(decrypted); + } + /** + * Parses an audio packet, decrypting it to yield an Opus packet. + * + * @param buffer - The buffer to parse + * @param mode - The encryption mode + * @param nonce - The nonce buffer used by the connection for encryption + * @param secretKey - The secret key used by the connection for encryption + * @returns The parsed Opus packet + */ parsePacket(buffer, mode, nonce2, secretKey) { let packet = this.decrypt(buffer, mode, nonce2, secretKey); if (!packet) @@ -1250,6 +1514,12 @@ var VoiceReceiver = class { } return packet; } + /** + * Called when the UDP socket of the attached connection receives a message. + * + * @param msg - The received message + * @internal + */ onUdpMessage(msg) { if (msg.length <= 8) return; @@ -1262,7 +1532,12 @@ var VoiceReceiver = class { if (!stream) return; if (this.connectionData.encryptionMode && this.connectionData.nonceBuffer && this.connectionData.secretKey) { - const packet = this.parsePacket(msg, this.connectionData.encryptionMode, this.connectionData.nonceBuffer, this.connectionData.secretKey); + const packet = this.parsePacket( + msg, + this.connectionData.encryptionMode, + this.connectionData.nonceBuffer, + this.connectionData.secretKey + ); if (packet) { stream.push(packet); } else { @@ -1270,6 +1545,12 @@ var VoiceReceiver = class { } } } + /** + * Creates a subscription for the given user id. + * + * @param target - The id of the user to subscribe to + * @returns A readable stream of Opus packets received from the target + */ subscribe(userId, options) { const existing = this.subscriptions.get(userId); if (existing) @@ -1287,11 +1568,11 @@ __name(VoiceReceiver, "VoiceReceiver"); // src/VoiceConnection.ts var VoiceConnectionStatus = /* @__PURE__ */ ((VoiceConnectionStatus2) => { - VoiceConnectionStatus2["Signalling"] = "signalling"; VoiceConnectionStatus2["Connecting"] = "connecting"; - VoiceConnectionStatus2["Ready"] = "ready"; - VoiceConnectionStatus2["Disconnected"] = "disconnected"; VoiceConnectionStatus2["Destroyed"] = "destroyed"; + VoiceConnectionStatus2["Disconnected"] = "disconnected"; + VoiceConnectionStatus2["Ready"] = "ready"; + VoiceConnectionStatus2["Signalling"] = "signalling"; return VoiceConnectionStatus2; })(VoiceConnectionStatus || {}); var VoiceConnectionDisconnectReason = /* @__PURE__ */ ((VoiceConnectionDisconnectReason2) => { @@ -1301,23 +1582,52 @@ var VoiceConnectionDisconnectReason = /* @__PURE__ */ ((VoiceConnectionDisconnec VoiceConnectionDisconnectReason2[VoiceConnectionDisconnectReason2["Manual"] = 3] = "Manual"; return VoiceConnectionDisconnectReason2; })(VoiceConnectionDisconnectReason || {}); -var VoiceConnection2 = class extends EventEmitter7 { - constructor(joinConfig, { debug, adapterCreator }) { +var VoiceConnection = class extends EventEmitter7 { + /** + * The number of consecutive rejoin attempts. Initially 0, and increments for each rejoin. + * When a connection is successfully established, it resets to 0. + */ + rejoinAttempts; + /** + * The state of the voice connection. + */ + _state; + /** + * A configuration storing all the data needed to reconnect to a Guild's voice server. + * + * @internal + */ + joinConfig; + /** + * The two packets needed to successfully establish a voice connection. They are received + * from the main Discord gateway after signalling to change the voice state. + */ + packets; + /** + * The receiver of this voice connection. You should join the voice channel with `selfDeaf` set + * to false for this feature to work properly. + */ + receiver; + /** + * The debug logger function, if debugging is enabled. + */ + debug; + /** + * Creates a new voice connection. + * + * @param joinConfig - The data required to establish the voice connection + * @param options - The options used to create this voice connection + */ + constructor(joinConfig, options) { super(); - __publicField(this, "rejoinAttempts"); - __publicField(this, "_state"); - __publicField(this, "joinConfig"); - __publicField(this, "packets"); - __publicField(this, "receiver"); - __publicField(this, "debug"); - this.debug = debug ? (message) => this.emit("debug", message) : null; + this.debug = options.debug ? (message) => this.emit("debug", message) : null; this.rejoinAttempts = 0; this.receiver = new VoiceReceiver(this); this.onNetworkingClose = this.onNetworkingClose.bind(this); this.onNetworkingStateChange = this.onNetworkingStateChange.bind(this); this.onNetworkingError = this.onNetworkingError.bind(this); this.onNetworkingDebug = this.onNetworkingDebug.bind(this); - const adapter = adapterCreator({ + const adapter = options.adapterCreator({ onVoiceServerUpdate: (data) => this.addServerPacket(data), onVoiceStateUpdate: (data) => this.addStatePacket(data), destroy: () => this.destroy(false) @@ -1329,9 +1639,15 @@ var VoiceConnection2 = class extends EventEmitter7 { }; this.joinConfig = joinConfig; } + /** + * The current state of the voice connection. + */ get state() { return this._state; } + /** + * Updates the state of the voice connection, performing clean-up operations where necessary. + */ set state(newState) { const oldState = this._state; const oldNetworking = Reflect.get(oldState, "networking"); @@ -1370,6 +1686,12 @@ var VoiceConnection2 = class extends EventEmitter7 { this.emit(newState.status, oldState, newState); } } + /** + * Registers a `VOICE_SERVER_UPDATE` packet to the voice connection. This will cause it to reconnect using the + * new data provided in the packet. + * + * @param packet - The received `VOICE_SERVER_UPDATE` packet + */ addServerPacket(packet) { this.packets.server = packet; if (packet.endpoint) { @@ -1382,15 +1704,28 @@ var VoiceConnection2 = class extends EventEmitter7 { }; } } + /** + * Registers a `VOICE_STATE_UPDATE` packet to the voice connection. Most importantly, it stores the id of the + * channel that the client is connected to. + * + * @param packet - The received `VOICE_STATE_UPDATE` packet + */ addStatePacket(packet) { this.packets.state = packet; - if (typeof packet.self_deaf !== "undefined") + if (packet.self_deaf !== void 0) this.joinConfig.selfDeaf = packet.self_deaf; - if (typeof packet.self_mute !== "undefined") + if (packet.self_mute !== void 0) this.joinConfig.selfMute = packet.self_mute; if (packet.channel_id) this.joinConfig.channelId = packet.channel_id; } + /** + * Called when the networking state changes, and the new ws/udp packet/message handlers need to be rebound + * to the new instances. + * + * @param newState - The new networking state + * @param oldState - The old networking state, if there is one + */ updateReceiveBindings(newState, oldState) { const oldWs = Reflect.get(oldState ?? {}, "ws"); const newWs = Reflect.get(newState, "ws"); @@ -1406,17 +1741,31 @@ var VoiceConnection2 = class extends EventEmitter7 { } this.receiver.connectionData = Reflect.get(newState, "connectionData") ?? {}; } + /** + * Attempts to configure a networking instance for this voice connection using the received packets. + * Both packets are required, and any existing networking instance will be destroyed. + * + * @remarks + * This is called when the voice server of the connection changes, e.g. if the bot is moved into a + * different channel in the same guild but has a different voice server. In this instance, the connection + * needs to be re-established to the new voice server. + * + * The connection will transition to the Connecting state when this is called. + */ configureNetworking() { const { server, state } = this.packets; if (!server || !state || this.state.status === "destroyed" /* Destroyed */ || !server.endpoint) return; - const networking = new Networking({ - endpoint: server.endpoint, - serverId: server.guild_id, - token: server.token, - sessionId: state.session_id, - userId: state.user_id - }, Boolean(this.debug)); + const networking = new Networking( + { + endpoint: server.endpoint, + serverId: server.guild_id, + token: server.token, + sessionId: state.session_id, + userId: state.user_id + }, + Boolean(this.debug) + ); networking.once("close", this.onNetworkingClose); networking.on("stateChange", this.onNetworkingStateChange); networking.on("error", this.onNetworkingError); @@ -1427,6 +1776,17 @@ var VoiceConnection2 = class extends EventEmitter7 { networking }; } + /** + * Called when the networking instance for this connection closes. If the close code is 4014 (do not reconnect), + * the voice connection will transition to the Disconnected state which will store the close code. You can + * decide whether or not to reconnect when this occurs by listening for the state change and calling reconnect(). + * + * @remarks + * If the close code was anything other than 4014, it is likely that the closing was not intended, and so the + * VoiceConnection will signal to Discord that it would like to rejoin the channel. This automatically attempts + * to re-establish the connection. This would be seen as a transition from the Ready state to the Signalling state. + * @param code - The close code + */ onNetworkingClose(code) { if (this.state.status === "destroyed" /* Destroyed */) return; @@ -1452,6 +1812,12 @@ var VoiceConnection2 = class extends EventEmitter7 { } } } + /** + * Called when the state of the networking instance changes. This is used to derive the state of the voice connection. + * + * @param oldState - The previous state + * @param newState - The new state + */ onNetworkingStateChange(oldState, newState) { this.updateReceiveBindings(newState, oldState); if (oldState.code === newState.code) @@ -1470,24 +1836,47 @@ var VoiceConnection2 = class extends EventEmitter7 { }; } } + /** + * Propagates errors from the underlying network instance. + * + * @param error - The error to propagate + */ onNetworkingError(error) { this.emit("error", error); } + /** + * Propagates debug messages from the underlying network instance. + * + * @param message - The debug message to propagate + */ onNetworkingDebug(message) { this.debug?.(`[NW] ${message}`); } + /** + * Prepares an audio packet for dispatch. + * + * @param buffer - The Opus packet to prepare + */ prepareAudioPacket(buffer) { const state = this.state; if (state.status !== "ready" /* Ready */) return; return state.networking.prepareAudioPacket(buffer); } + /** + * Dispatches the previously prepared audio packet (if any) + */ dispatchAudio() { const state = this.state; if (state.status !== "ready" /* Ready */) return; return state.networking.dispatchAudio(); } + /** + * Prepares an audio packet and dispatches it immediately. + * + * @param buffer - The Opus packet to play + */ playOpusPacket(buffer) { const state = this.state; if (state.status !== "ready" /* Ready */) @@ -1495,6 +1884,13 @@ var VoiceConnection2 = class extends EventEmitter7 { state.networking.prepareAudioPacket(buffer); return state.networking.dispatchAudio(); } + /** + * Destroys the VoiceConnection, preventing it from connecting to voice again. + * This method should be called when you no longer require the VoiceConnection to + * prevent memory leaks. + * + * @param adapterAvailable - Whether the adapter can be used + */ destroy(adapterAvailable = true) { if (this.state.status === "destroyed" /* Destroyed */) { throw new Error("Cannot destroy VoiceConnection - it has already been destroyed"); @@ -1509,6 +1905,11 @@ var VoiceConnection2 = class extends EventEmitter7 { status: "destroyed" /* Destroyed */ }; } + /** + * Disconnects the VoiceConnection, allowing the possibility of rejoining later on. + * + * @returns `true` if the connection was successfully disconnected + */ disconnect() { if (this.state.status === "destroyed" /* Destroyed */ || this.state.status === "signalling" /* Signalling */) { return false; @@ -1530,6 +1931,16 @@ var VoiceConnection2 = class extends EventEmitter7 { }; return true; } + /** + * Attempts to rejoin (better explanation soon:tm:) + * + * @remarks + * Calling this method successfully will automatically increment the `rejoinAttempts` counter, + * which you can use to inform whether or not you'd like to keep attempting to reconnect your + * voice connection. + * + * A state transition from Disconnected to Signalling will be observed when this is called. + */ rejoin(joinConfig) { if (this.state.status === "destroyed" /* Destroyed */) { return false; @@ -1555,11 +1966,23 @@ var VoiceConnection2 = class extends EventEmitter7 { }; return false; } + /** + * Updates the speaking status of the voice connection. This is used when audio players are done playing audio, + * and need to signal that the connection is no longer playing audio. + * + * @param enabled - Whether or not to show as speaking + */ setSpeaking(enabled) { if (this.state.status !== "ready" /* Ready */) return false; return this.state.networking.setSpeaking(enabled); } + /** + * Subscribes to an audio player, allowing the player to play audio on this voice connection. + * + * @param player - The audio player to subscribe to + * @returns The created subscription + */ subscribe(player) { if (this.state.status === "destroyed" /* Destroyed */) return; @@ -1570,6 +1993,14 @@ var VoiceConnection2 = class extends EventEmitter7 { }; return subscription; } + /** + * The latest ping (in milliseconds) for the WebSocket connection and audio playback for this voice + * connection, if this data is available. + * + * @remarks + * For this data to be available, the VoiceConnection must be in the Ready state, and its underlying + * WebSocket connection and UDP socket must have had at least one ping-pong exchange. + */ get ping() { if (this.state.status === "ready" /* Ready */ && this.state.networking.state.code === 4 /* Ready */) { return { @@ -1582,6 +2013,11 @@ var VoiceConnection2 = class extends EventEmitter7 { udp: void 0 }; } + /** + * Called when a subscription of this voice connection to an audio player is removed. + * + * @param subscription - The removed subscription + */ onSubscriptionRemoved(subscription) { if (this.state.status !== "destroyed" /* Destroyed */ && this.state.subscription === subscription) { this.state = { @@ -1591,7 +2027,7 @@ var VoiceConnection2 = class extends EventEmitter7 { } } }; -__name(VoiceConnection2, "VoiceConnection"); +__name(VoiceConnection, "VoiceConnection"); function createVoiceConnection(joinConfig, options) { const payload = createJoinVoiceChannelPayload(joinConfig); const existing = getVoiceConnection(joinConfig.guildId, joinConfig.group); @@ -1611,16 +2047,14 @@ function createVoiceConnection(joinConfig, options) { } return existing; } - const voiceConnection = new VoiceConnection2(joinConfig, options); + const voiceConnection = new VoiceConnection(joinConfig, options); trackVoiceConnection(voiceConnection); - if (voiceConnection.state.status !== "destroyed" /* Destroyed */) { - if (!voiceConnection.state.adapter.sendPayload(payload)) { - voiceConnection.state = { - ...voiceConnection.state, - status: "disconnected" /* Disconnected */, - reason: 1 /* AdapterUnavailable */ - }; - } + if (voiceConnection.state.status !== "destroyed" /* Destroyed */ && !voiceConnection.state.adapter.sendPayload(payload)) { + voiceConnection.state = { + ...voiceConnection.state, + status: "disconnected" /* Disconnected */, + reason: 1 /* AdapterUnavailable */ + }; } return voiceConnection; } @@ -1664,18 +2098,29 @@ var FFMPEG_OPUS_ARGUMENTS = [ ]; var StreamType = /* @__PURE__ */ ((StreamType2) => { StreamType2["Arbitrary"] = "arbitrary"; - StreamType2["Raw"] = "raw"; StreamType2["OggOpus"] = "ogg/opus"; - StreamType2["WebmOpus"] = "webm/opus"; StreamType2["Opus"] = "opus"; + StreamType2["Raw"] = "raw"; + StreamType2["WebmOpus"] = "webm/opus"; return StreamType2; })(StreamType || {}); var Node = class { + /** + * The outbound edges from this node. + */ + edges = []; + /** + * The type of stream for this node. + */ + type; constructor(type) { - __publicField(this, "edges", []); - __publicField(this, "type"); this.type = type; } + /** + * Creates an outbound edge from this node. + * + * @param edge - The edge to create + */ addEdge(edge) { this.edges.push({ ...edge, from: this }); } @@ -1758,9 +2203,9 @@ function findPath(from, constraints, goal = getNode("opus" /* Opus */), path = [ if (from === goal && constraints(path)) { return { cost: 0 }; } else if (depth === 0) { - return { cost: Infinity }; + return { cost: Number.POSITIVE_INFINITY }; } - let currentBest = void 0; + let currentBest; for (const edge of from.edges) { if (currentBest && edge.cost > currentBest.cost) continue; @@ -1770,7 +2215,7 @@ function findPath(from, constraints, goal = getNode("opus" /* Opus */), path = [ currentBest = { cost, edge, next }; } } - return currentBest ?? { cost: Infinity }; + return currentBest ?? { cost: Number.POSITIVE_INFINITY }; } __name(findPath, "findPath"); function constructPipeline(step) { @@ -1790,17 +2235,51 @@ __name(findPipeline, "findPipeline"); // src/audio/AudioResource.ts var AudioResource = class { + /** + * An object-mode Readable stream that emits Opus packets. This is what is played by audio players. + */ + playStream; + /** + * The pipeline used to convert the input stream into a playable format. For example, this may + * contain an FFmpeg component for arbitrary inputs, and it may contain a VolumeTransformer component + * for resources with inline volume transformation enabled. + */ + edges; + /** + * Optional metadata that can be used to identify the resource. + */ + metadata; + /** + * If the resource was created with inline volume transformation enabled, then this will be a + * prism-media VolumeTransformer. You can use this to alter the volume of the stream. + */ + volume; + /** + * If using an Opus encoder to create this audio resource, then this will be a prism-media opus.Encoder. + * You can use this to control settings such as bitrate, FEC, PLP. + */ + encoder; + /** + * The audio player that the resource is subscribed to, if any. + */ + audioPlayer; + /** + * The playback duration of this audio resource, given in milliseconds. + */ + playbackDuration = 0; + /** + * Whether or not the stream for this resource has started (data has become readable) + */ + started = false; + /** + * The number of silence frames to append to the end of the resource's audio stream, to prevent interpolation glitches. + */ + silencePaddingFrames; + /** + * The number of remaining silence frames to play. If -1, the frames have not yet started playing. + */ + silenceRemaining = -1; constructor(edges, streams, metadata, silencePaddingFrames) { - __publicField(this, "playStream"); - __publicField(this, "edges"); - __publicField(this, "metadata"); - __publicField(this, "volume"); - __publicField(this, "encoder"); - __publicField(this, "audioPlayer"); - __publicField(this, "playbackDuration", 0); - __publicField(this, "started", false); - __publicField(this, "silencePaddingFrames"); - __publicField(this, "silenceRemaining", -1); this.edges = edges; this.playStream = streams.length > 1 ? pipeline(streams, noop) : streams[0]; this.metadata = metadata; @@ -1814,6 +2293,10 @@ var AudioResource = class { } this.playStream.once("readable", () => this.started = true); } + /** + * Whether this resource is readable. If the underlying resource is no longer readable, this will still return true + * while there are silence padding frames left to play. + */ get readable() { if (this.silenceRemaining === 0) return false; @@ -1825,9 +2308,22 @@ var AudioResource = class { } return real; } + /** + * Whether this resource has ended or not. + */ get ended() { return this.playStream.readableEnded || this.playStream.destroyed || this.silenceRemaining === 0; } + /** + * Attempts to read an Opus packet from the audio resource. If a packet is available, the playbackDuration + * is incremented. + * + * @remarks + * It is advisable to check that the playStream is readable before calling this method. While no runtime + * errors will be thrown, you should check that the resource is still available before attempting to + * read from it. + * @internal + */ read() { if (this.silenceRemaining === 0) { return null; @@ -1865,7 +2361,7 @@ function createAudioResource(input, options = {}) { let needsInlineVolume = Boolean(options.inlineVolume); if (typeof input === "string") { inputType = "arbitrary" /* Arbitrary */; - } else if (typeof inputType === "undefined") { + } else if (inputType === void 0) { const analysis = inferStreamType(input); inputType = analysis.streamType; needsInlineVolume = needsInlineVolume && !analysis.hasVolume; @@ -1879,7 +2375,12 @@ function createAudioResource(input, options = {}) { const streams = transformerPipeline.map((edge) => edge.transformer(input)); if (typeof input !== "string") streams.unshift(input); - return new AudioResource(transformerPipeline, streams, options.metadata ?? null, options.silencePaddingFrames ?? 5); + return new AudioResource( + transformerPipeline, + streams, + options.metadata ?? null, + options.silencePaddingFrames ?? 5 + ); } __name(createAudioResource, "createAudioResource"); @@ -1895,16 +2396,19 @@ function findPackageJSON(dir, packageName, depth) { if (pkg.name !== packageName) throw new Error("package.json does not match"); return pkg; - } catch (err) { + } catch { return findPackageJSON(resolve(dir, ".."), packageName, depth - 1); } } __name(findPackageJSON, "findPackageJSON"); function version(name) { try { - const pkg = name === "@discordjs/voice" ? require_package() : findPackageJSON(dirname(__require.resolve(name)), name, 3); + if (name === "@discordjs/voice") { + return "0.16.0"; + } + const pkg = findPackageJSON(dirname(__require.resolve(name)), name, 3); return pkg?.version ?? "not found"; - } catch (err) { + } catch { return "not found"; } } @@ -1931,7 +2435,7 @@ function generateDependencyReport() { const info = prism3.FFmpeg.getInfo(); report.push(`- version: ${info.version}`); report.push(`- libopus: ${info.output.includes("--enable-libopus") ? "yes" : "no"}`); - } catch (err) { + } catch { report.push("- not found"); } return ["-".repeat(50), ...report, "-".repeat(50)].join("\n"); @@ -1965,7 +2469,9 @@ async function entersState(target, status, timeoutOrSignal) { __name(entersState, "entersState"); // src/util/demuxProbe.ts -import { Readable as Readable3 } from "node:stream"; +import { Buffer as Buffer7 } from "node:buffer"; +import process from "node:process"; +import { Readable as Readable2 } from "node:stream"; import prism4 from "prism-media"; function validateDiscordOpusHead(opusHead) { const channels = opusHead.readUInt8(9); @@ -1973,14 +2479,18 @@ function validateDiscordOpusHead(opusHead) { return channels === 2 && sampleRate === 48e3; } __name(validateDiscordOpusHead, "validateDiscordOpusHead"); -function demuxProbe(stream, probeSize = 1024, validator = validateDiscordOpusHead) { +async function demuxProbe(stream, probeSize = 1024, validator = validateDiscordOpusHead) { return new Promise((resolve2, reject) => { - if (stream.readableObjectMode) - return reject(new Error("Cannot probe a readable stream in object mode")); - if (stream.readableEnded) - return reject(new Error("Cannot probe a stream that has ended")); - let readBuffer = Buffer.alloc(0); - let resolved = void 0; + if (stream.readableObjectMode) { + reject(new Error("Cannot probe a readable stream in object mode")); + return; + } + if (stream.readableEnded) { + reject(new Error("Cannot probe a stream that has ended")); + return; + } + let readBuffer = Buffer7.alloc(0); + let resolved; const finish = /* @__PURE__ */ __name((type) => { stream.off("data", onData); stream.off("close", onClose); @@ -1989,7 +2499,7 @@ function demuxProbe(stream, probeSize = 1024, validator = validateDiscordOpusHea resolved = type; if (stream.readableEnded) { resolve2({ - stream: Readable3.from(readBuffer), + stream: Readable2.from(readBuffer), type }); } else { @@ -2019,7 +2529,7 @@ function demuxProbe(stream, probeSize = 1024, validator = validateDiscordOpusHea } }, "onClose"); const onData = /* @__PURE__ */ __name((buffer) => { - readBuffer = Buffer.concat([readBuffer, buffer]); + readBuffer = Buffer7.concat([readBuffer, buffer]); webm.write(buffer); ogg.write(buffer); if (readBuffer.length >= probeSize) { @@ -2035,6 +2545,9 @@ function demuxProbe(stream, probeSize = 1024, validator = validateDiscordOpusHea }); } __name(demuxProbe, "demuxProbe"); + +// src/index.ts +var version2 = "0.16.0"; export { AudioPlayer, AudioPlayerError, @@ -2047,7 +2560,7 @@ export { SSRCMap, SpeakingMap, StreamType, - VoiceConnection2 as VoiceConnection, + VoiceConnection, VoiceConnectionDisconnectReason, VoiceConnectionStatus, VoiceReceiver, @@ -2061,6 +2574,7 @@ export { getVoiceConnection, getVoiceConnections, joinVoiceChannel, - validateDiscordOpusHead + validateDiscordOpusHead, + version2 as version }; //# sourceMappingURL=index.mjs.map \ No newline at end of file diff --git a/node_modules/@discordjs/voice/dist/index.mjs.map b/node_modules/@discordjs/voice/dist/index.mjs.map index fc2762d..c50c838 100644 --- a/node_modules/@discordjs/voice/dist/index.mjs.map +++ b/node_modules/@discordjs/voice/dist/index.mjs.map @@ -1 +1 @@ -{"version":3,"sources":["../src/VoiceConnection.ts","../src/DataStore.ts","../src/networking/Networking.ts","../src/networking/VoiceUDPSocket.ts","../src/networking/VoiceWebSocket.ts","../src/util/Secretbox.ts","../src/util/util.ts","../src/receive/VoiceReceiver.ts","../src/receive/AudioReceiveStream.ts","../src/audio/AudioPlayer.ts","../src/audio/AudioPlayerError.ts","../src/audio/PlayerSubscription.ts","../src/receive/SSRCMap.ts","../src/receive/SpeakingMap.ts","../src/joinVoiceChannel.ts","../src/audio/AudioResource.ts","../src/audio/TransformerGraph.ts","../src/util/generateDependencyReport.ts","../src/util/entersState.ts","../src/util/abortAfter.ts","../src/util/demuxProbe.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/method-signature-style */\nimport { EventEmitter } from 'node:events';\nimport type { GatewayVoiceServerUpdateDispatchData, GatewayVoiceStateUpdateDispatchData } from 'discord-api-types/v10';\nimport type { CreateVoiceConnectionOptions } from '.';\nimport {\n\tgetVoiceConnection,\n\tcreateJoinVoiceChannelPayload,\n\ttrackVoiceConnection,\n\tJoinConfig,\n\tuntrackVoiceConnection,\n} from './DataStore';\nimport type { AudioPlayer } from './audio/AudioPlayer';\nimport type { PlayerSubscription } from './audio/PlayerSubscription';\nimport type { VoiceWebSocket, VoiceUDPSocket } from './networking';\nimport { Networking, NetworkingState, NetworkingStatusCode } from './networking/Networking';\nimport { VoiceReceiver } from './receive';\nimport type { DiscordGatewayAdapterImplementerMethods } from './util/adapter';\nimport { noop } from './util/util';\n\n/**\n * The various status codes a voice connection can hold at any one time.\n */\nexport enum VoiceConnectionStatus {\n\t/**\n\t * Sending a packet to the main Discord gateway to indicate we want to change our voice state.\n\t */\n\tSignalling = 'signalling',\n\n\t/**\n\t * The `VOICE_SERVER_UPDATE` and `VOICE_STATE_UPDATE` packets have been received, now attempting to establish a voice connection.\n\t */\n\tConnecting = 'connecting',\n\n\t/**\n\t * A voice connection has been established, and is ready to be used.\n\t */\n\tReady = 'ready',\n\n\t/**\n\t * The voice connection has either been severed or not established.\n\t */\n\tDisconnected = 'disconnected',\n\n\t/**\n\t * The voice connection has been destroyed and untracked, it cannot be reused.\n\t */\n\tDestroyed = 'destroyed',\n}\n\n/**\n * The state that a VoiceConnection will be in when it is waiting to receive a VOICE_SERVER_UPDATE and\n * VOICE_STATE_UPDATE packet from Discord, provided by the adapter.\n */\nexport interface VoiceConnectionSignallingState {\n\tstatus: VoiceConnectionStatus.Signalling;\n\tsubscription?: PlayerSubscription;\n\tadapter: DiscordGatewayAdapterImplementerMethods;\n}\n\n/**\n * The reasons a voice connection can be in the disconnected state.\n */\nexport enum VoiceConnectionDisconnectReason {\n\t/**\n\t * When the WebSocket connection has been closed.\n\t */\n\tWebSocketClose,\n\n\t/**\n\t * When the adapter was unable to send a message requested by the VoiceConnection.\n\t */\n\tAdapterUnavailable,\n\n\t/**\n\t * When a VOICE_SERVER_UPDATE packet is received with a null endpoint, causing the connection to be severed.\n\t */\n\tEndpointRemoved,\n\n\t/**\n\t * When a manual disconnect was requested.\n\t */\n\tManual,\n}\n\n/**\n * The state that a VoiceConnection will be in when it is not connected to a Discord voice server nor is\n * it attempting to connect. You can manually attempt to reconnect using VoiceConnection#reconnect.\n */\nexport interface VoiceConnectionDisconnectedBaseState {\n\tstatus: VoiceConnectionStatus.Disconnected;\n\tsubscription?: PlayerSubscription;\n\tadapter: DiscordGatewayAdapterImplementerMethods;\n}\n\n/**\n * The state that a VoiceConnection will be in when it is not connected to a Discord voice server nor is\n * it attempting to connect. You can manually attempt to reconnect using VoiceConnection#reconnect.\n */\nexport interface VoiceConnectionDisconnectedOtherState extends VoiceConnectionDisconnectedBaseState {\n\treason: Exclude;\n}\n\n/**\n * The state that a VoiceConnection will be in when its WebSocket connection was closed.\n * You can manually attempt to reconnect using VoiceConnection#reconnect.\n */\nexport interface VoiceConnectionDisconnectedWebSocketState extends VoiceConnectionDisconnectedBaseState {\n\treason: VoiceConnectionDisconnectReason.WebSocketClose;\n\n\t/**\n\t * The close code of the WebSocket connection to the Discord voice server.\n\t */\n\tcloseCode: number;\n}\n\n/**\n * The states that a VoiceConnection can be in when it is not connected to a Discord voice server nor is\n * it attempting to connect. You can manually attempt to connect using VoiceConnection#reconnect.\n */\nexport type VoiceConnectionDisconnectedState =\n\t| VoiceConnectionDisconnectedOtherState\n\t| VoiceConnectionDisconnectedWebSocketState;\n\n/**\n * The state that a VoiceConnection will be in when it is establishing a connection to a Discord\n * voice server.\n */\nexport interface VoiceConnectionConnectingState {\n\tstatus: VoiceConnectionStatus.Connecting;\n\tnetworking: Networking;\n\tsubscription?: PlayerSubscription;\n\tadapter: DiscordGatewayAdapterImplementerMethods;\n}\n\n/**\n * The state that a VoiceConnection will be in when it has an active connection to a Discord\n * voice server.\n */\nexport interface VoiceConnectionReadyState {\n\tstatus: VoiceConnectionStatus.Ready;\n\tnetworking: Networking;\n\tsubscription?: PlayerSubscription;\n\tadapter: DiscordGatewayAdapterImplementerMethods;\n}\n\n/**\n * The state that a VoiceConnection will be in when it has been permanently been destroyed by the\n * user and untracked by the library. It cannot be reconnected, instead, a new VoiceConnection\n * needs to be established.\n */\nexport interface VoiceConnectionDestroyedState {\n\tstatus: VoiceConnectionStatus.Destroyed;\n}\n\n/**\n * The various states that a voice connection can be in.\n */\nexport type VoiceConnectionState =\n\t| VoiceConnectionSignallingState\n\t| VoiceConnectionDisconnectedState\n\t| VoiceConnectionConnectingState\n\t| VoiceConnectionReadyState\n\t| VoiceConnectionDestroyedState;\n\nexport interface VoiceConnection extends EventEmitter {\n\t/**\n\t * Emitted when there is an error emitted from the voice connection\n\t * @event\n\t */\n\ton(event: 'error', listener: (error: Error) => void): this;\n\t/**\n\t * Emitted debugging information about the voice connection\n\t * @event\n\t */\n\ton(event: 'debug', listener: (message: string) => void): this;\n\t/**\n\t * Emitted when the state of the voice connection changes\n\t * @event\n\t */\n\ton(event: 'stateChange', listener: (oldState: VoiceConnectionState, newState: VoiceConnectionState) => void): this;\n\t/**\n\t * Emitted when the state of the voice connection changes to a specific status\n\t * @event\n\t */\n\ton(\n\t\tevent: T,\n\t\tlistener: (oldState: VoiceConnectionState, newState: VoiceConnectionState & { status: T }) => void,\n\t): this;\n}\n\n/**\n * A connection to the voice server of a Guild, can be used to play audio in voice channels.\n */\nexport class VoiceConnection extends EventEmitter {\n\t/**\n\t * The number of consecutive rejoin attempts. Initially 0, and increments for each rejoin.\n\t * When a connection is successfully established, it resets to 0.\n\t */\n\tpublic rejoinAttempts: number;\n\n\t/**\n\t * The state of the voice connection.\n\t */\n\tprivate _state: VoiceConnectionState;\n\n\t/**\n\t * A configuration storing all the data needed to reconnect to a Guild's voice server.\n\t *\n\t * @internal\n\t */\n\tpublic readonly joinConfig: JoinConfig;\n\n\t/**\n\t * The two packets needed to successfully establish a voice connection. They are received\n\t * from the main Discord gateway after signalling to change the voice state.\n\t */\n\tprivate readonly packets: {\n\t\tserver: GatewayVoiceServerUpdateDispatchData | undefined;\n\t\tstate: GatewayVoiceStateUpdateDispatchData | undefined;\n\t};\n\n\t/**\n\t * The receiver of this voice connection. You should join the voice channel with `selfDeaf` set\n\t * to false for this feature to work properly.\n\t */\n\tpublic readonly receiver: VoiceReceiver;\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: null | ((message: string) => void);\n\n\t/**\n\t * Creates a new voice connection.\n\t *\n\t * @param joinConfig - The data required to establish the voice connection\n\t * @param options - The options used to create this voice connection\n\t */\n\tpublic constructor(joinConfig: JoinConfig, { debug, adapterCreator }: CreateVoiceConnectionOptions) {\n\t\tsuper();\n\n\t\tthis.debug = debug ? (message: string) => this.emit('debug', message) : null;\n\t\tthis.rejoinAttempts = 0;\n\n\t\tthis.receiver = new VoiceReceiver(this);\n\n\t\tthis.onNetworkingClose = this.onNetworkingClose.bind(this);\n\t\tthis.onNetworkingStateChange = this.onNetworkingStateChange.bind(this);\n\t\tthis.onNetworkingError = this.onNetworkingError.bind(this);\n\t\tthis.onNetworkingDebug = this.onNetworkingDebug.bind(this);\n\n\t\tconst adapter = adapterCreator({\n\t\t\tonVoiceServerUpdate: (data) => this.addServerPacket(data),\n\t\t\tonVoiceStateUpdate: (data) => this.addStatePacket(data),\n\t\t\tdestroy: () => this.destroy(false),\n\t\t});\n\n\t\tthis._state = { status: VoiceConnectionStatus.Signalling, adapter };\n\n\t\tthis.packets = {\n\t\t\tserver: undefined,\n\t\t\tstate: undefined,\n\t\t};\n\n\t\tthis.joinConfig = joinConfig;\n\t}\n\n\t/**\n\t * The current state of the voice connection.\n\t */\n\tpublic get state() {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * Updates the state of the voice connection, performing clean-up operations where necessary.\n\t */\n\tpublic set state(newState: VoiceConnectionState) {\n\t\tconst oldState = this._state;\n\t\tconst oldNetworking = Reflect.get(oldState, 'networking') as Networking | undefined;\n\t\tconst newNetworking = Reflect.get(newState, 'networking') as Networking | undefined;\n\n\t\tconst oldSubscription = Reflect.get(oldState, 'subscription') as PlayerSubscription | undefined;\n\t\tconst newSubscription = Reflect.get(newState, 'subscription') as PlayerSubscription | undefined;\n\n\t\tif (oldNetworking !== newNetworking) {\n\t\t\tif (oldNetworking) {\n\t\t\t\toldNetworking.on('error', noop);\n\t\t\t\toldNetworking.off('debug', this.onNetworkingDebug);\n\t\t\t\toldNetworking.off('error', this.onNetworkingError);\n\t\t\t\toldNetworking.off('close', this.onNetworkingClose);\n\t\t\t\toldNetworking.off('stateChange', this.onNetworkingStateChange);\n\t\t\t\toldNetworking.destroy();\n\t\t\t}\n\t\t\tif (newNetworking) this.updateReceiveBindings(newNetworking.state, oldNetworking?.state);\n\t\t}\n\n\t\tif (newState.status === VoiceConnectionStatus.Ready) {\n\t\t\tthis.rejoinAttempts = 0;\n\t\t} else if (newState.status === VoiceConnectionStatus.Destroyed) {\n\t\t\tfor (const stream of this.receiver.subscriptions.values()) {\n\t\t\t\tif (!stream.destroyed) stream.destroy();\n\t\t\t}\n\t\t}\n\n\t\t// If destroyed, the adapter can also be destroyed so it can be cleaned up by the user\n\t\tif (oldState.status !== VoiceConnectionStatus.Destroyed && newState.status === VoiceConnectionStatus.Destroyed) {\n\t\t\toldState.adapter.destroy();\n\t\t}\n\n\t\tthis._state = newState;\n\n\t\tif (oldSubscription && oldSubscription !== newSubscription) {\n\t\t\toldSubscription.unsubscribe();\n\t\t}\n\n\t\tthis.emit('stateChange', oldState, newState);\n\t\tif (oldState.status !== newState.status) {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\t\tthis.emit(newState.status, oldState, newState as any);\n\t\t}\n\t}\n\n\t/**\n\t * Registers a `VOICE_SERVER_UPDATE` packet to the voice connection. This will cause it to reconnect using the\n\t * new data provided in the packet.\n\t *\n\t * @param packet - The received `VOICE_SERVER_UPDATE` packet\n\t */\n\tprivate addServerPacket(packet: GatewayVoiceServerUpdateDispatchData) {\n\t\tthis.packets.server = packet;\n\t\tif (packet.endpoint) {\n\t\t\tthis.configureNetworking();\n\t\t} else if (this.state.status !== VoiceConnectionStatus.Destroyed) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.EndpointRemoved,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Registers a `VOICE_STATE_UPDATE` packet to the voice connection. Most importantly, it stores the id of the\n\t * channel that the client is connected to.\n\t *\n\t * @param packet - The received `VOICE_STATE_UPDATE` packet\n\t */\n\tprivate addStatePacket(packet: GatewayVoiceStateUpdateDispatchData) {\n\t\tthis.packets.state = packet;\n\n\t\tif (typeof packet.self_deaf !== 'undefined') this.joinConfig.selfDeaf = packet.self_deaf;\n\t\tif (typeof packet.self_mute !== 'undefined') this.joinConfig.selfMute = packet.self_mute;\n\t\tif (packet.channel_id) this.joinConfig.channelId = packet.channel_id;\n\t\t/*\n\t\t\tthe channel_id being null doesn't necessarily mean it was intended for the client to leave the voice channel\n\t\t\tas it may have disconnected due to network failure. This will be gracefully handled once the voice websocket\n\t\t\tdies, and then it is up to the user to decide how they wish to handle this.\n\t\t*/\n\t}\n\n\t/**\n\t * Called when the networking state changes, and the new ws/udp packet/message handlers need to be rebound\n\t * to the new instances.\n\t * @param newState - The new networking state\n\t * @param oldState - The old networking state, if there is one\n\t */\n\tprivate updateReceiveBindings(newState: NetworkingState, oldState?: NetworkingState) {\n\t\tconst oldWs = Reflect.get(oldState ?? {}, 'ws') as VoiceWebSocket | undefined;\n\t\tconst newWs = Reflect.get(newState, 'ws') as VoiceWebSocket | undefined;\n\t\tconst oldUdp = Reflect.get(oldState ?? {}, 'udp') as VoiceUDPSocket | undefined;\n\t\tconst newUdp = Reflect.get(newState, 'udp') as VoiceUDPSocket | undefined;\n\n\t\tif (oldWs !== newWs) {\n\t\t\toldWs?.off('packet', this.receiver.onWsPacket);\n\t\t\tnewWs?.on('packet', this.receiver.onWsPacket);\n\t\t}\n\n\t\tif (oldUdp !== newUdp) {\n\t\t\toldUdp?.off('message', this.receiver.onUdpMessage);\n\t\t\tnewUdp?.on('message', this.receiver.onUdpMessage);\n\t\t}\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\tthis.receiver.connectionData = Reflect.get(newState, 'connectionData') ?? {};\n\t}\n\n\t/**\n\t * Attempts to configure a networking instance for this voice connection using the received packets.\n\t * Both packets are required, and any existing networking instance will be destroyed.\n\t *\n\t * @remarks\n\t * This is called when the voice server of the connection changes, e.g. if the bot is moved into a\n\t * different channel in the same guild but has a different voice server. In this instance, the connection\n\t * needs to be re-established to the new voice server.\n\t *\n\t * The connection will transition to the Connecting state when this is called.\n\t */\n\tpublic configureNetworking() {\n\t\tconst { server, state } = this.packets;\n\t\tif (!server || !state || this.state.status === VoiceConnectionStatus.Destroyed || !server.endpoint) return;\n\n\t\tconst networking = new Networking(\n\t\t\t{\n\t\t\t\tendpoint: server.endpoint,\n\t\t\t\tserverId: server.guild_id,\n\t\t\t\ttoken: server.token,\n\t\t\t\tsessionId: state.session_id,\n\t\t\t\tuserId: state.user_id,\n\t\t\t},\n\t\t\tBoolean(this.debug),\n\t\t);\n\n\t\tnetworking.once('close', this.onNetworkingClose);\n\t\tnetworking.on('stateChange', this.onNetworkingStateChange);\n\t\tnetworking.on('error', this.onNetworkingError);\n\t\tnetworking.on('debug', this.onNetworkingDebug);\n\n\t\tthis.state = {\n\t\t\t...this.state,\n\t\t\tstatus: VoiceConnectionStatus.Connecting,\n\t\t\tnetworking,\n\t\t};\n\t}\n\n\t/**\n\t * Called when the networking instance for this connection closes. If the close code is 4014 (do not reconnect),\n\t * the voice connection will transition to the Disconnected state which will store the close code. You can\n\t * decide whether or not to reconnect when this occurs by listening for the state change and calling reconnect().\n\t *\n\t * @remarks\n\t * If the close code was anything other than 4014, it is likely that the closing was not intended, and so the\n\t * VoiceConnection will signal to Discord that it would like to rejoin the channel. This automatically attempts\n\t * to re-establish the connection. This would be seen as a transition from the Ready state to the Signalling state.\n\t *\n\t * @param code - The close code\n\t */\n\tprivate onNetworkingClose(code: number) {\n\t\tif (this.state.status === VoiceConnectionStatus.Destroyed) return;\n\t\t// If networking closes, try to connect to the voice channel again.\n\t\tif (code === 4014) {\n\t\t\t// Disconnected - networking is already destroyed here\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.WebSocketClose,\n\t\t\t\tcloseCode: code,\n\t\t\t};\n\t\t} else {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Signalling,\n\t\t\t};\n\t\t\tthis.rejoinAttempts++;\n\t\t\tif (!this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) {\n\t\t\t\tthis.state = {\n\t\t\t\t\t...this.state,\n\t\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Called when the state of the networking instance changes. This is used to derive the state of the voice connection.\n\t *\n\t * @param oldState - The previous state\n\t * @param newState - The new state\n\t */\n\tprivate onNetworkingStateChange(oldState: NetworkingState, newState: NetworkingState) {\n\t\tthis.updateReceiveBindings(newState, oldState);\n\t\tif (oldState.code === newState.code) return;\n\t\tif (this.state.status !== VoiceConnectionStatus.Connecting && this.state.status !== VoiceConnectionStatus.Ready)\n\t\t\treturn;\n\n\t\tif (newState.code === NetworkingStatusCode.Ready) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Ready,\n\t\t\t};\n\t\t} else if (newState.code !== NetworkingStatusCode.Closed) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Connecting,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Propagates errors from the underlying network instance.\n\t *\n\t * @param error - The error to propagate\n\t */\n\tprivate onNetworkingError(error: Error) {\n\t\tthis.emit('error', error);\n\t}\n\n\t/**\n\t * Propagates debug messages from the underlying network instance.\n\t *\n\t * @param message - The debug message to propagate\n\t */\n\tprivate onNetworkingDebug(message: string) {\n\t\tthis.debug?.(`[NW] ${message}`);\n\t}\n\n\t/**\n\t * Prepares an audio packet for dispatch.\n\t *\n\t * @param buffer - The Opus packet to prepare\n\t */\n\tpublic prepareAudioPacket(buffer: Buffer) {\n\t\tconst state = this.state;\n\t\tif (state.status !== VoiceConnectionStatus.Ready) return;\n\t\treturn state.networking.prepareAudioPacket(buffer);\n\t}\n\n\t/**\n\t * Dispatches the previously prepared audio packet (if any)\n\t */\n\tpublic dispatchAudio() {\n\t\tconst state = this.state;\n\t\tif (state.status !== VoiceConnectionStatus.Ready) return;\n\t\treturn state.networking.dispatchAudio();\n\t}\n\n\t/**\n\t * Prepares an audio packet and dispatches it immediately.\n\t *\n\t * @param buffer - The Opus packet to play\n\t */\n\tpublic playOpusPacket(buffer: Buffer) {\n\t\tconst state = this.state;\n\t\tif (state.status !== VoiceConnectionStatus.Ready) return;\n\t\tstate.networking.prepareAudioPacket(buffer);\n\t\treturn state.networking.dispatchAudio();\n\t}\n\n\t/**\n\t * Destroys the VoiceConnection, preventing it from connecting to voice again.\n\t * This method should be called when you no longer require the VoiceConnection to\n\t * prevent memory leaks.\n\t *\n\t * @param adapterAvailable - Whether the adapter can be used\n\t */\n\tpublic destroy(adapterAvailable = true) {\n\t\tif (this.state.status === VoiceConnectionStatus.Destroyed) {\n\t\t\tthrow new Error('Cannot destroy VoiceConnection - it has already been destroyed');\n\t\t}\n\t\tif (getVoiceConnection(this.joinConfig.guildId, this.joinConfig.group) === this) {\n\t\t\tuntrackVoiceConnection(this);\n\t\t}\n\t\tif (adapterAvailable) {\n\t\t\tthis.state.adapter.sendPayload(createJoinVoiceChannelPayload({ ...this.joinConfig, channelId: null }));\n\t\t}\n\t\tthis.state = {\n\t\t\tstatus: VoiceConnectionStatus.Destroyed,\n\t\t};\n\t}\n\n\t/**\n\t * Disconnects the VoiceConnection, allowing the possibility of rejoining later on.\n\t *\n\t * @returns `true` if the connection was successfully disconnected\n\t */\n\tpublic disconnect() {\n\t\tif (\n\t\t\tthis.state.status === VoiceConnectionStatus.Destroyed ||\n\t\t\tthis.state.status === VoiceConnectionStatus.Signalling\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\t\tthis.joinConfig.channelId = null;\n\t\tif (!this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) {\n\t\t\tthis.state = {\n\t\t\t\tadapter: this.state.adapter,\n\t\t\t\tsubscription: this.state.subscription,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t\t};\n\t\t\treturn false;\n\t\t}\n\t\tthis.state = {\n\t\t\tadapter: this.state.adapter,\n\t\t\treason: VoiceConnectionDisconnectReason.Manual,\n\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t};\n\t\treturn true;\n\t}\n\n\t/**\n\t * Attempts to rejoin (better explanation soon:tm:)\n\t *\n\t * @remarks\n\t * Calling this method successfully will automatically increment the `rejoinAttempts` counter,\n\t * which you can use to inform whether or not you'd like to keep attempting to reconnect your\n\t * voice connection.\n\t *\n\t * A state transition from Disconnected to Signalling will be observed when this is called.\n\t */\n\tpublic rejoin(joinConfig?: Omit) {\n\t\tif (this.state.status === VoiceConnectionStatus.Destroyed) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst notReady = this.state.status !== VoiceConnectionStatus.Ready;\n\n\t\tif (notReady) this.rejoinAttempts++;\n\t\tObject.assign(this.joinConfig, joinConfig);\n\t\tif (this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) {\n\t\t\tif (notReady) {\n\t\t\t\tthis.state = {\n\t\t\t\t\t...this.state,\n\t\t\t\t\tstatus: VoiceConnectionStatus.Signalling,\n\t\t\t\t};\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\n\t\tthis.state = {\n\t\t\tadapter: this.state.adapter,\n\t\t\tsubscription: this.state.subscription,\n\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t};\n\t\treturn false;\n\t}\n\n\t/**\n\t * Updates the speaking status of the voice connection. This is used when audio players are done playing audio,\n\t * and need to signal that the connection is no longer playing audio.\n\t *\n\t * @param enabled - Whether or not to show as speaking\n\t */\n\tpublic setSpeaking(enabled: boolean) {\n\t\tif (this.state.status !== VoiceConnectionStatus.Ready) return false;\n\t\treturn this.state.networking.setSpeaking(enabled);\n\t}\n\n\t/**\n\t * Subscribes to an audio player, allowing the player to play audio on this voice connection.\n\t *\n\t * @param player - The audio player to subscribe to\n\t *\n\t * @returns The created subscription\n\t */\n\tpublic subscribe(player: AudioPlayer) {\n\t\tif (this.state.status === VoiceConnectionStatus.Destroyed) return;\n\n\t\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\t\tconst subscription = player['subscribe'](this);\n\n\t\tthis.state = {\n\t\t\t...this.state,\n\t\t\tsubscription,\n\t\t};\n\n\t\treturn subscription;\n\t}\n\n\t/**\n\t * The latest ping (in milliseconds) for the WebSocket connection and audio playback for this voice\n\t * connection, if this data is available.\n\t *\n\t * @remarks\n\t * For this data to be available, the VoiceConnection must be in the Ready state, and its underlying\n\t * WebSocket connection and UDP socket must have had at least one ping-pong exchange.\n\t */\n\tpublic get ping() {\n\t\tif (\n\t\t\tthis.state.status === VoiceConnectionStatus.Ready &&\n\t\t\tthis.state.networking.state.code === NetworkingStatusCode.Ready\n\t\t) {\n\t\t\treturn {\n\t\t\t\tws: this.state.networking.state.ws.ping,\n\t\t\t\tudp: this.state.networking.state.udp.ping,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\tws: undefined,\n\t\t\tudp: undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Called when a subscription of this voice connection to an audio player is removed.\n\t *\n\t * @param subscription - The removed subscription\n\t */\n\tprivate onSubscriptionRemoved(subscription: PlayerSubscription) {\n\t\tif (this.state.status !== VoiceConnectionStatus.Destroyed && this.state.subscription === subscription) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tsubscription: undefined,\n\t\t\t};\n\t\t}\n\t}\n}\n\n/**\n * Creates a new voice connection.\n *\n * @param joinConfig - The data required to establish the voice connection\n * @param options - The options to use when joining the voice channel\n */\nexport function createVoiceConnection(joinConfig: JoinConfig, options: CreateVoiceConnectionOptions) {\n\tconst payload = createJoinVoiceChannelPayload(joinConfig);\n\tconst existing = getVoiceConnection(joinConfig.guildId, joinConfig.group);\n\tif (existing && existing.state.status !== VoiceConnectionStatus.Destroyed) {\n\t\tif (existing.state.status === VoiceConnectionStatus.Disconnected) {\n\t\t\texisting.rejoin({\n\t\t\t\tchannelId: joinConfig.channelId,\n\t\t\t\tselfDeaf: joinConfig.selfDeaf,\n\t\t\t\tselfMute: joinConfig.selfMute,\n\t\t\t});\n\t\t} else if (!existing.state.adapter.sendPayload(payload)) {\n\t\t\texisting.state = {\n\t\t\t\t...existing.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t\t};\n\t\t}\n\t\treturn existing;\n\t}\n\n\tconst voiceConnection = new VoiceConnection(joinConfig, options);\n\ttrackVoiceConnection(voiceConnection);\n\tif (voiceConnection.state.status !== VoiceConnectionStatus.Destroyed) {\n\t\tif (!voiceConnection.state.adapter.sendPayload(payload)) {\n\t\t\tvoiceConnection.state = {\n\t\t\t\t...voiceConnection.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t\t};\n\t\t}\n\t}\n\treturn voiceConnection;\n}\n","import { GatewayOpcodes } from 'discord-api-types/v10';\nimport type { VoiceConnection } from './VoiceConnection';\nimport type { AudioPlayer } from './audio';\n\nexport interface JoinConfig {\n\tguildId: string;\n\tchannelId: string | null;\n\tselfDeaf: boolean;\n\tselfMute: boolean;\n\tgroup: string;\n}\n\n/**\n * Sends a voice state update to the main websocket shard of a guild, to indicate joining/leaving/moving across\n * voice channels.\n *\n * @param config - The configuration to use when joining the voice channel\n */\nexport function createJoinVoiceChannelPayload(config: JoinConfig) {\n\treturn {\n\t\top: GatewayOpcodes.VoiceStateUpdate,\n\t\td: {\n\t\t\tguild_id: config.guildId,\n\t\t\tchannel_id: config.channelId,\n\t\t\tself_deaf: config.selfDeaf,\n\t\t\tself_mute: config.selfMute,\n\t\t},\n\t};\n}\n\n// Voice Connections\nconst groups = new Map>();\ngroups.set('default', new Map());\n\nfunction getOrCreateGroup(group: string) {\n\tconst existing = groups.get(group);\n\tif (existing) return existing;\n\tconst map = new Map();\n\tgroups.set(group, map);\n\treturn map;\n}\n\n/**\n * Retrieves the map of group names to maps of voice connections. By default, all voice connections\n * are created under the 'default' group.\n *\n * @returns The group map\n */\nexport function getGroups() {\n\treturn groups;\n}\n\n/**\n * Retrieves all the voice connections under the 'default' group.\n *\n * @param group - The group to look up\n *\n * @returns The map of voice connections\n */\nexport function getVoiceConnections(group?: 'default'): Map;\n\n/**\n * Retrieves all the voice connections under the given group name.\n *\n * @param group - The group to look up\n *\n * @returns The map of voice connections\n */\nexport function getVoiceConnections(group: string): Map | undefined;\n\n/**\n * Retrieves all the voice connections under the given group name. Defaults to the 'default' group.\n *\n * @param group - The group to look up\n *\n * @returns The map of voice connections\n */\nexport function getVoiceConnections(group = 'default') {\n\treturn groups.get(group);\n}\n\n/**\n * Finds a voice connection with the given guild id and group. Defaults to the 'default' group.\n *\n * @param guildId - The guild id of the voice connection\n * @param group - the group that the voice connection was registered with\n *\n * @returns The voice connection, if it exists\n */\nexport function getVoiceConnection(guildId: string, group = 'default') {\n\treturn getVoiceConnections(group)?.get(guildId);\n}\n\nexport function untrackVoiceConnection(voiceConnection: VoiceConnection) {\n\treturn getVoiceConnections(voiceConnection.joinConfig.group)?.delete(voiceConnection.joinConfig.guildId);\n}\n\nexport function trackVoiceConnection(voiceConnection: VoiceConnection) {\n\treturn getOrCreateGroup(voiceConnection.joinConfig.group).set(voiceConnection.joinConfig.guildId, voiceConnection);\n}\n\n// Audio Players\n\n// Each audio packet is 20ms long\nconst FRAME_LENGTH = 20;\n\nlet audioCycleInterval: NodeJS.Timeout | undefined;\nlet nextTime = -1;\n\n/**\n * A list of created audio players that are still active and haven't been destroyed.\n */\nconst audioPlayers: AudioPlayer[] = [];\n\n/**\n * Called roughly every 20 milliseconds. Dispatches audio from all players, and then gets the players to prepare\n * the next audio frame.\n */\nfunction audioCycleStep() {\n\tif (nextTime === -1) return;\n\n\tnextTime += FRAME_LENGTH;\n\tconst available = audioPlayers.filter((player) => player.checkPlayable());\n\n\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\tavailable.forEach((player) => player['_stepDispatch']());\n\n\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\tprepareNextAudioFrame(available);\n}\n\n/**\n * Recursively gets the players that have been passed as parameters to prepare audio frames that can be played\n * at the start of the next cycle.\n */\nfunction prepareNextAudioFrame(players: AudioPlayer[]) {\n\tconst nextPlayer = players.shift();\n\n\tif (!nextPlayer) {\n\t\tif (nextTime !== -1) {\n\t\t\taudioCycleInterval = setTimeout(() => audioCycleStep(), nextTime - Date.now());\n\t\t}\n\t\treturn;\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\tnextPlayer['_stepPrepare']();\n\n\t// setImmediate to avoid long audio player chains blocking other scheduled tasks\n\tsetImmediate(() => prepareNextAudioFrame(players));\n}\n\n/**\n * Checks whether or not the given audio player is being driven by the data store clock.\n *\n * @param target - The target to test for\n *\n * @returns `true` if it is being tracked, `false` otherwise\n */\nexport function hasAudioPlayer(target: AudioPlayer) {\n\treturn audioPlayers.includes(target);\n}\n\n/**\n * Adds an audio player to the data store tracking list, if it isn't already there.\n *\n * @param player - The player to track\n */\nexport function addAudioPlayer(player: AudioPlayer) {\n\tif (hasAudioPlayer(player)) return player;\n\taudioPlayers.push(player);\n\tif (audioPlayers.length === 1) {\n\t\tnextTime = Date.now();\n\t\tsetImmediate(() => audioCycleStep());\n\t}\n\treturn player;\n}\n\n/**\n * Removes an audio player from the data store tracking list, if it is present there.\n */\nexport function deleteAudioPlayer(player: AudioPlayer) {\n\tconst index = audioPlayers.indexOf(player);\n\tif (index === -1) return;\n\taudioPlayers.splice(index, 1);\n\tif (audioPlayers.length === 0) {\n\t\tnextTime = -1;\n\t\tif (typeof audioCycleInterval !== 'undefined') clearTimeout(audioCycleInterval);\n\t}\n}\n","/* eslint-disable @typescript-eslint/method-signature-style */\nimport { EventEmitter } from 'node:events';\nimport { VoiceOpcodes } from 'discord-api-types/voice/v4';\nimport type { CloseEvent } from 'ws';\nimport { VoiceUDPSocket } from './VoiceUDPSocket';\nimport { VoiceWebSocket } from './VoiceWebSocket';\nimport * as secretbox from '../util/Secretbox';\nimport { noop } from '../util/util';\n\n// The number of audio channels required by Discord\nconst CHANNELS = 2;\nconst TIMESTAMP_INC = (48000 / 100) * CHANNELS;\nconst MAX_NONCE_SIZE = 2 ** 32 - 1;\n\nexport const SUPPORTED_ENCRYPTION_MODES = ['xsalsa20_poly1305_lite', 'xsalsa20_poly1305_suffix', 'xsalsa20_poly1305'];\n\n/**\n * The different statuses that a networking instance can hold. The order\n * of the states between OpeningWs and Ready is chronological (first the\n * instance enters OpeningWs, then it enters Identifying etc.)\n */\nexport enum NetworkingStatusCode {\n\tOpeningWs,\n\tIdentifying,\n\tUdpHandshaking,\n\tSelectingProtocol,\n\tReady,\n\tResuming,\n\tClosed,\n}\n\n/**\n * The initial Networking state. Instances will be in this state when a WebSocket connection to a Discord\n * voice gateway is being opened.\n */\nexport interface NetworkingOpeningWsState {\n\tcode: NetworkingStatusCode.OpeningWs;\n\tws: VoiceWebSocket;\n\tconnectionOptions: ConnectionOptions;\n}\n\n/**\n * The state that a Networking instance will be in when it is attempting to authorize itself.\n */\nexport interface NetworkingIdentifyingState {\n\tcode: NetworkingStatusCode.Identifying;\n\tws: VoiceWebSocket;\n\tconnectionOptions: ConnectionOptions;\n}\n\n/**\n * The state that a Networking instance will be in when opening a UDP connection to the IP and port provided\n * by Discord, as well as performing IP discovery.\n */\nexport interface NetworkingUdpHandshakingState {\n\tcode: NetworkingStatusCode.UdpHandshaking;\n\tws: VoiceWebSocket;\n\tudp: VoiceUDPSocket;\n\tconnectionOptions: ConnectionOptions;\n\tconnectionData: Pick;\n}\n\n/**\n * The state that a Networking instance will be in when selecting an encryption protocol for audio packets.\n */\nexport interface NetworkingSelectingProtocolState {\n\tcode: NetworkingStatusCode.SelectingProtocol;\n\tws: VoiceWebSocket;\n\tudp: VoiceUDPSocket;\n\tconnectionOptions: ConnectionOptions;\n\tconnectionData: Pick;\n}\n\n/**\n * The state that a Networking instance will be in when it has a fully established connection to a Discord\n * voice server.\n */\nexport interface NetworkingReadyState {\n\tcode: NetworkingStatusCode.Ready;\n\tws: VoiceWebSocket;\n\tudp: VoiceUDPSocket;\n\tconnectionOptions: ConnectionOptions;\n\tconnectionData: ConnectionData;\n\tpreparedPacket?: Buffer;\n}\n\n/**\n * The state that a Networking instance will be in when its connection has been dropped unexpectedly, and it\n * is attempting to resume an existing session.\n */\nexport interface NetworkingResumingState {\n\tcode: NetworkingStatusCode.Resuming;\n\tws: VoiceWebSocket;\n\tudp: VoiceUDPSocket;\n\tconnectionOptions: ConnectionOptions;\n\tconnectionData: ConnectionData;\n\tpreparedPacket?: Buffer;\n}\n\n/**\n * The state that a Networking instance will be in when it has been destroyed. It cannot be recovered from this\n * state.\n */\nexport interface NetworkingClosedState {\n\tcode: NetworkingStatusCode.Closed;\n}\n\n/**\n * The various states that a networking instance can be in.\n */\nexport type NetworkingState =\n\t| NetworkingOpeningWsState\n\t| NetworkingIdentifyingState\n\t| NetworkingUdpHandshakingState\n\t| NetworkingSelectingProtocolState\n\t| NetworkingReadyState\n\t| NetworkingResumingState\n\t| NetworkingClosedState;\n\n/**\n * Details required to connect to the Discord voice gateway. These details\n * are first received on the main bot gateway, in the form of VOICE_SERVER_UPDATE\n * and VOICE_STATE_UPDATE packets.\n */\ninterface ConnectionOptions {\n\tserverId: string;\n\tuserId: string;\n\tsessionId: string;\n\ttoken: string;\n\tendpoint: string;\n}\n\n/**\n * Information about the current connection, e.g. which encryption mode is to be used on\n * the connection, timing information for playback of streams.\n */\nexport interface ConnectionData {\n\tssrc: number;\n\tencryptionMode: string;\n\tsecretKey: Uint8Array;\n\tsequence: number;\n\ttimestamp: number;\n\tpacketsPlayed: number;\n\tnonce: number;\n\tnonceBuffer: Buffer;\n\tspeaking: boolean;\n}\n\n/**\n * An empty buffer that is reused in packet encryption by many different networking instances.\n */\nconst nonce = Buffer.alloc(24);\n\nexport interface Networking extends EventEmitter {\n\t/**\n\t * Debug event for Networking.\n\t *\n\t * @event\n\t */\n\ton(event: 'debug', listener: (message: string) => void): this;\n\ton(event: 'error', listener: (error: Error) => void): this;\n\ton(event: 'stateChange', listener: (oldState: NetworkingState, newState: NetworkingState) => void): this;\n\ton(event: 'close', listener: (code: number) => void): this;\n}\n\n/**\n * Stringifies a NetworkingState.\n *\n * @param state - The state to stringify\n */\nfunction stringifyState(state: NetworkingState) {\n\treturn JSON.stringify({\n\t\t...state,\n\t\tws: Reflect.has(state, 'ws'),\n\t\tudp: Reflect.has(state, 'udp'),\n\t});\n}\n\n/**\n * Chooses an encryption mode from a list of given options. Chooses the most preferred option.\n *\n * @param options - The available encryption options\n */\nfunction chooseEncryptionMode(options: string[]): string {\n\tconst option = options.find((option) => SUPPORTED_ENCRYPTION_MODES.includes(option));\n\tif (!option) {\n\t\tthrow new Error(`No compatible encryption modes. Available include: ${options.join(', ')}`);\n\t}\n\treturn option;\n}\n\n/**\n * Returns a random number that is in the range of n bits.\n *\n * @param n - The number of bits\n */\nfunction randomNBit(n: number) {\n\treturn Math.floor(Math.random() * 2 ** n);\n}\n\n/**\n * Manages the networking required to maintain a voice connection and dispatch audio packets\n */\nexport class Networking extends EventEmitter {\n\tprivate _state: NetworkingState;\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: null | ((message: string) => void);\n\n\t/**\n\t * Creates a new Networking instance.\n\t */\n\tpublic constructor(options: ConnectionOptions, debug: boolean) {\n\t\tsuper();\n\n\t\tthis.onWsOpen = this.onWsOpen.bind(this);\n\t\tthis.onChildError = this.onChildError.bind(this);\n\t\tthis.onWsPacket = this.onWsPacket.bind(this);\n\t\tthis.onWsClose = this.onWsClose.bind(this);\n\t\tthis.onWsDebug = this.onWsDebug.bind(this);\n\t\tthis.onUdpDebug = this.onUdpDebug.bind(this);\n\t\tthis.onUdpClose = this.onUdpClose.bind(this);\n\n\t\tthis.debug = debug ? (message: string) => this.emit('debug', message) : null;\n\n\t\tthis._state = {\n\t\t\tcode: NetworkingStatusCode.OpeningWs,\n\t\t\tws: this.createWebSocket(options.endpoint),\n\t\t\tconnectionOptions: options,\n\t\t};\n\t}\n\n\t/**\n\t * Destroys the Networking instance, transitioning it into the Closed state.\n\t */\n\tpublic destroy() {\n\t\tthis.state = {\n\t\t\tcode: NetworkingStatusCode.Closed,\n\t\t};\n\t}\n\n\t/**\n\t * The current state of the networking instance.\n\t */\n\tpublic get state(): NetworkingState {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * Sets a new state for the networking instance, performing clean-up operations where necessary.\n\t */\n\tpublic set state(newState: NetworkingState) {\n\t\tconst oldWs = Reflect.get(this._state, 'ws') as VoiceWebSocket | undefined;\n\t\tconst newWs = Reflect.get(newState, 'ws') as VoiceWebSocket | undefined;\n\t\tif (oldWs && oldWs !== newWs) {\n\t\t\t// The old WebSocket is being freed - remove all handlers from it\n\t\t\toldWs.off('debug', this.onWsDebug);\n\t\t\toldWs.on('error', noop);\n\t\t\toldWs.off('error', this.onChildError);\n\t\t\toldWs.off('open', this.onWsOpen);\n\t\t\toldWs.off('packet', this.onWsPacket);\n\t\t\toldWs.off('close', this.onWsClose);\n\t\t\toldWs.destroy();\n\t\t}\n\n\t\tconst oldUdp = Reflect.get(this._state, 'udp') as VoiceUDPSocket | undefined;\n\t\tconst newUdp = Reflect.get(newState, 'udp') as VoiceUDPSocket | undefined;\n\n\t\tif (oldUdp && oldUdp !== newUdp) {\n\t\t\toldUdp.on('error', noop);\n\t\t\toldUdp.off('error', this.onChildError);\n\t\t\toldUdp.off('close', this.onUdpClose);\n\t\t\toldUdp.off('debug', this.onUdpDebug);\n\t\t\toldUdp.destroy();\n\t\t}\n\n\t\tconst oldState = this._state;\n\t\tthis._state = newState;\n\t\tthis.emit('stateChange', oldState, newState);\n\n\t\tthis.debug?.(`state change:\\nfrom ${stringifyState(oldState)}\\nto ${stringifyState(newState)}`);\n\t}\n\n\t/**\n\t * Creates a new WebSocket to a Discord Voice gateway.\n\t *\n\t * @param endpoint - The endpoint to connect to\n\t * @param debug - Whether to enable debug logging\n\t */\n\tprivate createWebSocket(endpoint: string) {\n\t\tconst ws = new VoiceWebSocket(`wss://${endpoint}?v=4`, Boolean(this.debug));\n\n\t\tws.on('error', this.onChildError);\n\t\tws.once('open', this.onWsOpen);\n\t\tws.on('packet', this.onWsPacket);\n\t\tws.once('close', this.onWsClose);\n\t\tws.on('debug', this.onWsDebug);\n\n\t\treturn ws;\n\t}\n\n\t/**\n\t * Propagates errors from the children VoiceWebSocket and VoiceUDPSocket.\n\t *\n\t * @param error - The error that was emitted by a child\n\t */\n\tprivate onChildError(error: Error) {\n\t\tthis.emit('error', error);\n\t}\n\n\t/**\n\t * Called when the WebSocket opens. Depending on the state that the instance is in,\n\t * it will either identify with a new session, or it will attempt to resume an existing session.\n\t */\n\tprivate onWsOpen() {\n\t\tif (this.state.code === NetworkingStatusCode.OpeningWs) {\n\t\t\tconst packet = {\n\t\t\t\top: VoiceOpcodes.Identify,\n\t\t\t\td: {\n\t\t\t\t\tserver_id: this.state.connectionOptions.serverId,\n\t\t\t\t\tuser_id: this.state.connectionOptions.userId,\n\t\t\t\t\tsession_id: this.state.connectionOptions.sessionId,\n\t\t\t\t\ttoken: this.state.connectionOptions.token,\n\t\t\t\t},\n\t\t\t};\n\t\t\tthis.state.ws.sendPacket(packet);\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Identifying,\n\t\t\t};\n\t\t} else if (this.state.code === NetworkingStatusCode.Resuming) {\n\t\t\tconst packet = {\n\t\t\t\top: VoiceOpcodes.Resume,\n\t\t\t\td: {\n\t\t\t\t\tserver_id: this.state.connectionOptions.serverId,\n\t\t\t\t\tsession_id: this.state.connectionOptions.sessionId,\n\t\t\t\t\ttoken: this.state.connectionOptions.token,\n\t\t\t\t},\n\t\t\t};\n\t\t\tthis.state.ws.sendPacket(packet);\n\t\t}\n\t}\n\n\t/**\n\t * Called when the WebSocket closes. Based on the reason for closing (given by the code parameter),\n\t * the instance will either attempt to resume, or enter the closed state and emit a 'close' event\n\t * with the close code, allowing the user to decide whether or not they would like to reconnect.\n\t *\n\t * @param code - The close code\n\t */\n\tprivate onWsClose({ code }: CloseEvent) {\n\t\tconst canResume = code === 4015 || code < 4000;\n\t\tif (canResume && this.state.code === NetworkingStatusCode.Ready) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Resuming,\n\t\t\t\tws: this.createWebSocket(this.state.connectionOptions.endpoint),\n\t\t\t};\n\t\t} else if (this.state.code !== NetworkingStatusCode.Closed) {\n\t\t\tthis.destroy();\n\t\t\tthis.emit('close', code);\n\t\t}\n\t}\n\n\t/**\n\t * Called when the UDP socket has closed itself if it has stopped receiving replies from Discord.\n\t */\n\tprivate onUdpClose() {\n\t\tif (this.state.code === NetworkingStatusCode.Ready) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Resuming,\n\t\t\t\tws: this.createWebSocket(this.state.connectionOptions.endpoint),\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Called when a packet is received on the connection's WebSocket.\n\t *\n\t * @param packet - The received packet\n\t */\n\tprivate onWsPacket(packet: any) {\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\tif (packet.op === VoiceOpcodes.Hello && this.state.code !== NetworkingStatusCode.Closed) {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access\n\t\t\tthis.state.ws.setHeartbeatInterval(packet.d.heartbeat_interval);\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t} else if (packet.op === VoiceOpcodes.Ready && this.state.code === NetworkingStatusCode.Identifying) {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\t\tconst { ip, port, ssrc, modes } = packet.d;\n\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\t\tconst udp = new VoiceUDPSocket({ ip, port });\n\t\t\tudp.on('error', this.onChildError);\n\t\t\tudp.on('debug', this.onUdpDebug);\n\t\t\tudp.once('close', this.onUdpClose);\n\t\t\tudp\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\t\t\t.performIPDiscovery(ssrc)\n\t\t\t\t.then((localConfig) => {\n\t\t\t\t\tif (this.state.code !== NetworkingStatusCode.UdpHandshaking) return;\n\t\t\t\t\tthis.state.ws.sendPacket({\n\t\t\t\t\t\top: VoiceOpcodes.SelectProtocol,\n\t\t\t\t\t\td: {\n\t\t\t\t\t\t\tprotocol: 'udp',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\taddress: localConfig.ip,\n\t\t\t\t\t\t\t\tport: localConfig.port,\n\t\t\t\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\t\t\t\t\t\t\tmode: chooseEncryptionMode(modes),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tthis.state = {\n\t\t\t\t\t\t...this.state,\n\t\t\t\t\t\tcode: NetworkingStatusCode.SelectingProtocol,\n\t\t\t\t\t};\n\t\t\t\t})\n\t\t\t\t.catch((error: Error) => this.emit('error', error));\n\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.UdpHandshaking,\n\t\t\t\tudp,\n\t\t\t\tconnectionData: {\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\t\t\t\tssrc,\n\t\t\t\t},\n\t\t\t};\n\t\t} else if (\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\tpacket.op === VoiceOpcodes.SessionDescription &&\n\t\t\tthis.state.code === NetworkingStatusCode.SelectingProtocol\n\t\t) {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\t\tconst { mode: encryptionMode, secret_key: secretKey } = packet.d;\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Ready,\n\t\t\t\tconnectionData: {\n\t\t\t\t\t...this.state.connectionData,\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\t\t\t\tencryptionMode,\n\t\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\t\t\t\tsecretKey: new Uint8Array(secretKey),\n\t\t\t\t\tsequence: randomNBit(16),\n\t\t\t\t\ttimestamp: randomNBit(32),\n\t\t\t\t\tnonce: 0,\n\t\t\t\t\tnonceBuffer: Buffer.alloc(24),\n\t\t\t\t\tspeaking: false,\n\t\t\t\t\tpacketsPlayed: 0,\n\t\t\t\t},\n\t\t\t};\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t} else if (packet.op === VoiceOpcodes.Resumed && this.state.code === NetworkingStatusCode.Resuming) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Ready,\n\t\t\t};\n\t\t\tthis.state.connectionData.speaking = false;\n\t\t}\n\t}\n\n\t/**\n\t * Propagates debug messages from the child WebSocket.\n\t *\n\t * @param message - The emitted debug message\n\t */\n\tprivate onWsDebug(message: string) {\n\t\tthis.debug?.(`[WS] ${message}`);\n\t}\n\n\t/**\n\t * Propagates debug messages from the child UDPSocket.\n\t *\n\t * @param message - The emitted debug message\n\t */\n\tprivate onUdpDebug(message: string) {\n\t\tthis.debug?.(`[UDP] ${message}`);\n\t}\n\n\t/**\n\t * Prepares an Opus packet for playback. This includes attaching metadata to it and encrypting it.\n\t * It will be stored within the instance, and can be played by dispatchAudio()\n\t *\n\t * @remarks\n\t * Calling this method while there is already a prepared audio packet that has not yet been dispatched\n\t * will overwrite the existing audio packet. This should be avoided.\n\t *\n\t * @param opusPacket - The Opus packet to encrypt\n\t *\n\t * @returns The audio packet that was prepared\n\t */\n\tpublic prepareAudioPacket(opusPacket: Buffer) {\n\t\tconst state = this.state;\n\t\tif (state.code !== NetworkingStatusCode.Ready) return;\n\t\tstate.preparedPacket = this.createAudioPacket(opusPacket, state.connectionData);\n\t\treturn state.preparedPacket;\n\t}\n\n\t/**\n\t * Dispatches the audio packet previously prepared by prepareAudioPacket(opusPacket). The audio packet\n\t * is consumed and cannot be dispatched again.\n\t */\n\tpublic dispatchAudio() {\n\t\tconst state = this.state;\n\t\tif (state.code !== NetworkingStatusCode.Ready) return false;\n\t\tif (typeof state.preparedPacket !== 'undefined') {\n\t\t\tthis.playAudioPacket(state.preparedPacket);\n\t\t\tstate.preparedPacket = undefined;\n\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\t/**\n\t * Plays an audio packet, updating timing metadata used for playback.\n\t *\n\t * @param audioPacket - The audio packet to play\n\t */\n\tprivate playAudioPacket(audioPacket: Buffer) {\n\t\tconst state = this.state;\n\t\tif (state.code !== NetworkingStatusCode.Ready) return;\n\t\tconst { connectionData } = state;\n\t\tconnectionData.packetsPlayed++;\n\t\tconnectionData.sequence++;\n\t\tconnectionData.timestamp += TIMESTAMP_INC;\n\t\tif (connectionData.sequence >= 2 ** 16) connectionData.sequence = 0;\n\t\tif (connectionData.timestamp >= 2 ** 32) connectionData.timestamp = 0;\n\t\tthis.setSpeaking(true);\n\t\tstate.udp.send(audioPacket);\n\t}\n\n\t/**\n\t * Sends a packet to the voice gateway indicating that the client has start/stopped sending\n\t * audio.\n\t *\n\t * @param speaking - Whether or not the client should be shown as speaking\n\t */\n\tpublic setSpeaking(speaking: boolean) {\n\t\tconst state = this.state;\n\t\tif (state.code !== NetworkingStatusCode.Ready) return;\n\t\tif (state.connectionData.speaking === speaking) return;\n\t\tstate.connectionData.speaking = speaking;\n\t\tstate.ws.sendPacket({\n\t\t\top: VoiceOpcodes.Speaking,\n\t\t\td: {\n\t\t\t\tspeaking: speaking ? 1 : 0,\n\t\t\t\tdelay: 0,\n\t\t\t\tssrc: state.connectionData.ssrc,\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Creates a new audio packet from an Opus packet. This involves encrypting the packet,\n\t * then prepending a header that includes metadata.\n\t *\n\t * @param opusPacket - The Opus packet to prepare\n\t * @param connectionData - The current connection data of the instance\n\t */\n\tprivate createAudioPacket(opusPacket: Buffer, connectionData: ConnectionData) {\n\t\tconst packetBuffer = Buffer.alloc(12);\n\t\tpacketBuffer[0] = 0x80;\n\t\tpacketBuffer[1] = 0x78;\n\n\t\tconst { sequence, timestamp, ssrc } = connectionData;\n\n\t\tpacketBuffer.writeUIntBE(sequence, 2, 2);\n\t\tpacketBuffer.writeUIntBE(timestamp, 4, 4);\n\t\tpacketBuffer.writeUIntBE(ssrc, 8, 4);\n\n\t\tpacketBuffer.copy(nonce, 0, 0, 12);\n\t\treturn Buffer.concat([packetBuffer, ...this.encryptOpusPacket(opusPacket, connectionData)]);\n\t}\n\n\t/**\n\t * Encrypts an Opus packet using the format agreed upon by the instance and Discord.\n\t *\n\t * @param opusPacket - The Opus packet to encrypt\n\t * @param connectionData - The current connection data of the instance\n\t */\n\tprivate encryptOpusPacket(opusPacket: Buffer, connectionData: ConnectionData) {\n\t\tconst { secretKey, encryptionMode } = connectionData;\n\n\t\tif (encryptionMode === 'xsalsa20_poly1305_lite') {\n\t\t\tconnectionData.nonce++;\n\t\t\tif (connectionData.nonce > MAX_NONCE_SIZE) connectionData.nonce = 0;\n\t\t\tconnectionData.nonceBuffer.writeUInt32BE(connectionData.nonce, 0);\n\t\t\treturn [\n\t\t\t\tsecretbox.methods.close(opusPacket, connectionData.nonceBuffer, secretKey),\n\t\t\t\tconnectionData.nonceBuffer.slice(0, 4),\n\t\t\t];\n\t\t} else if (encryptionMode === 'xsalsa20_poly1305_suffix') {\n\t\t\tconst random = secretbox.methods.random(24, connectionData.nonceBuffer);\n\t\t\treturn [secretbox.methods.close(opusPacket, random, secretKey), random];\n\t\t}\n\t\treturn [secretbox.methods.close(opusPacket, nonce, secretKey)];\n\t}\n}\n","/* eslint-disable @typescript-eslint/method-signature-style */\nimport { createSocket, Socket } from 'node:dgram';\nimport { EventEmitter } from 'node:events';\nimport { isIPv4 } from 'node:net';\n\n/**\n * Stores an IP address and port. Used to store socket details for the local client as well as\n * for Discord.\n */\nexport interface SocketConfig {\n\tip: string;\n\tport: number;\n}\n\ninterface KeepAlive {\n\tvalue: number;\n\ttimestamp: number;\n}\n\n/**\n * Parses the response from Discord to aid with local IP discovery.\n *\n * @param message - The received message\n */\nexport function parseLocalPacket(message: Buffer): SocketConfig {\n\tconst packet = Buffer.from(message);\n\n\tconst ip = packet.slice(8, packet.indexOf(0, 8)).toString('utf-8');\n\n\tif (!isIPv4(ip)) {\n\t\tthrow new Error('Malformed IP address');\n\t}\n\n\tconst port = packet.readUInt16BE(packet.length - 2);\n\n\treturn { ip, port };\n}\n\n/**\n * The interval in milliseconds at which keep alive datagrams are sent.\n */\nconst KEEP_ALIVE_INTERVAL = 5e3;\n\n/**\n * The maximum number of keep alive packets which can be missed.\n */\nconst KEEP_ALIVE_LIMIT = 12;\n\n/**\n * The maximum value of the keep alive counter.\n */\nconst MAX_COUNTER_VALUE = 2 ** 32 - 1;\n\nexport interface VoiceUDPSocket extends EventEmitter {\n\ton(event: 'error', listener: (error: Error) => void): this;\n\ton(event: 'close', listener: () => void): this;\n\ton(event: 'debug', listener: (message: string) => void): this;\n\ton(event: 'message', listener: (message: Buffer) => void): this;\n}\n\n/**\n * Manages the UDP networking for a voice connection.\n */\nexport class VoiceUDPSocket extends EventEmitter {\n\t/**\n\t * The underlying network Socket for the VoiceUDPSocket.\n\t */\n\tprivate readonly socket: Socket;\n\n\t/**\n\t * The socket details for Discord (remote)\n\t */\n\tprivate readonly remote: SocketConfig;\n\n\t/**\n\t * A list of keep alives that are waiting to be acknowledged.\n\t */\n\tprivate readonly keepAlives: KeepAlive[];\n\n\t/**\n\t * The counter used in the keep alive mechanism.\n\t */\n\tprivate keepAliveCounter = 0;\n\n\t/**\n\t * The buffer used to write the keep alive counter into.\n\t */\n\tprivate readonly keepAliveBuffer: Buffer;\n\n\t/**\n\t * The Node.js interval for the keep-alive mechanism.\n\t */\n\tprivate readonly keepAliveInterval: NodeJS.Timeout;\n\n\t/**\n\t * The time taken to receive a response to keep alive messages.\n\t */\n\tpublic ping?: number;\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: null | ((message: string) => void);\n\n\t/**\n\t * Creates a new VoiceUDPSocket.\n\t *\n\t * @param remote - Details of the remote socket\n\t */\n\tpublic constructor(remote: SocketConfig, debug = false) {\n\t\tsuper();\n\t\tthis.socket = createSocket('udp4');\n\t\tthis.socket.on('error', (error: Error) => this.emit('error', error));\n\t\tthis.socket.on('message', (buffer: Buffer) => this.onMessage(buffer));\n\t\tthis.socket.on('close', () => this.emit('close'));\n\t\tthis.remote = remote;\n\t\tthis.keepAlives = [];\n\t\tthis.keepAliveBuffer = Buffer.alloc(8);\n\t\tthis.keepAliveInterval = setInterval(() => this.keepAlive(), KEEP_ALIVE_INTERVAL);\n\t\tsetImmediate(() => this.keepAlive());\n\n\t\tthis.debug = debug ? (message: string) => this.emit('debug', message) : null;\n\t}\n\n\t/**\n\t * Called when a message is received on the UDP socket.\n\t *\n\t * @param buffer - The received buffer\n\t */\n\tprivate onMessage(buffer: Buffer): void {\n\t\t// Handle keep alive message\n\t\tif (buffer.length === 8) {\n\t\t\tconst counter = buffer.readUInt32LE(0);\n\t\t\tconst index = this.keepAlives.findIndex(({ value }) => value === counter);\n\t\t\tif (index === -1) return;\n\t\t\tthis.ping = Date.now() - this.keepAlives[index]!.timestamp;\n\t\t\t// Delete all keep alives up to and including the received one\n\t\t\tthis.keepAlives.splice(0, index);\n\t\t}\n\t\t// Propagate the message\n\t\tthis.emit('message', buffer);\n\t}\n\n\t/**\n\t * Called at a regular interval to check whether we are still able to send datagrams to Discord.\n\t */\n\tprivate keepAlive() {\n\t\tif (this.keepAlives.length >= KEEP_ALIVE_LIMIT) {\n\t\t\tthis.debug?.('UDP socket has not received enough responses from Discord - closing socket');\n\t\t\tthis.destroy();\n\t\t\treturn;\n\t\t}\n\n\t\tthis.keepAliveBuffer.writeUInt32LE(this.keepAliveCounter, 0);\n\t\tthis.send(this.keepAliveBuffer);\n\t\tthis.keepAlives.push({\n\t\t\tvalue: this.keepAliveCounter,\n\t\t\ttimestamp: Date.now(),\n\t\t});\n\t\tthis.keepAliveCounter++;\n\t\tif (this.keepAliveCounter > MAX_COUNTER_VALUE) {\n\t\t\tthis.keepAliveCounter = 0;\n\t\t}\n\t}\n\n\t/**\n\t * Sends a buffer to Discord.\n\t *\n\t * @param buffer - The buffer to send\n\t */\n\tpublic send(buffer: Buffer) {\n\t\treturn this.socket.send(buffer, this.remote.port, this.remote.ip);\n\t}\n\n\t/**\n\t * Closes the socket, the instance will not be able to be reused.\n\t */\n\tpublic destroy() {\n\t\ttry {\n\t\t\tthis.socket.close();\n\t\t} catch {}\n\t\tclearInterval(this.keepAliveInterval);\n\t}\n\n\t/**\n\t * Performs IP discovery to discover the local address and port to be used for the voice connection.\n\t *\n\t * @param ssrc - The SSRC received from Discord\n\t */\n\tpublic performIPDiscovery(ssrc: number): Promise {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst listener = (message: Buffer) => {\n\t\t\t\ttry {\n\t\t\t\t\tif (message.readUInt16BE(0) !== 2) return;\n\t\t\t\t\tconst packet = parseLocalPacket(message);\n\t\t\t\t\tthis.socket.off('message', listener);\n\t\t\t\t\tresolve(packet);\n\t\t\t\t} catch {}\n\t\t\t};\n\n\t\t\tthis.socket.on('message', listener);\n\t\t\tthis.socket.once('close', () => reject(new Error('Cannot perform IP discovery - socket closed')));\n\n\t\t\tconst discoveryBuffer = Buffer.alloc(74);\n\n\t\t\tdiscoveryBuffer.writeUInt16BE(1, 0);\n\t\t\tdiscoveryBuffer.writeUInt16BE(70, 2);\n\t\t\tdiscoveryBuffer.writeUInt32BE(ssrc, 4);\n\t\t\tthis.send(discoveryBuffer);\n\t\t});\n\t}\n}\n","/* eslint-disable @typescript-eslint/method-signature-style */\nimport { EventEmitter } from 'node:events';\nimport { VoiceOpcodes } from 'discord-api-types/voice/v4';\nimport WebSocket, { MessageEvent } from 'ws';\n\nexport interface VoiceWebSocket extends EventEmitter {\n\ton(event: 'error', listener: (error: Error) => void): this;\n\ton(event: 'open', listener: (event: WebSocket.Event) => void): this;\n\ton(event: 'close', listener: (event: WebSocket.CloseEvent) => void): this;\n\t/**\n\t * Debug event for VoiceWebSocket.\n\t *\n\t * @event\n\t */\n\ton(event: 'debug', listener: (message: string) => void): this;\n\t/**\n\t * Packet event.\n\t *\n\t * @event\n\t */\n\ton(event: 'packet', listener: (packet: any) => void): this;\n}\n\n/**\n * An extension of the WebSocket class to provide helper functionality when interacting\n * with the Discord Voice gateway.\n */\nexport class VoiceWebSocket extends EventEmitter {\n\t/**\n\t * The current heartbeat interval, if any.\n\t */\n\tprivate heartbeatInterval?: NodeJS.Timeout;\n\n\t/**\n\t * The time (milliseconds since UNIX epoch) that the last heartbeat acknowledgement packet was received.\n\t * This is set to 0 if an acknowledgement packet hasn't been received yet.\n\t */\n\tprivate lastHeartbeatAck: number;\n\n\t/**\n\t * The time (milliseconds since UNIX epoch) that the last heartbeat was sent. This is set to 0 if a heartbeat\n\t * hasn't been sent yet.\n\t */\n\tprivate lastHeartbeatSend: number;\n\n\t/**\n\t * The number of consecutively missed heartbeats.\n\t */\n\tprivate missedHeartbeats = 0;\n\n\t/**\n\t * The last recorded ping.\n\t */\n\tpublic ping?: number;\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: null | ((message: string) => void);\n\n\t/**\n\t * The underlying WebSocket of this wrapper.\n\t */\n\tprivate readonly ws: WebSocket;\n\n\t/**\n\t * Creates a new VoiceWebSocket.\n\t *\n\t * @param address - The address to connect to\n\t */\n\tpublic constructor(address: string, debug: boolean) {\n\t\tsuper();\n\t\tthis.ws = new WebSocket(address);\n\t\tthis.ws.onmessage = (e) => this.onMessage(e);\n\t\tthis.ws.onopen = (e) => this.emit('open', e);\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\tthis.ws.onerror = (e: Error | WebSocket.ErrorEvent) => this.emit('error', e instanceof Error ? e : e.error);\n\t\tthis.ws.onclose = (e) => this.emit('close', e);\n\n\t\tthis.lastHeartbeatAck = 0;\n\t\tthis.lastHeartbeatSend = 0;\n\n\t\tthis.debug = debug ? (message: string) => this.emit('debug', message) : null;\n\t}\n\n\t/**\n\t * Destroys the VoiceWebSocket. The heartbeat interval is cleared, and the connection is closed.\n\t */\n\tpublic destroy() {\n\t\ttry {\n\t\t\tthis.debug?.('destroyed');\n\t\t\tthis.setHeartbeatInterval(-1);\n\t\t\tthis.ws.close(1000);\n\t\t} catch (error) {\n\t\t\tconst e = error as Error;\n\t\t\tthis.emit('error', e);\n\t\t}\n\t}\n\n\t/**\n\t * Handles message events on the WebSocket. Attempts to JSON parse the messages and emit them\n\t * as packets.\n\t *\n\t * @param event - The message event\n\t */\n\tpublic onMessage(event: MessageEvent) {\n\t\tif (typeof event.data !== 'string') return;\n\n\t\tthis.debug?.(`<< ${event.data}`);\n\n\t\tlet packet: any;\n\t\ttry {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\t\tpacket = JSON.parse(event.data);\n\t\t} catch (error) {\n\t\t\tconst e = error as Error;\n\t\t\tthis.emit('error', e);\n\t\t\treturn;\n\t\t}\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\tif (packet.op === VoiceOpcodes.HeartbeatAck) {\n\t\t\tthis.lastHeartbeatAck = Date.now();\n\t\t\tthis.missedHeartbeats = 0;\n\t\t\tthis.ping = this.lastHeartbeatAck - this.lastHeartbeatSend;\n\t\t}\n\n\t\tthis.emit('packet', packet);\n\t}\n\n\t/**\n\t * Sends a JSON-stringifiable packet over the WebSocket.\n\t *\n\t * @param packet - The packet to send\n\t */\n\tpublic sendPacket(packet: any) {\n\t\ttry {\n\t\t\tconst stringified = JSON.stringify(packet);\n\t\t\tthis.debug?.(`>> ${stringified}`);\n\t\t\treturn this.ws.send(stringified);\n\t\t} catch (error) {\n\t\t\tconst e = error as Error;\n\t\t\tthis.emit('error', e);\n\t\t}\n\t}\n\n\t/**\n\t * Sends a heartbeat over the WebSocket.\n\t */\n\tprivate sendHeartbeat() {\n\t\tthis.lastHeartbeatSend = Date.now();\n\t\tthis.missedHeartbeats++;\n\t\tconst nonce = this.lastHeartbeatSend;\n\t\treturn this.sendPacket({\n\t\t\top: VoiceOpcodes.Heartbeat,\n\t\t\td: nonce,\n\t\t});\n\t}\n\n\t/**\n\t * Sets/clears an interval to send heartbeats over the WebSocket.\n\t *\n\t * @param ms - The interval in milliseconds. If negative, the interval will be unset\n\t */\n\tpublic setHeartbeatInterval(ms: number) {\n\t\tif (typeof this.heartbeatInterval !== 'undefined') clearInterval(this.heartbeatInterval);\n\t\tif (ms > 0) {\n\t\t\tthis.heartbeatInterval = setInterval(() => {\n\t\t\t\tif (this.lastHeartbeatSend !== 0 && this.missedHeartbeats >= 3) {\n\t\t\t\t\t// Missed too many heartbeats - disconnect\n\t\t\t\t\tthis.ws.close();\n\t\t\t\t\tthis.setHeartbeatInterval(-1);\n\t\t\t\t}\n\t\t\t\tthis.sendHeartbeat();\n\t\t\t}, ms);\n\t\t}\n\t}\n}\n","interface Methods {\n\topen: (buffer: Buffer, nonce: Buffer, secretKey: Uint8Array) => Buffer | null;\n\tclose: (opusPacket: Buffer, nonce: Buffer, secretKey: Uint8Array) => Buffer;\n\trandom: (bytes: number, nonce: Buffer) => Buffer;\n}\n\nconst libs = {\n\t'sodium-native': (sodium: any): Methods => ({\n\t\topen: (buffer: Buffer, nonce: Buffer, secretKey: Uint8Array) => {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n\t\t\tif (buffer) {\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\t\tconst output = Buffer.allocUnsafe(buffer.length - sodium.crypto_box_MACBYTES);\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n\t\t\t\tif (sodium.crypto_secretbox_open_easy(output, buffer, nonce, secretKey)) return output;\n\t\t\t}\n\t\t\treturn null;\n\t\t},\n\t\tclose: (opusPacket: Buffer, nonce: Buffer, secretKey: Uint8Array) => {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-argument, @typescript-eslint/restrict-plus-operands\n\t\t\tconst output = Buffer.allocUnsafe(opusPacket.length + sodium.crypto_box_MACBYTES);\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n\t\t\tsodium.crypto_secretbox_easy(output, opusPacket, nonce, secretKey);\n\t\t\treturn output;\n\t\t},\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\trandom: (n: number, buffer: Buffer = Buffer.allocUnsafe(n)) => {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n\t\t\tsodium.randombytes_buf(buffer);\n\t\t\treturn buffer;\n\t\t},\n\t}),\n\tsodium: (sodium: any): Methods => ({\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\topen: sodium.api.crypto_secretbox_open_easy,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\tclose: sodium.api.crypto_secretbox_easy,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\trandom: (n: number, buffer: Buffer = Buffer.allocUnsafe(n)) => {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-unsafe-call\n\t\t\tsodium.api.randombytes_buf(buffer);\n\t\t\treturn buffer;\n\t\t},\n\t}),\n\t'libsodium-wrappers': (sodium: any): Methods => ({\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\topen: sodium.crypto_secretbox_open_easy,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\tclose: sodium.crypto_secretbox_easy,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\trandom: sodium.randombytes_buf,\n\t}),\n\ttweetnacl: (tweetnacl: any): Methods => ({\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\topen: tweetnacl.secretbox.open,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\tclose: tweetnacl.secretbox,\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\trandom: tweetnacl.randomBytes,\n\t}),\n} as const;\n\nconst fallbackError = () => {\n\tthrow new Error(\n\t\t`Cannot play audio as no valid encryption package is installed.\n- Install sodium, libsodium-wrappers, or tweetnacl.\n- Use the generateDependencyReport() function for more information.\\n`,\n\t);\n};\n\nconst methods: Methods = {\n\topen: fallbackError,\n\tclose: fallbackError,\n\trandom: fallbackError,\n};\n\nvoid (async () => {\n\tfor (const libName of Object.keys(libs) as (keyof typeof libs)[]) {\n\t\ttry {\n\t\t\t// eslint-disable-next-line\n\t\t\tconst lib = require(libName);\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\tif (libName === 'libsodium-wrappers' && lib.ready) await lib.ready;\n\t\t\tObject.assign(methods, libs[libName](lib));\n\t\t\tbreak;\n\t\t} catch {}\n\t}\n})();\n\nexport { methods };\n","// eslint-disable-next-line @typescript-eslint/no-empty-function\nexport const noop = () => {};\n","import { VoiceOpcodes } from 'discord-api-types/voice/v4';\nimport {\n\tAudioReceiveStream,\n\tAudioReceiveStreamOptions,\n\tcreateDefaultAudioReceiveStreamOptions,\n} from './AudioReceiveStream';\nimport { SSRCMap } from './SSRCMap';\nimport { SpeakingMap } from './SpeakingMap';\nimport type { VoiceConnection } from '../VoiceConnection';\nimport type { ConnectionData } from '../networking/Networking';\nimport { methods } from '../util/Secretbox';\n\n/**\n * Attaches to a VoiceConnection, allowing you to receive audio packets from other\n * users that are speaking.\n *\n * @beta\n */\nexport class VoiceReceiver {\n\t/**\n\t * The attached connection of this receiver.\n\t */\n\tpublic readonly voiceConnection;\n\n\t/**\n\t * Maps SSRCs to Discord user ids.\n\t */\n\tpublic readonly ssrcMap: SSRCMap;\n\n\t/**\n\t * The current audio subscriptions of this receiver.\n\t */\n\tpublic readonly subscriptions: Map;\n\n\t/**\n\t * The connection data of the receiver.\n\t *\n\t * @internal\n\t */\n\tpublic connectionData: Partial;\n\n\t/**\n\t * The speaking map of the receiver.\n\t */\n\tpublic readonly speaking: SpeakingMap;\n\n\tpublic constructor(voiceConnection: VoiceConnection) {\n\t\tthis.voiceConnection = voiceConnection;\n\t\tthis.ssrcMap = new SSRCMap();\n\t\tthis.speaking = new SpeakingMap();\n\t\tthis.subscriptions = new Map();\n\t\tthis.connectionData = {};\n\n\t\tthis.onWsPacket = this.onWsPacket.bind(this);\n\t\tthis.onUdpMessage = this.onUdpMessage.bind(this);\n\t}\n\n\t/**\n\t * Called when a packet is received on the attached connection's WebSocket.\n\t *\n\t * @param packet - The received packet\n\t *\n\t * @internal\n\t */\n\tpublic onWsPacket(packet: any) {\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\tif (packet.op === VoiceOpcodes.ClientDisconnect && typeof packet.d?.user_id === 'string') {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-unsafe-member-access\n\t\t\tthis.ssrcMap.delete(packet.d.user_id);\n\t\t} else if (\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\tpacket.op === VoiceOpcodes.Speaking &&\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\ttypeof packet.d?.user_id === 'string' &&\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\ttypeof packet.d?.ssrc === 'number'\n\t\t) {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\t\tthis.ssrcMap.update({ userId: packet.d.user_id, audioSSRC: packet.d.ssrc });\n\t\t} else if (\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\tpacket.op === VoiceOpcodes.ClientConnect &&\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\ttypeof packet.d?.user_id === 'string' &&\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\t\ttypeof packet.d?.audio_ssrc === 'number'\n\t\t) {\n\t\t\tthis.ssrcMap.update({\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\t\t\tuserId: packet.d.user_id,\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\t\t\taudioSSRC: packet.d.audio_ssrc,\n\t\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access\n\t\t\t\tvideoSSRC: packet.d.video_ssrc === 0 ? undefined : packet.d.video_ssrc,\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate decrypt(buffer: Buffer, mode: string, nonce: Buffer, secretKey: Uint8Array) {\n\t\t// Choose correct nonce depending on encryption\n\t\tlet end;\n\t\tif (mode === 'xsalsa20_poly1305_lite') {\n\t\t\tbuffer.copy(nonce, 0, buffer.length - 4);\n\t\t\tend = buffer.length - 4;\n\t\t} else if (mode === 'xsalsa20_poly1305_suffix') {\n\t\t\tbuffer.copy(nonce, 0, buffer.length - 24);\n\t\t\tend = buffer.length - 24;\n\t\t} else {\n\t\t\tbuffer.copy(nonce, 0, 0, 12);\n\t\t}\n\n\t\t// Open packet\n\t\tconst decrypted = methods.open(buffer.slice(12, end), nonce, secretKey);\n\t\tif (!decrypted) return;\n\t\treturn Buffer.from(decrypted);\n\t}\n\n\t/**\n\t * Parses an audio packet, decrypting it to yield an Opus packet.\n\t *\n\t * @param buffer - The buffer to parse\n\t * @param mode - The encryption mode\n\t * @param nonce - The nonce buffer used by the connection for encryption\n\t * @param secretKey - The secret key used by the connection for encryption\n\t *\n\t * @returns The parsed Opus packet\n\t */\n\tprivate parsePacket(buffer: Buffer, mode: string, nonce: Buffer, secretKey: Uint8Array) {\n\t\tlet packet = this.decrypt(buffer, mode, nonce, secretKey);\n\t\tif (!packet) return;\n\n\t\t// Strip RTP Header Extensions (one-byte only)\n\t\tif (packet[0] === 0xbe && packet[1] === 0xde) {\n\t\t\tconst headerExtensionLength = packet.readUInt16BE(2);\n\t\t\tpacket = packet.subarray(4 + 4 * headerExtensionLength);\n\t\t}\n\n\t\treturn packet;\n\t}\n\n\t/**\n\t * Called when the UDP socket of the attached connection receives a message.\n\t *\n\t * @param msg - The received message\n\t *\n\t * @internal\n\t */\n\tpublic onUdpMessage(msg: Buffer) {\n\t\tif (msg.length <= 8) return;\n\t\tconst ssrc = msg.readUInt32BE(8);\n\n\t\tconst userData = this.ssrcMap.get(ssrc);\n\t\tif (!userData) return;\n\n\t\tthis.speaking.onPacket(userData.userId);\n\n\t\tconst stream = this.subscriptions.get(userData.userId);\n\t\tif (!stream) return;\n\n\t\tif (this.connectionData.encryptionMode && this.connectionData.nonceBuffer && this.connectionData.secretKey) {\n\t\t\tconst packet = this.parsePacket(\n\t\t\t\tmsg,\n\t\t\t\tthis.connectionData.encryptionMode,\n\t\t\t\tthis.connectionData.nonceBuffer,\n\t\t\t\tthis.connectionData.secretKey,\n\t\t\t);\n\t\t\tif (packet) {\n\t\t\t\tstream.push(packet);\n\t\t\t} else {\n\t\t\t\tstream.destroy(new Error('Failed to parse packet'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Creates a subscription for the given user id.\n\t *\n\t * @param target - The id of the user to subscribe to\n\t *\n\t * @returns A readable stream of Opus packets received from the target\n\t */\n\tpublic subscribe(userId: string, options?: Partial) {\n\t\tconst existing = this.subscriptions.get(userId);\n\t\tif (existing) return existing;\n\n\t\tconst stream = new AudioReceiveStream({\n\t\t\t...createDefaultAudioReceiveStreamOptions(),\n\t\t\t...options,\n\t\t});\n\n\t\tstream.once('close', () => this.subscriptions.delete(userId));\n\t\tthis.subscriptions.set(userId, stream);\n\t\treturn stream;\n\t}\n}\n","import { Readable, ReadableOptions } from 'node:stream';\nimport { SILENCE_FRAME } from '../audio/AudioPlayer';\n\n/**\n * The different behaviors an audio receive stream can have for deciding when to end.\n */\nexport enum EndBehaviorType {\n\t/**\n\t * The stream will only end when manually destroyed.\n\t */\n\tManual,\n\n\t/**\n\t * The stream will end after a given time period of silence/no audio packets.\n\t */\n\tAfterSilence,\n\n\t/**\n\t * The stream will end after a given time period of no audio packets.\n\t */\n\tAfterInactivity,\n}\n\nexport type EndBehavior =\n\t| {\n\t\t\tbehavior: EndBehaviorType.Manual;\n\t }\n\t| {\n\t\t\tbehavior: EndBehaviorType.AfterSilence | EndBehaviorType.AfterInactivity;\n\t\t\tduration: number;\n\t };\n\nexport interface AudioReceiveStreamOptions extends ReadableOptions {\n\tend: EndBehavior;\n}\n\nexport function createDefaultAudioReceiveStreamOptions(): AudioReceiveStreamOptions {\n\treturn {\n\t\tend: {\n\t\t\tbehavior: EndBehaviorType.Manual,\n\t\t},\n\t};\n}\n\n/**\n * A readable stream of Opus packets received from a specific entity\n * in a Discord voice connection.\n */\nexport class AudioReceiveStream extends Readable {\n\t/**\n\t * The end behavior of the receive stream.\n\t */\n\tpublic readonly end: EndBehavior;\n\n\tprivate endTimeout?: NodeJS.Timeout;\n\n\tpublic constructor({ end, ...options }: AudioReceiveStreamOptions) {\n\t\tsuper({\n\t\t\t...options,\n\t\t\tobjectMode: true,\n\t\t});\n\n\t\tthis.end = end;\n\t}\n\n\tpublic override push(buffer: Buffer | null) {\n\t\tif (buffer) {\n\t\t\tif (\n\t\t\t\tthis.end.behavior === EndBehaviorType.AfterInactivity ||\n\t\t\t\t(this.end.behavior === EndBehaviorType.AfterSilence &&\n\t\t\t\t\t(buffer.compare(SILENCE_FRAME) !== 0 || typeof this.endTimeout === 'undefined'))\n\t\t\t) {\n\t\t\t\tthis.renewEndTimeout(this.end);\n\t\t\t}\n\t\t}\n\n\t\treturn super.push(buffer);\n\t}\n\n\tprivate renewEndTimeout(end: EndBehavior & { duration: number }) {\n\t\tif (this.endTimeout) {\n\t\t\tclearTimeout(this.endTimeout);\n\t\t}\n\t\tthis.endTimeout = setTimeout(() => this.push(null), end.duration);\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/no-empty-function\n\tpublic override _read() {}\n}\n","/* eslint-disable @typescript-eslint/prefer-ts-expect-error, @typescript-eslint/method-signature-style */\nimport EventEmitter from 'node:events';\nimport { AudioPlayerError } from './AudioPlayerError';\nimport type { AudioResource } from './AudioResource';\nimport { PlayerSubscription } from './PlayerSubscription';\nimport { addAudioPlayer, deleteAudioPlayer } from '../DataStore';\nimport { VoiceConnection, VoiceConnectionStatus } from '../VoiceConnection';\nimport { noop } from '../util/util';\n\n// The Opus \"silent\" frame\nexport const SILENCE_FRAME = Buffer.from([0xf8, 0xff, 0xfe]);\n\n/**\n * Describes the behavior of the player when an audio packet is played but there are no available\n * voice connections to play to.\n */\nexport enum NoSubscriberBehavior {\n\t/**\n\t * Pauses playing the stream until a voice connection becomes available.\n\t */\n\tPause = 'pause',\n\n\t/**\n\t * Continues to play through the resource regardless.\n\t */\n\tPlay = 'play',\n\n\t/**\n\t * The player stops and enters the Idle state.\n\t */\n\tStop = 'stop',\n}\n\nexport enum AudioPlayerStatus {\n\t/**\n\t * When there is currently no resource for the player to be playing.\n\t */\n\tIdle = 'idle',\n\n\t/**\n\t * When the player is waiting for an audio resource to become readable before transitioning to Playing.\n\t */\n\tBuffering = 'buffering',\n\n\t/**\n\t * When the player has been manually paused.\n\t */\n\tPaused = 'paused',\n\n\t/**\n\t * When the player is actively playing an audio resource.\n\t */\n\tPlaying = 'playing',\n\n\t/**\n\t * When the player has paused itself. Only possible with the \"pause\" no subscriber behavior.\n\t */\n\tAutoPaused = 'autopaused',\n}\n\n/**\n * Options that can be passed when creating an audio player, used to specify its behavior.\n */\nexport interface CreateAudioPlayerOptions {\n\tdebug?: boolean;\n\tbehaviors?: {\n\t\tnoSubscriber?: NoSubscriberBehavior;\n\t\tmaxMissedFrames?: number;\n\t};\n}\n\n/**\n * The state that an AudioPlayer is in when it has no resource to play. This is the starting state.\n */\nexport interface AudioPlayerIdleState {\n\tstatus: AudioPlayerStatus.Idle;\n}\n\n/**\n * The state that an AudioPlayer is in when it is waiting for a resource to become readable. Once this\n * happens, the AudioPlayer will enter the Playing state. If the resource ends/errors before this, then\n * it will re-enter the Idle state.\n */\nexport interface AudioPlayerBufferingState {\n\tstatus: AudioPlayerStatus.Buffering;\n\t/**\n\t * The resource that the AudioPlayer is waiting for\n\t */\n\tresource: AudioResource;\n\tonReadableCallback: () => void;\n\tonFailureCallback: () => void;\n\tonStreamError: (error: Error) => void;\n}\n\n/**\n * The state that an AudioPlayer is in when it is actively playing an AudioResource. When playback ends,\n * it will enter the Idle state.\n */\nexport interface AudioPlayerPlayingState {\n\tstatus: AudioPlayerStatus.Playing;\n\t/**\n\t * The number of consecutive times that the audio resource has been unable to provide an Opus frame.\n\t */\n\tmissedFrames: number;\n\n\t/**\n\t * The playback duration in milliseconds of the current audio resource. This includes filler silence packets\n\t * that have been played when the resource was buffering.\n\t */\n\tplaybackDuration: number;\n\n\t/**\n\t * The resource that is being played.\n\t */\n\tresource: AudioResource;\n\n\tonStreamError: (error: Error) => void;\n}\n\n/**\n * The state that an AudioPlayer is in when it has either been explicitly paused by the user, or done\n * automatically by the AudioPlayer itself if there are no available subscribers.\n */\nexport interface AudioPlayerPausedState {\n\tstatus: AudioPlayerStatus.Paused | AudioPlayerStatus.AutoPaused;\n\t/**\n\t * How many silence packets still need to be played to avoid audio interpolation due to the stream suddenly pausing.\n\t */\n\tsilencePacketsRemaining: number;\n\n\t/**\n\t * The playback duration in milliseconds of the current audio resource. This includes filler silence packets\n\t * that have been played when the resource was buffering.\n\t */\n\tplaybackDuration: number;\n\n\t/**\n\t * The current resource of the audio player.\n\t */\n\tresource: AudioResource;\n\n\tonStreamError: (error: Error) => void;\n}\n\n/**\n * The various states that the player can be in.\n */\nexport type AudioPlayerState =\n\t| AudioPlayerIdleState\n\t| AudioPlayerBufferingState\n\t| AudioPlayerPlayingState\n\t| AudioPlayerPausedState;\n\nexport interface AudioPlayer extends EventEmitter {\n\t/**\n\t * Emitted when there is an error emitted from the audio resource played by the audio player\n\t * @event\n\t */\n\ton(event: 'error', listener: (error: AudioPlayerError) => void): this;\n\t/**\n\t * Emitted debugging information about the audio player\n\t * @event\n\t */\n\ton(event: 'debug', listener: (message: string) => void): this;\n\t/**\n\t * Emitted when the state of the audio player changes\n\t * @event\n\t */\n\ton(event: 'stateChange', listener: (oldState: AudioPlayerState, newState: AudioPlayerState) => void): this;\n\t/**\n\t * Emitted when the audio player is subscribed to a voice connection\n\t * @event\n\t */\n\ton(event: 'subscribe' | 'unsubscribe', listener: (subscription: PlayerSubscription) => void): this;\n\t/**\n\t * Emitted when the status of state changes to a specific status\n\t * @event\n\t */\n\ton(\n\t\tevent: T,\n\t\tlistener: (oldState: AudioPlayerState, newState: AudioPlayerState & { status: T }) => void,\n\t): this;\n}\n\n/**\n * Stringifies an AudioPlayerState instance.\n *\n * @param state - The state to stringify\n */\nfunction stringifyState(state: AudioPlayerState) {\n\treturn JSON.stringify({\n\t\t...state,\n\t\tresource: Reflect.has(state, 'resource'),\n\t\tstepTimeout: Reflect.has(state, 'stepTimeout'),\n\t});\n}\n\n/**\n * Used to play audio resources (i.e. tracks, streams) to voice connections.\n *\n * @remarks\n * Audio players are designed to be re-used - even if a resource has finished playing, the player itself\n * can still be used.\n *\n * The AudioPlayer drives the timing of playback, and therefore is unaffected by voice connections\n * becoming unavailable. Its behavior in these scenarios can be configured.\n */\nexport class AudioPlayer extends EventEmitter {\n\t/**\n\t * The state that the AudioPlayer is in.\n\t */\n\tprivate _state: AudioPlayerState;\n\n\t/**\n\t * A list of VoiceConnections that are registered to this AudioPlayer. The player will attempt to play audio\n\t * to the streams in this list.\n\t */\n\tprivate readonly subscribers: PlayerSubscription[] = [];\n\n\t/**\n\t * The behavior that the player should follow when it enters certain situations.\n\t */\n\tprivate readonly behaviors: {\n\t\tnoSubscriber: NoSubscriberBehavior;\n\t\tmaxMissedFrames: number;\n\t};\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: null | ((message: string) => void);\n\n\t/**\n\t * Creates a new AudioPlayer.\n\t */\n\tpublic constructor(options: CreateAudioPlayerOptions = {}) {\n\t\tsuper();\n\t\tthis._state = { status: AudioPlayerStatus.Idle };\n\t\tthis.behaviors = {\n\t\t\tnoSubscriber: NoSubscriberBehavior.Pause,\n\t\t\tmaxMissedFrames: 5,\n\t\t\t...options.behaviors,\n\t\t};\n\t\tthis.debug = options.debug === false ? null : (message: string) => this.emit('debug', message);\n\t}\n\n\t/**\n\t * A list of subscribed voice connections that can currently receive audio to play.\n\t */\n\tpublic get playable() {\n\t\treturn this.subscribers\n\t\t\t.filter(({ connection }) => connection.state.status === VoiceConnectionStatus.Ready)\n\t\t\t.map(({ connection }) => connection);\n\t}\n\n\t/**\n\t * Subscribes a VoiceConnection to the audio player's play list. If the VoiceConnection is already subscribed,\n\t * then the existing subscription is used.\n\t *\n\t * @remarks\n\t * This method should not be directly called. Instead, use VoiceConnection#subscribe.\n\t *\n\t * @param connection - The connection to subscribe\n\t *\n\t * @returns The new subscription if the voice connection is not yet subscribed, otherwise the existing subscription\n\t */\n\t// @ts-ignore\n\tprivate subscribe(connection: VoiceConnection) {\n\t\tconst existingSubscription = this.subscribers.find((subscription) => subscription.connection === connection);\n\t\tif (!existingSubscription) {\n\t\t\tconst subscription = new PlayerSubscription(connection, this);\n\t\t\tthis.subscribers.push(subscription);\n\t\t\tsetImmediate(() => this.emit('subscribe', subscription));\n\t\t\treturn subscription;\n\t\t}\n\t\treturn existingSubscription;\n\t}\n\n\t/**\n\t * Unsubscribes a subscription - i.e. removes a voice connection from the play list of the audio player.\n\t *\n\t * @remarks\n\t * This method should not be directly called. Instead, use PlayerSubscription#unsubscribe.\n\t *\n\t * @param subscription - The subscription to remove\n\t *\n\t * @returns Whether or not the subscription existed on the player and was removed\n\t */\n\t// @ts-ignore\n\tprivate unsubscribe(subscription: PlayerSubscription) {\n\t\tconst index = this.subscribers.indexOf(subscription);\n\t\tconst exists = index !== -1;\n\t\tif (exists) {\n\t\t\tthis.subscribers.splice(index, 1);\n\t\t\tsubscription.connection.setSpeaking(false);\n\t\t\tthis.emit('unsubscribe', subscription);\n\t\t}\n\t\treturn exists;\n\t}\n\n\t/**\n\t * The state that the player is in.\n\t */\n\tpublic get state() {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * Sets a new state for the player, performing clean-up operations where necessary.\n\t */\n\tpublic set state(newState: AudioPlayerState) {\n\t\tconst oldState = this._state;\n\t\tconst newResource = Reflect.get(newState, 'resource') as AudioResource | undefined;\n\n\t\tif (oldState.status !== AudioPlayerStatus.Idle && oldState.resource !== newResource) {\n\t\t\toldState.resource.playStream.on('error', noop);\n\t\t\toldState.resource.playStream.off('error', oldState.onStreamError);\n\t\t\toldState.resource.audioPlayer = undefined;\n\t\t\toldState.resource.playStream.destroy();\n\t\t\toldState.resource.playStream.read(); // required to ensure buffered data is drained, prevents memory leak\n\t\t}\n\n\t\t// When leaving the Buffering state (or buffering a new resource), then remove the event listeners from it\n\t\tif (\n\t\t\toldState.status === AudioPlayerStatus.Buffering &&\n\t\t\t(newState.status !== AudioPlayerStatus.Buffering || newState.resource !== oldState.resource)\n\t\t) {\n\t\t\toldState.resource.playStream.off('end', oldState.onFailureCallback);\n\t\t\toldState.resource.playStream.off('close', oldState.onFailureCallback);\n\t\t\toldState.resource.playStream.off('finish', oldState.onFailureCallback);\n\t\t\toldState.resource.playStream.off('readable', oldState.onReadableCallback);\n\t\t}\n\n\t\t// transitioning into an idle should ensure that connections stop speaking\n\t\tif (newState.status === AudioPlayerStatus.Idle) {\n\t\t\tthis._signalStopSpeaking();\n\t\t\tdeleteAudioPlayer(this);\n\t\t}\n\n\t\t// attach to the global audio player timer\n\t\tif (newResource) {\n\t\t\taddAudioPlayer(this);\n\t\t}\n\n\t\t// playing -> playing state changes should still transition if a resource changed (seems like it would be useful!)\n\t\tconst didChangeResources =\n\t\t\toldState.status !== AudioPlayerStatus.Idle &&\n\t\t\tnewState.status === AudioPlayerStatus.Playing &&\n\t\t\toldState.resource !== newState.resource;\n\n\t\tthis._state = newState;\n\n\t\tthis.emit('stateChange', oldState, this._state);\n\t\tif (oldState.status !== newState.status || didChangeResources) {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-argument\n\t\t\tthis.emit(newState.status, oldState, this._state as any);\n\t\t}\n\t\tthis.debug?.(`state change:\\nfrom ${stringifyState(oldState)}\\nto ${stringifyState(newState)}`);\n\t}\n\n\t/**\n\t * Plays a new resource on the player. If the player is already playing a resource, the existing resource is destroyed\n\t * (it cannot be reused, even in another player) and is replaced with the new resource.\n\t *\n\t * @remarks\n\t * The player will transition to the Playing state once playback begins, and will return to the Idle state once\n\t * playback is ended.\n\t *\n\t * If the player was previously playing a resource and this method is called, the player will not transition to the\n\t * Idle state during the swap over.\n\t *\n\t * @param resource - The resource to play\n\t *\n\t * @throws Will throw if attempting to play an audio resource that has already ended, or is being played by another player\n\t */\n\tpublic play(resource: AudioResource) {\n\t\tif (resource.ended) {\n\t\t\tthrow new Error('Cannot play a resource that has already ended.');\n\t\t}\n\n\t\tif (resource.audioPlayer) {\n\t\t\tif (resource.audioPlayer === this) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow new Error('Resource is already being played by another audio player.');\n\t\t}\n\t\tresource.audioPlayer = this;\n\n\t\t// Attach error listeners to the stream that will propagate the error and then return to the Idle\n\t\t// state if the resource is still being used.\n\t\tconst onStreamError = (error: Error) => {\n\t\t\tif (this.state.status !== AudioPlayerStatus.Idle) {\n\t\t\t\tthis.emit('error', new AudioPlayerError(error, this.state.resource));\n\t\t\t}\n\n\t\t\tif (this.state.status !== AudioPlayerStatus.Idle && this.state.resource === resource) {\n\t\t\t\tthis.state = {\n\t\t\t\t\tstatus: AudioPlayerStatus.Idle,\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\n\t\tresource.playStream.once('error', onStreamError);\n\n\t\tif (resource.started) {\n\t\t\tthis.state = {\n\t\t\t\tstatus: AudioPlayerStatus.Playing,\n\t\t\t\tmissedFrames: 0,\n\t\t\t\tplaybackDuration: 0,\n\t\t\t\tresource,\n\t\t\t\tonStreamError,\n\t\t\t};\n\t\t} else {\n\t\t\tconst onReadableCallback = () => {\n\t\t\t\tif (this.state.status === AudioPlayerStatus.Buffering && this.state.resource === resource) {\n\t\t\t\t\tthis.state = {\n\t\t\t\t\t\tstatus: AudioPlayerStatus.Playing,\n\t\t\t\t\t\tmissedFrames: 0,\n\t\t\t\t\t\tplaybackDuration: 0,\n\t\t\t\t\t\tresource,\n\t\t\t\t\t\tonStreamError,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst onFailureCallback = () => {\n\t\t\t\tif (this.state.status === AudioPlayerStatus.Buffering && this.state.resource === resource) {\n\t\t\t\t\tthis.state = {\n\t\t\t\t\t\tstatus: AudioPlayerStatus.Idle,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tresource.playStream.once('readable', onReadableCallback);\n\n\t\t\tresource.playStream.once('end', onFailureCallback);\n\t\t\tresource.playStream.once('close', onFailureCallback);\n\t\t\tresource.playStream.once('finish', onFailureCallback);\n\n\t\t\tthis.state = {\n\t\t\t\tstatus: AudioPlayerStatus.Buffering,\n\t\t\t\tresource,\n\t\t\t\tonReadableCallback,\n\t\t\t\tonFailureCallback,\n\t\t\t\tonStreamError,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Pauses playback of the current resource, if any.\n\t *\n\t * @param interpolateSilence - If true, the player will play 5 packets of silence after pausing to prevent audio glitches\n\t *\n\t * @returns `true` if the player was successfully paused, otherwise `false`\n\t */\n\tpublic pause(interpolateSilence = true) {\n\t\tif (this.state.status !== AudioPlayerStatus.Playing) return false;\n\t\tthis.state = {\n\t\t\t...this.state,\n\t\t\tstatus: AudioPlayerStatus.Paused,\n\t\t\tsilencePacketsRemaining: interpolateSilence ? 5 : 0,\n\t\t};\n\t\treturn true;\n\t}\n\n\t/**\n\t * Unpauses playback of the current resource, if any.\n\t *\n\t * @returns `true` if the player was successfully unpaused, otherwise `false`\n\t */\n\tpublic unpause() {\n\t\tif (this.state.status !== AudioPlayerStatus.Paused) return false;\n\t\tthis.state = {\n\t\t\t...this.state,\n\t\t\tstatus: AudioPlayerStatus.Playing,\n\t\t\tmissedFrames: 0,\n\t\t};\n\t\treturn true;\n\t}\n\n\t/**\n\t * Stops playback of the current resource and destroys the resource. The player will either transition to the Idle state,\n\t * or remain in its current state until the silence padding frames of the resource have been played.\n\t *\n\t * @param force - If true, will force the player to enter the Idle state even if the resource has silence padding frames\n\t *\n\t * @returns `true` if the player will come to a stop, otherwise `false`\n\t */\n\tpublic stop(force = false) {\n\t\tif (this.state.status === AudioPlayerStatus.Idle) return false;\n\t\tif (force || this.state.resource.silencePaddingFrames === 0) {\n\t\t\tthis.state = {\n\t\t\t\tstatus: AudioPlayerStatus.Idle,\n\t\t\t};\n\t\t} else if (this.state.resource.silenceRemaining === -1) {\n\t\t\tthis.state.resource.silenceRemaining = this.state.resource.silencePaddingFrames;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks whether the underlying resource (if any) is playable (readable)\n\t *\n\t * @returns `true` if the resource is playable, otherwise `false`\n\t */\n\tpublic checkPlayable() {\n\t\tconst state = this._state;\n\t\tif (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) return false;\n\n\t\t// If the stream has been destroyed or is no longer readable, then transition to the Idle state.\n\t\tif (!state.resource.readable) {\n\t\t\tthis.state = {\n\t\t\t\tstatus: AudioPlayerStatus.Idle,\n\t\t\t};\n\t\t\treturn false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Called roughly every 20ms by the global audio player timer. Dispatches any audio packets that are buffered\n\t * by the active connections of this audio player.\n\t */\n\t// @ts-ignore\n\tprivate _stepDispatch() {\n\t\tconst state = this._state;\n\n\t\t// Guard against the Idle state\n\t\tif (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) return;\n\n\t\t// Dispatch any audio packets that were prepared in the previous cycle\n\t\tthis.playable.forEach((connection) => connection.dispatchAudio());\n\t}\n\n\t/**\n\t * Called roughly every 20ms by the global audio player timer. Attempts to read an audio packet from the\n\t * underlying resource of the stream, and then has all the active connections of the audio player prepare it\n\t * (encrypt it, append header data) so that it is ready to play at the start of the next cycle.\n\t */\n\t// @ts-ignore\n\tprivate _stepPrepare() {\n\t\tconst state = this._state;\n\n\t\t// Guard against the Idle state\n\t\tif (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) return;\n\n\t\t// List of connections that can receive the packet\n\t\tconst playable = this.playable;\n\n\t\t/* If the player was previously in the AutoPaused state, check to see whether there are newly available\n\t\t connections, allowing us to transition out of the AutoPaused state back into the Playing state */\n\t\tif (state.status === AudioPlayerStatus.AutoPaused && playable.length > 0) {\n\t\t\tthis.state = {\n\t\t\t\t...state,\n\t\t\t\tstatus: AudioPlayerStatus.Playing,\n\t\t\t\tmissedFrames: 0,\n\t\t\t};\n\t\t}\n\n\t\t/* If the player is (auto)paused, check to see whether silence packets should be played and\n\t\t set a timeout to begin the next cycle, ending the current cycle here. */\n\t\tif (state.status === AudioPlayerStatus.Paused || state.status === AudioPlayerStatus.AutoPaused) {\n\t\t\tif (state.silencePacketsRemaining > 0) {\n\t\t\t\tstate.silencePacketsRemaining--;\n\t\t\t\tthis._preparePacket(SILENCE_FRAME, playable, state);\n\t\t\t\tif (state.silencePacketsRemaining === 0) {\n\t\t\t\t\tthis._signalStopSpeaking();\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn;\n\t\t}\n\n\t\t// If there are no available connections in this cycle, observe the configured \"no subscriber\" behavior.\n\t\tif (playable.length === 0) {\n\t\t\tif (this.behaviors.noSubscriber === NoSubscriberBehavior.Pause) {\n\t\t\t\tthis.state = {\n\t\t\t\t\t...state,\n\t\t\t\t\tstatus: AudioPlayerStatus.AutoPaused,\n\t\t\t\t\tsilencePacketsRemaining: 5,\n\t\t\t\t};\n\t\t\t\treturn;\n\t\t\t} else if (this.behaviors.noSubscriber === NoSubscriberBehavior.Stop) {\n\t\t\t\tthis.stop(true);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Attempt to read an Opus packet from the resource. If there isn't an available packet,\n\t\t * play a silence packet. If there are 5 consecutive cycles with failed reads, then the\n\t\t * playback will end.\n\t\t */\n\t\tconst packet: Buffer | null = state.resource.read();\n\n\t\t// eslint-disable-next-line @typescript-eslint/no-unnecessary-condition\n\t\tif (state.status === AudioPlayerStatus.Playing) {\n\t\t\tif (packet) {\n\t\t\t\tthis._preparePacket(packet, playable, state);\n\t\t\t\tstate.missedFrames = 0;\n\t\t\t} else {\n\t\t\t\tthis._preparePacket(SILENCE_FRAME, playable, state);\n\t\t\t\tstate.missedFrames++;\n\t\t\t\tif (state.missedFrames >= this.behaviors.maxMissedFrames) {\n\t\t\t\t\tthis.stop();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Signals to all the subscribed connections that they should send a packet to Discord indicating\n\t * they are no longer speaking. Called once playback of a resource ends.\n\t */\n\tprivate _signalStopSpeaking() {\n\t\treturn this.subscribers.forEach(({ connection }) => connection.setSpeaking(false));\n\t}\n\n\t/**\n\t * Instructs the given connections to each prepare this packet to be played at the start of the\n\t * next cycle.\n\t *\n\t * @param packet - The Opus packet to be prepared by each receiver\n\t * @param receivers - The connections that should play this packet\n\t */\n\tprivate _preparePacket(\n\t\tpacket: Buffer,\n\t\treceivers: VoiceConnection[],\n\t\tstate: AudioPlayerPlayingState | AudioPlayerPausedState,\n\t) {\n\t\tstate.playbackDuration += 20;\n\t\treceivers.forEach((connection) => connection.prepareAudioPacket(packet));\n\t}\n}\n\n/**\n * Creates a new AudioPlayer to be used.\n */\nexport function createAudioPlayer(options?: CreateAudioPlayerOptions) {\n\treturn new AudioPlayer(options);\n}\n","import type { AudioResource } from './AudioResource';\n\n/**\n * An error emitted by an AudioPlayer. Contains an attached resource to aid with\n * debugging and identifying where the error came from.\n */\nexport class AudioPlayerError extends Error {\n\t/**\n\t * The resource associated with the audio player at the time the error was thrown.\n\t */\n\tpublic readonly resource: AudioResource;\n\tpublic constructor(error: Error, resource: AudioResource) {\n\t\tsuper(error.message);\n\t\tthis.resource = resource;\n\t\tthis.name = error.name;\n\t\tthis.stack = error.stack;\n\t}\n}\n","/* eslint-disable @typescript-eslint/dot-notation */\nimport type { AudioPlayer } from './AudioPlayer';\nimport type { VoiceConnection } from '../VoiceConnection';\n\n/**\n * Represents a subscription of a voice connection to an audio player, allowing\n * the audio player to play audio on the voice connection.\n */\nexport class PlayerSubscription {\n\t/**\n\t * The voice connection of this subscription.\n\t */\n\tpublic readonly connection: VoiceConnection;\n\n\t/**\n\t * The audio player of this subscription.\n\t */\n\tpublic readonly player: AudioPlayer;\n\n\tpublic constructor(connection: VoiceConnection, player: AudioPlayer) {\n\t\tthis.connection = connection;\n\t\tthis.player = player;\n\t}\n\n\t/**\n\t * Unsubscribes the connection from the audio player, meaning that the\n\t * audio player cannot stream audio to it until a new subscription is made.\n\t */\n\tpublic unsubscribe() {\n\t\tthis.connection['onSubscriptionRemoved'](this);\n\t\tthis.player['unsubscribe'](this);\n\t}\n}\n","/* eslint-disable @typescript-eslint/method-signature-style */\nimport { EventEmitter } from 'node:events';\n\n/**\n * The known data for a user in a Discord voice connection.\n */\nexport interface VoiceUserData {\n\t/**\n\t * The SSRC of the user's audio stream.\n\t */\n\taudioSSRC: number;\n\n\t/**\n\t * The SSRC of the user's video stream (if one exists)\n\t * Cannot be 0. If undefined, the user has no video stream.\n\t */\n\tvideoSSRC?: number;\n\n\t/**\n\t * The Discord user id of the user.\n\t */\n\tuserId: string;\n}\n\nexport interface SSRCMap extends EventEmitter {\n\ton(event: 'create', listener: (newData: VoiceUserData) => void): this;\n\ton(event: 'update', listener: (oldData: VoiceUserData | undefined, newData: VoiceUserData) => void): this;\n\ton(event: 'delete', listener: (deletedData: VoiceUserData) => void): this;\n}\n\n/**\n * Maps audio SSRCs to data of users in voice connections.\n */\nexport class SSRCMap extends EventEmitter {\n\t/**\n\t * The underlying map.\n\t */\n\tprivate readonly map: Map;\n\n\tpublic constructor() {\n\t\tsuper();\n\t\tthis.map = new Map();\n\t}\n\n\t/**\n\t * Updates the map with new user data\n\t *\n\t * @param data - The data to update with\n\t */\n\tpublic update(data: VoiceUserData) {\n\t\tconst existing = this.map.get(data.audioSSRC);\n\n\t\tconst newValue = {\n\t\t\t...this.map.get(data.audioSSRC),\n\t\t\t...data,\n\t\t};\n\n\t\tthis.map.set(data.audioSSRC, newValue);\n\t\tif (!existing) this.emit('create', newValue);\n\t\tthis.emit('update', existing, newValue);\n\t}\n\n\t/**\n\t * Gets the stored voice data of a user.\n\t *\n\t * @param target - The target, either their user id or audio SSRC\n\t */\n\tpublic get(target: number | string) {\n\t\tif (typeof target === 'number') {\n\t\t\treturn this.map.get(target);\n\t\t}\n\n\t\tfor (const data of this.map.values()) {\n\t\t\tif (data.userId === target) {\n\t\t\t\treturn data;\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Deletes the stored voice data about a user.\n\t *\n\t * @param target - The target of the delete operation, either their audio SSRC or user id\n\t *\n\t * @returns The data that was deleted, if any\n\t */\n\tpublic delete(target: number | string) {\n\t\tif (typeof target === 'number') {\n\t\t\tconst existing = this.map.get(target);\n\t\t\tif (existing) {\n\t\t\t\tthis.map.delete(target);\n\t\t\t\tthis.emit('delete', existing);\n\t\t\t}\n\t\t\treturn existing;\n\t\t}\n\n\t\tfor (const [audioSSRC, data] of this.map.entries()) {\n\t\t\tif (data.userId === target) {\n\t\t\t\tthis.map.delete(audioSSRC);\n\t\t\t\tthis.emit('delete', data);\n\t\t\t\treturn data;\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n}\n","/* eslint-disable @typescript-eslint/method-signature-style, @typescript-eslint/unified-signatures */\nimport { EventEmitter } from 'node:events';\n\nexport interface SpeakingMap extends EventEmitter {\n\t/**\n\t * Emitted when a user starts speaking.\n\t * @event\n\t */\n\ton(event: 'start', listener: (userId: string) => void): this;\n\n\t/**\n\t * Emitted when a user ends speaking.\n\t * @event\n\t */\n\ton(event: 'end', listener: (userId: string) => void): this;\n}\n\n/**\n * Tracks the speaking states of users in a voice channel.\n */\nexport class SpeakingMap extends EventEmitter {\n\t/**\n\t * The delay after a packet is received from a user until they're marked as not speaking anymore.\n\t */\n\tpublic static readonly DELAY = 100;\n\n\t/**\n\t * The currently speaking users, mapped to the milliseconds since UNIX epoch at which they started speaking.\n\t */\n\tpublic readonly users: Map;\n\n\tprivate readonly speakingTimeouts: Map;\n\n\tpublic constructor() {\n\t\tsuper();\n\t\tthis.users = new Map();\n\t\tthis.speakingTimeouts = new Map();\n\t}\n\n\tpublic onPacket(userId: string) {\n\t\tconst timeout = this.speakingTimeouts.get(userId);\n\t\tif (timeout) {\n\t\t\tclearTimeout(timeout);\n\t\t} else {\n\t\t\tthis.users.set(userId, Date.now());\n\t\t\tthis.emit('start', userId);\n\t\t}\n\t\tthis.startTimeout(userId);\n\t}\n\n\tprivate startTimeout(userId: string) {\n\t\tthis.speakingTimeouts.set(\n\t\t\tuserId,\n\t\t\tsetTimeout(() => {\n\t\t\t\tthis.emit('end', userId);\n\t\t\t\tthis.speakingTimeouts.delete(userId);\n\t\t\t\tthis.users.delete(userId);\n\t\t\t}, SpeakingMap.DELAY),\n\t\t);\n\t}\n}\n","import type { JoinConfig } from './DataStore';\nimport { createVoiceConnection } from './VoiceConnection';\nimport type { DiscordGatewayAdapterCreator } from './util/adapter';\n\n/**\n * The options that can be given when creating a voice connection.\n */\nexport interface CreateVoiceConnectionOptions {\n\t/**\n\t * If true, debug messages will be enabled for the voice connection and its\n\t * related components. Defaults to false.\n\t */\n\tdebug?: boolean;\n\n\tadapterCreator: DiscordGatewayAdapterCreator;\n}\n\n/**\n * The options that can be given when joining a voice channel.\n */\nexport interface JoinVoiceChannelOptions {\n\t/**\n\t * The id of the Discord voice channel to join.\n\t */\n\tchannelId: string;\n\n\t/**\n\t * The id of the guild that the voice channel belongs to.\n\t */\n\tguildId: string;\n\n\t/**\n\t * Whether to join the channel deafened (defaults to true)\n\t */\n\tselfDeaf?: boolean;\n\n\t/**\n\t * Whether to join the channel muted (defaults to true)\n\t */\n\tselfMute?: boolean;\n\n\t/**\n\t * An optional group identifier for the voice connection.\n\t */\n\tgroup?: string;\n}\n\n/**\n * Creates a VoiceConnection to a Discord voice channel.\n *\n * @param voiceChannel - the voice channel to connect to\n * @param options - the options for joining the voice channel\n */\nexport function joinVoiceChannel(options: JoinVoiceChannelOptions & CreateVoiceConnectionOptions) {\n\tconst joinConfig: JoinConfig = {\n\t\tselfDeaf: true,\n\t\tselfMute: false,\n\t\tgroup: 'default',\n\t\t...options,\n\t};\n\n\treturn createVoiceConnection(joinConfig, {\n\t\tadapterCreator: options.adapterCreator,\n\t\tdebug: options.debug,\n\t});\n}\n","import { pipeline, Readable } from 'node:stream';\nimport prism from 'prism-media';\nimport { AudioPlayer, SILENCE_FRAME } from './AudioPlayer';\nimport { Edge, findPipeline, StreamType, TransformerType } from './TransformerGraph';\nimport { noop } from '../util/util';\n\n/**\n * Options that are set when creating a new audio resource.\n *\n * @template T - the type for the metadata (if any) of the audio resource\n */\nexport interface CreateAudioResourceOptions {\n\t/**\n\t * The type of the input stream. Defaults to `StreamType.Arbitrary`.\n\t */\n\tinputType?: StreamType;\n\n\t/**\n\t * Optional metadata that can be attached to the resource (e.g. track title, random id).\n\t * This is useful for identification purposes when the resource is passed around in events.\n\t * See {@link AudioResource.metadata}\n\t */\n\tmetadata?: T;\n\n\t/**\n\t * Whether or not inline volume should be enabled. If enabled, you will be able to change the volume\n\t * of the stream on-the-fly. However, this also increases the performance cost of playback. Defaults to `false`.\n\t */\n\tinlineVolume?: boolean;\n\n\t/**\n\t * The number of silence frames to append to the end of the resource's audio stream, to prevent interpolation glitches.\n\t * Defaults to 5.\n\t */\n\tsilencePaddingFrames?: number;\n}\n\n/**\n * Represents an audio resource that can be played by an audio player.\n *\n * @template T - the type for the metadata (if any) of the audio resource\n */\nexport class AudioResource {\n\t/**\n\t * An object-mode Readable stream that emits Opus packets. This is what is played by audio players.\n\t */\n\tpublic readonly playStream: Readable;\n\n\t/**\n\t * The pipeline used to convert the input stream into a playable format. For example, this may\n\t * contain an FFmpeg component for arbitrary inputs, and it may contain a VolumeTransformer component\n\t * for resources with inline volume transformation enabled.\n\t */\n\tpublic readonly edges: readonly Edge[];\n\n\t/**\n\t * Optional metadata that can be used to identify the resource.\n\t */\n\tpublic metadata: T;\n\n\t/**\n\t * If the resource was created with inline volume transformation enabled, then this will be a\n\t * prism-media VolumeTransformer. You can use this to alter the volume of the stream.\n\t */\n\tpublic readonly volume?: prism.VolumeTransformer;\n\n\t/**\n\t * If using an Opus encoder to create this audio resource, then this will be a prism-media opus.Encoder.\n\t * You can use this to control settings such as bitrate, FEC, PLP.\n\t */\n\tpublic readonly encoder?: prism.opus.Encoder;\n\n\t/**\n\t * The audio player that the resource is subscribed to, if any.\n\t */\n\tpublic audioPlayer?: AudioPlayer;\n\n\t/**\n\t * The playback duration of this audio resource, given in milliseconds.\n\t */\n\tpublic playbackDuration = 0;\n\n\t/**\n\t * Whether or not the stream for this resource has started (data has become readable)\n\t */\n\tpublic started = false;\n\n\t/**\n\t * The number of silence frames to append to the end of the resource's audio stream, to prevent interpolation glitches.\n\t */\n\tpublic readonly silencePaddingFrames: number;\n\n\t/**\n\t * The number of remaining silence frames to play. If -1, the frames have not yet started playing.\n\t */\n\tpublic silenceRemaining = -1;\n\n\tpublic constructor(edges: readonly Edge[], streams: readonly Readable[], metadata: T, silencePaddingFrames: number) {\n\t\tthis.edges = edges;\n\t\tthis.playStream = streams.length > 1 ? (pipeline(streams, noop) as any as Readable) : streams[0]!;\n\t\tthis.metadata = metadata;\n\t\tthis.silencePaddingFrames = silencePaddingFrames;\n\n\t\tfor (const stream of streams) {\n\t\t\tif (stream instanceof prism.VolumeTransformer) {\n\t\t\t\tthis.volume = stream;\n\t\t\t} else if (stream instanceof prism.opus.Encoder) {\n\t\t\t\tthis.encoder = stream;\n\t\t\t}\n\t\t}\n\n\t\tthis.playStream.once('readable', () => (this.started = true));\n\t}\n\n\t/**\n\t * Whether this resource is readable. If the underlying resource is no longer readable, this will still return true\n\t * while there are silence padding frames left to play.\n\t */\n\tpublic get readable() {\n\t\tif (this.silenceRemaining === 0) return false;\n\t\tconst real = this.playStream.readable;\n\t\tif (!real) {\n\t\t\tif (this.silenceRemaining === -1) this.silenceRemaining = this.silencePaddingFrames;\n\t\t\treturn this.silenceRemaining !== 0;\n\t\t}\n\t\treturn real;\n\t}\n\n\t/**\n\t * Whether this resource has ended or not.\n\t */\n\tpublic get ended() {\n\t\treturn this.playStream.readableEnded || this.playStream.destroyed || this.silenceRemaining === 0;\n\t}\n\n\t/**\n\t * Attempts to read an Opus packet from the audio resource. If a packet is available, the playbackDuration\n\t * is incremented.\n\t *\n\t * @remarks\n\t * It is advisable to check that the playStream is readable before calling this method. While no runtime\n\t * errors will be thrown, you should check that the resource is still available before attempting to\n\t * read from it.\n\t *\n\t * @internal\n\t */\n\tpublic read(): Buffer | null {\n\t\tif (this.silenceRemaining === 0) {\n\t\t\treturn null;\n\t\t} else if (this.silenceRemaining > 0) {\n\t\t\tthis.silenceRemaining--;\n\t\t\treturn SILENCE_FRAME;\n\t\t}\n\t\tconst packet = this.playStream.read() as Buffer | null;\n\t\tif (packet) {\n\t\t\tthis.playbackDuration += 20;\n\t\t}\n\t\treturn packet;\n\t}\n}\n\n/**\n * Ensures that a path contains at least one volume transforming component.\n *\n * @param path - The path to validate constraints on\n */\nexport const VOLUME_CONSTRAINT = (path: Edge[]) => path.some((edge) => edge.type === TransformerType.InlineVolume);\n\nexport const NO_CONSTRAINT = () => true;\n\n/**\n * Tries to infer the type of a stream to aid with transcoder pipelining.\n *\n * @param stream - The stream to infer the type of\n */\nexport function inferStreamType(stream: Readable): {\n\tstreamType: StreamType;\n\thasVolume: boolean;\n} {\n\tif (stream instanceof prism.opus.Encoder) {\n\t\treturn { streamType: StreamType.Opus, hasVolume: false };\n\t} else if (stream instanceof prism.opus.Decoder) {\n\t\treturn { streamType: StreamType.Raw, hasVolume: false };\n\t} else if (stream instanceof prism.VolumeTransformer) {\n\t\treturn { streamType: StreamType.Raw, hasVolume: true };\n\t} else if (stream instanceof prism.opus.OggDemuxer) {\n\t\treturn { streamType: StreamType.Opus, hasVolume: false };\n\t} else if (stream instanceof prism.opus.WebmDemuxer) {\n\t\treturn { streamType: StreamType.Opus, hasVolume: false };\n\t}\n\treturn { streamType: StreamType.Arbitrary, hasVolume: false };\n}\n\n/**\n * Creates an audio resource that can be played by audio players.\n *\n * @remarks\n * If the input is given as a string, then the inputType option will be overridden and FFmpeg will be used.\n *\n * If the input is not in the correct format, then a pipeline of transcoders and transformers will be created\n * to ensure that the resultant stream is in the correct format for playback. This could involve using FFmpeg,\n * Opus transcoders, and Ogg/WebM demuxers.\n *\n * @param input - The resource to play\n * @param options - Configurable options for creating the resource\n *\n * @template T - the type for the metadata (if any) of the audio resource\n */\nexport function createAudioResource(\n\tinput: string | Readable,\n\toptions: CreateAudioResourceOptions &\n\t\tPick<\n\t\t\tT extends null | undefined ? CreateAudioResourceOptions : Required>,\n\t\t\t'metadata'\n\t\t>,\n): AudioResource;\n\n/**\n * Creates an audio resource that can be played by audio players.\n *\n * @remarks\n * If the input is given as a string, then the inputType option will be overridden and FFmpeg will be used.\n *\n * If the input is not in the correct format, then a pipeline of transcoders and transformers will be created\n * to ensure that the resultant stream is in the correct format for playback. This could involve using FFmpeg,\n * Opus transcoders, and Ogg/WebM demuxers.\n *\n * @param input - The resource to play\n * @param options - Configurable options for creating the resource\n *\n * @template T - the type for the metadata (if any) of the audio resource\n */\nexport function createAudioResource(\n\tinput: string | Readable,\n\toptions?: Omit, 'metadata'>,\n): AudioResource;\n\n/**\n * Creates an audio resource that can be played by audio players.\n *\n * @remarks\n * If the input is given as a string, then the inputType option will be overridden and FFmpeg will be used.\n *\n * If the input is not in the correct format, then a pipeline of transcoders and transformers will be created\n * to ensure that the resultant stream is in the correct format for playback. This could involve using FFmpeg,\n * Opus transcoders, and Ogg/WebM demuxers.\n *\n * @param input - The resource to play\n * @param options - Configurable options for creating the resource\n *\n * @template T - the type for the metadata (if any) of the audio resource\n */\nexport function createAudioResource(\n\tinput: string | Readable,\n\toptions: CreateAudioResourceOptions = {},\n): AudioResource {\n\tlet inputType = options.inputType;\n\tlet needsInlineVolume = Boolean(options.inlineVolume);\n\n\t// string inputs can only be used with FFmpeg\n\tif (typeof input === 'string') {\n\t\tinputType = StreamType.Arbitrary;\n\t} else if (typeof inputType === 'undefined') {\n\t\tconst analysis = inferStreamType(input);\n\t\tinputType = analysis.streamType;\n\t\tneedsInlineVolume = needsInlineVolume && !analysis.hasVolume;\n\t}\n\n\tconst transformerPipeline = findPipeline(inputType, needsInlineVolume ? VOLUME_CONSTRAINT : NO_CONSTRAINT);\n\n\tif (transformerPipeline.length === 0) {\n\t\tif (typeof input === 'string') throw new Error(`Invalid pipeline constructed for string resource '${input}'`);\n\t\t// No adjustments required\n\t\treturn new AudioResource([], [input], (options.metadata ?? null) as T, options.silencePaddingFrames ?? 5);\n\t}\n\tconst streams = transformerPipeline.map((edge) => edge.transformer(input));\n\tif (typeof input !== 'string') streams.unshift(input);\n\n\treturn new AudioResource(\n\t\ttransformerPipeline,\n\t\tstreams,\n\t\t(options.metadata ?? null) as T,\n\t\toptions.silencePaddingFrames ?? 5,\n\t);\n}\n","import type { Readable } from 'node:stream';\nimport prism from 'prism-media';\n\n/**\n * This module creates a Transformer Graph to figure out what the most efficient way\n * of transforming the input stream into something playable would be.\n */\n\nconst FFMPEG_PCM_ARGUMENTS = ['-analyzeduration', '0', '-loglevel', '0', '-f', 's16le', '-ar', '48000', '-ac', '2'];\nconst FFMPEG_OPUS_ARGUMENTS = [\n\t'-analyzeduration',\n\t'0',\n\t'-loglevel',\n\t'0',\n\t'-acodec',\n\t'libopus',\n\t'-f',\n\t'opus',\n\t'-ar',\n\t'48000',\n\t'-ac',\n\t'2',\n];\n\n/**\n * The different types of stream that can exist within the pipeline.\n *\n * @remarks\n * - `Arbitrary` - the type of the stream at this point is unknown.\n * - `Raw` - the stream at this point is s16le PCM.\n * - `OggOpus` - the stream at this point is Opus audio encoded in an Ogg wrapper.\n * - `WebmOpus` - the stream at this point is Opus audio encoded in a WebM wrapper.\n * - `Opus` - the stream at this point is Opus audio, and the stream is in object-mode. This is ready to play.\n */\nexport enum StreamType {\n\tArbitrary = 'arbitrary',\n\tRaw = 'raw',\n\tOggOpus = 'ogg/opus',\n\tWebmOpus = 'webm/opus',\n\tOpus = 'opus',\n}\n\n/**\n * The different types of transformers that can exist within the pipeline.\n */\nexport enum TransformerType {\n\tFFmpegPCM = 'ffmpeg pcm',\n\tFFmpegOgg = 'ffmpeg ogg',\n\tOpusEncoder = 'opus encoder',\n\tOpusDecoder = 'opus decoder',\n\tOggOpusDemuxer = 'ogg/opus demuxer',\n\tWebmOpusDemuxer = 'webm/opus demuxer',\n\tInlineVolume = 'volume transformer',\n}\n\n/**\n * Represents a pathway from one stream type to another using a transformer.\n */\nexport interface Edge {\n\tfrom: Node;\n\tto: Node;\n\tcost: number;\n\ttransformer: (input: string | Readable) => Readable;\n\ttype: TransformerType;\n}\n\n/**\n * Represents a type of stream within the graph, e.g. an Opus stream, or a stream of raw audio.\n */\nexport class Node {\n\t/**\n\t * The outbound edges from this node.\n\t */\n\tpublic readonly edges: Edge[] = [];\n\n\t/**\n\t * The type of stream for this node.\n\t */\n\tpublic readonly type: StreamType;\n\n\tpublic constructor(type: StreamType) {\n\t\tthis.type = type;\n\t}\n\n\t/**\n\t * Creates an outbound edge from this node.\n\t *\n\t * @param edge - The edge to create\n\t */\n\tpublic addEdge(edge: Omit) {\n\t\tthis.edges.push({ ...edge, from: this });\n\t}\n}\n\n// Create a node for each stream type\nconst NODES = new Map();\nfor (const streamType of Object.values(StreamType)) {\n\tNODES.set(streamType, new Node(streamType));\n}\n\n/**\n * Gets a node from its stream type.\n *\n * @param type - The stream type of the target node\n */\nexport function getNode(type: StreamType) {\n\tconst node = NODES.get(type);\n\tif (!node) throw new Error(`Node type '${type}' does not exist!`);\n\treturn node;\n}\n\ngetNode(StreamType.Raw).addEdge({\n\ttype: TransformerType.OpusEncoder,\n\tto: getNode(StreamType.Opus),\n\tcost: 1.5,\n\ttransformer: () => new prism.opus.Encoder({ rate: 48000, channels: 2, frameSize: 960 }),\n});\n\ngetNode(StreamType.Opus).addEdge({\n\ttype: TransformerType.OpusDecoder,\n\tto: getNode(StreamType.Raw),\n\tcost: 1.5,\n\ttransformer: () => new prism.opus.Decoder({ rate: 48000, channels: 2, frameSize: 960 }),\n});\n\ngetNode(StreamType.OggOpus).addEdge({\n\ttype: TransformerType.OggOpusDemuxer,\n\tto: getNode(StreamType.Opus),\n\tcost: 1,\n\ttransformer: () => new prism.opus.OggDemuxer(),\n});\n\ngetNode(StreamType.WebmOpus).addEdge({\n\ttype: TransformerType.WebmOpusDemuxer,\n\tto: getNode(StreamType.Opus),\n\tcost: 1,\n\ttransformer: () => new prism.opus.WebmDemuxer(),\n});\n\nconst FFMPEG_PCM_EDGE: Omit = {\n\ttype: TransformerType.FFmpegPCM,\n\tto: getNode(StreamType.Raw),\n\tcost: 2,\n\ttransformer: (input) =>\n\t\tnew prism.FFmpeg({\n\t\t\targs: typeof input === 'string' ? ['-i', input, ...FFMPEG_PCM_ARGUMENTS] : FFMPEG_PCM_ARGUMENTS,\n\t\t}),\n};\n\ngetNode(StreamType.Arbitrary).addEdge(FFMPEG_PCM_EDGE);\ngetNode(StreamType.OggOpus).addEdge(FFMPEG_PCM_EDGE);\ngetNode(StreamType.WebmOpus).addEdge(FFMPEG_PCM_EDGE);\n\ngetNode(StreamType.Raw).addEdge({\n\ttype: TransformerType.InlineVolume,\n\tto: getNode(StreamType.Raw),\n\tcost: 0.5,\n\ttransformer: () => new prism.VolumeTransformer({ type: 's16le' }),\n});\n\n// Try to enable FFmpeg Ogg optimizations\nfunction canEnableFFmpegOptimizations(): boolean {\n\ttry {\n\t\treturn prism.FFmpeg.getInfo().output.includes('--enable-libopus');\n\t} catch {}\n\treturn false;\n}\n\nif (canEnableFFmpegOptimizations()) {\n\tconst FFMPEG_OGG_EDGE: Omit = {\n\t\ttype: TransformerType.FFmpegOgg,\n\t\tto: getNode(StreamType.OggOpus),\n\t\tcost: 2,\n\t\ttransformer: (input) =>\n\t\t\tnew prism.FFmpeg({\n\t\t\t\targs: typeof input === 'string' ? ['-i', input, ...FFMPEG_OPUS_ARGUMENTS] : FFMPEG_OPUS_ARGUMENTS,\n\t\t\t}),\n\t};\n\tgetNode(StreamType.Arbitrary).addEdge(FFMPEG_OGG_EDGE);\n\t// Include Ogg and WebM as well in case they have different sampling rates or are mono instead of stereo\n\t// at the moment, this will not do anything. However, if/when detection for correct Opus headers is\n\t// implemented, this will help inform the voice engine that it is able to transcode the audio.\n\tgetNode(StreamType.OggOpus).addEdge(FFMPEG_OGG_EDGE);\n\tgetNode(StreamType.WebmOpus).addEdge(FFMPEG_OGG_EDGE);\n}\n\n/**\n * Represents a step in the path from node A to node B.\n */\ninterface Step {\n\t/**\n\t * The next step.\n\t */\n\tnext?: Step;\n\n\t/**\n\t * The cost of the steps after this step.\n\t */\n\tcost: number;\n\n\t/**\n\t * The edge associated with this step.\n\t */\n\tedge?: Edge;\n}\n\n/**\n * Finds the shortest cost path from node A to node B.\n *\n * @param from - The start node\n * @param constraints - Extra validation for a potential solution. Takes a path, returns true if the path is valid\n * @param goal - The target node\n * @param path - The running path\n * @param depth - The number of remaining recursions\n */\nfunction findPath(\n\tfrom: Node,\n\tconstraints: (path: Edge[]) => boolean,\n\tgoal = getNode(StreamType.Opus),\n\tpath: Edge[] = [],\n\tdepth = 5,\n): Step {\n\tif (from === goal && constraints(path)) {\n\t\treturn { cost: 0 };\n\t} else if (depth === 0) {\n\t\treturn { cost: Infinity };\n\t}\n\n\tlet currentBest: Step | undefined = undefined;\n\tfor (const edge of from.edges) {\n\t\tif (currentBest && edge.cost > currentBest.cost) continue;\n\t\tconst next = findPath(edge.to, constraints, goal, [...path, edge], depth - 1);\n\t\tconst cost = edge.cost + next.cost;\n\t\tif (!currentBest || cost < currentBest.cost) {\n\t\t\tcurrentBest = { cost, edge, next };\n\t\t}\n\t}\n\treturn currentBest ?? { cost: Infinity };\n}\n\n/**\n * Takes the solution from findPath and assembles it into a list of edges.\n *\n * @param step - The first step of the path\n */\nfunction constructPipeline(step: Step) {\n\tconst edges = [];\n\tlet current: Step | undefined = step;\n\twhile (current?.edge) {\n\t\tedges.push(current.edge);\n\t\tcurrent = current.next;\n\t}\n\treturn edges;\n}\n\n/**\n * Finds the lowest-cost pipeline to convert the input stream type into an Opus stream.\n *\n * @param from - The stream type to start from\n * @param constraint - Extra constraints that may be imposed on potential solution\n */\nexport function findPipeline(from: StreamType, constraint: (path: Edge[]) => boolean) {\n\treturn constructPipeline(findPath(getNode(from), constraint));\n}\n","/* eslint-disable @typescript-eslint/no-var-requires */\n/* eslint-disable @typescript-eslint/no-require-imports */\nimport { resolve, dirname } from 'node:path';\nimport prism from 'prism-media';\n\n/**\n * Tries to find the package.json file for a given module.\n *\n * @param dir - The directory to look in\n * @param packageName - The name of the package to look for\n * @param depth - The maximum recursion depth\n */\nfunction findPackageJSON(\n\tdir: string,\n\tpackageName: string,\n\tdepth: number,\n): { name: string; version: string } | undefined {\n\tif (depth === 0) return undefined;\n\tconst attemptedPath = resolve(dir, './package.json');\n\ttry {\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\tconst pkg = require(attemptedPath);\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access\n\t\tif (pkg.name !== packageName) throw new Error('package.json does not match');\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-return\n\t\treturn pkg;\n\t} catch (err) {\n\t\treturn findPackageJSON(resolve(dir, '..'), packageName, depth - 1);\n\t}\n}\n\n/**\n * Tries to find the version of a dependency.\n *\n * @param name - The package to find the version of\n */\nfunction version(name: string): string {\n\ttry {\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment\n\t\tconst pkg =\n\t\t\tname === '@discordjs/voice'\n\t\t\t\t? require('../../package.json')\n\t\t\t\t: findPackageJSON(dirname(require.resolve(name)), name, 3);\n\t\t// eslint-disable-next-line @typescript-eslint/no-unsafe-return, @typescript-eslint/no-unsafe-member-access\n\t\treturn pkg?.version ?? 'not found';\n\t} catch (err) {\n\t\treturn 'not found';\n\t}\n}\n\n/**\n * Generates a report of the dependencies used by the \\@discordjs/voice module.\n * Useful for debugging.\n */\nexport function generateDependencyReport() {\n\tconst report = [];\n\tconst addVersion = (name: string) => report.push(`- ${name}: ${version(name)}`);\n\t// general\n\treport.push('Core Dependencies');\n\taddVersion('@discordjs/voice');\n\taddVersion('prism-media');\n\treport.push('');\n\n\t// opus\n\treport.push('Opus Libraries');\n\taddVersion('@discordjs/opus');\n\taddVersion('opusscript');\n\treport.push('');\n\n\t// encryption\n\treport.push('Encryption Libraries');\n\taddVersion('sodium-native');\n\taddVersion('sodium');\n\taddVersion('libsodium-wrappers');\n\taddVersion('tweetnacl');\n\treport.push('');\n\n\t// ffmpeg\n\treport.push('FFmpeg');\n\ttry {\n\t\tconst info = prism.FFmpeg.getInfo();\n\t\treport.push(`- version: ${info.version}`);\n\t\treport.push(`- libopus: ${info.output.includes('--enable-libopus') ? 'yes' : 'no'}`);\n\t} catch (err) {\n\t\treport.push('- not found');\n\t}\n\n\treturn ['-'.repeat(50), ...report, '-'.repeat(50)].join('\\n');\n}\n","import EventEmitter, { once } from 'node:events';\nimport { abortAfter } from './abortAfter';\nimport type { VoiceConnection, VoiceConnectionStatus } from '../VoiceConnection';\nimport type { AudioPlayer, AudioPlayerStatus } from '../audio/AudioPlayer';\n\n/**\n * Allows a voice connection a specified amount of time to enter a given state, otherwise rejects with an error.\n *\n * @param target - The voice connection that we want to observe the state change for\n * @param status - The status that the voice connection should be in\n * @param timeoutOrSignal - The maximum time we are allowing for this to occur, or a signal that will abort the operation\n */\nexport function entersState(\n\ttarget: VoiceConnection,\n\tstatus: VoiceConnectionStatus,\n\ttimeoutOrSignal: number | AbortSignal,\n): Promise;\n\n/**\n * Allows an audio player a specified amount of time to enter a given state, otherwise rejects with an error.\n *\n * @param target - The audio player that we want to observe the state change for\n * @param status - The status that the audio player should be in\n * @param timeoutOrSignal - The maximum time we are allowing for this to occur, or a signal that will abort the operation\n */\nexport function entersState(\n\ttarget: AudioPlayer,\n\tstatus: AudioPlayerStatus,\n\ttimeoutOrSignal: number | AbortSignal,\n): Promise;\n\n/**\n * Allows a target a specified amount of time to enter a given state, otherwise rejects with an error.\n *\n * @param target - The object that we want to observe the state change for\n * @param status - The status that the target should be in\n * @param timeoutOrSignal - The maximum time we are allowing for this to occur, or a signal that will abort the operation\n */\nexport async function entersState(\n\ttarget: T,\n\tstatus: VoiceConnectionStatus | AudioPlayerStatus,\n\ttimeoutOrSignal: number | AbortSignal,\n) {\n\tif (target.state.status !== status) {\n\t\tconst [ac, signal] =\n\t\t\ttypeof timeoutOrSignal === 'number' ? abortAfter(timeoutOrSignal) : [undefined, timeoutOrSignal];\n\t\ttry {\n\t\t\tawait once(target as EventEmitter, status, { signal });\n\t\t} finally {\n\t\t\tac?.abort();\n\t\t}\n\t}\n\treturn target;\n}\n","/**\n * Creates an abort controller that aborts after the given time.\n *\n * @param delay - The time in milliseconds to wait before aborting\n */\nexport function abortAfter(delay: number): [AbortController, AbortSignal] {\n\tconst ac = new AbortController();\n\tconst timeout = setTimeout(() => ac.abort(), delay);\n\t// @ts-expect-error\n\t// eslint-disable-next-line @typescript-eslint/no-unsafe-call\n\tac.signal.addEventListener('abort', () => clearTimeout(timeout));\n\treturn [ac, ac.signal];\n}\n","import { Readable } from 'node:stream';\nimport prism from 'prism-media';\nimport { noop } from './util';\nimport { StreamType } from '..';\n\n/**\n * Takes an Opus Head, and verifies whether the associated Opus audio is suitable to play in a Discord voice channel.\n *\n * @param opusHead - The Opus Head to validate\n *\n * @returns `true` if suitable to play in a Discord voice channel, otherwise `false`\n */\nexport function validateDiscordOpusHead(opusHead: Buffer): boolean {\n\tconst channels = opusHead.readUInt8(9);\n\tconst sampleRate = opusHead.readUInt32LE(12);\n\treturn channels === 2 && sampleRate === 48000;\n}\n\n/**\n * The resulting information after probing an audio stream\n */\nexport interface ProbeInfo {\n\t/**\n\t * The readable audio stream to use. You should use this rather than the input stream, as the probing\n\t * function can sometimes read the input stream to its end and cause the stream to close.\n\t */\n\tstream: Readable;\n\n\t/**\n\t * The recommended stream type for this audio stream.\n\t */\n\ttype: StreamType;\n}\n\n/**\n * Attempt to probe a readable stream to figure out whether it can be demuxed using an Ogg or WebM Opus demuxer.\n *\n * @param stream - The readable stream to probe\n * @param probeSize - The number of bytes to attempt to read before giving up on the probe\n * @param validator - The Opus Head validator function\n *\n * @experimental\n */\nexport function demuxProbe(\n\tstream: Readable,\n\tprobeSize = 1024,\n\tvalidator = validateDiscordOpusHead,\n): Promise {\n\treturn new Promise((resolve, reject) => {\n\t\t// Preconditions\n\t\tif (stream.readableObjectMode) return reject(new Error('Cannot probe a readable stream in object mode'));\n\t\tif (stream.readableEnded) return reject(new Error('Cannot probe a stream that has ended'));\n\n\t\tlet readBuffer = Buffer.alloc(0);\n\n\t\tlet resolved: StreamType | undefined = undefined;\n\n\t\tconst finish = (type: StreamType) => {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\t\tstream.off('data', onData);\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\t\tstream.off('close', onClose);\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\t\tstream.off('end', onClose);\n\t\t\tstream.pause();\n\t\t\tresolved = type;\n\t\t\tif (stream.readableEnded) {\n\t\t\t\tresolve({\n\t\t\t\t\tstream: Readable.from(readBuffer),\n\t\t\t\t\ttype,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (readBuffer.length > 0) {\n\t\t\t\t\tstream.push(readBuffer);\n\t\t\t\t}\n\t\t\t\tresolve({\n\t\t\t\t\tstream,\n\t\t\t\t\ttype,\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\n\t\tconst foundHead = (type: StreamType) => (head: Buffer) => {\n\t\t\tif (validator(head)) {\n\t\t\t\tfinish(type);\n\t\t\t}\n\t\t};\n\n\t\tconst webm = new prism.opus.WebmDemuxer();\n\t\twebm.once('error', noop);\n\t\twebm.on('head', foundHead(StreamType.WebmOpus));\n\n\t\tconst ogg = new prism.opus.OggDemuxer();\n\t\togg.once('error', noop);\n\t\togg.on('head', foundHead(StreamType.OggOpus));\n\n\t\tconst onClose = () => {\n\t\t\tif (!resolved) {\n\t\t\t\tfinish(StreamType.Arbitrary);\n\t\t\t}\n\t\t};\n\n\t\tconst onData = (buffer: Buffer) => {\n\t\t\treadBuffer = Buffer.concat([readBuffer, buffer]);\n\n\t\t\twebm.write(buffer);\n\t\t\togg.write(buffer);\n\n\t\t\tif (readBuffer.length >= probeSize) {\n\t\t\t\tstream.off('data', onData);\n\t\t\t\tstream.pause();\n\t\t\t\tprocess.nextTick(onClose);\n\t\t\t}\n\t\t};\n\n\t\tstream.once('error', reject);\n\t\tstream.on('data', onData);\n\t\tstream.once('close', onClose);\n\t\tstream.once('end', onClose);\n\t});\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AACA;;;ACDA;AAkBO,uCAAuC,QAAoB;AACjE,SAAO;AAAA,IACN,IAAI,eAAe;AAAA,IACnB,GAAG;AAAA,MACF,UAAU,OAAO;AAAA,MACjB,YAAY,OAAO;AAAA,MACnB,WAAW,OAAO;AAAA,MAClB,WAAW,OAAO;AAAA,IACnB;AAAA,EACD;AACD;AAVgB;AAahB,IAAM,SAAS,oBAAI,IAA0C;AAC7D,OAAO,IAAI,WAAW,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X,UAAI,OAAO,eAAe;AACzB,iBAAQ;AAAA,UACP,QAAQ,UAAS,KAAK,UAAU;AAAA,UAChC;AAAA,QACD,CAAC;AAAA,MACF,OAAO;AACN,YAAI,WAAW,SAAS,GAAG;AAC1B,iBAAO,KAAK,UAAU;AAAA,QACvB;AACA,iBAAQ;AAAA,UACP;AAAA,UACA;AAAA,QACD,CAAC;AAAA,MACF;AAAA,IACD,GAvBe;AAyBf,UAAM,YAAY,wBAAC,SAAqB,CAAC,SAAiB;AACzD,UAAI,UAAU,IAAI,GAAG;AACpB,eAAO,IAAI;AAAA,MACZ;AAAA,IACD,GAJkB;AAMlB,UAAM,OAAO,IAAI,OAAM,KAAK,YAAY;AACxC,SAAK,KAAK,SAAS,IAAI;AACvB,SAAK,GAAG,QAAQ,UAAU,0BAAmB,CAAC;AAE9C,UAAM,MAAM,IAAI,OAAM,KAAK,WAAW;AACtC,QAAI,KAAK,SAAS,IAAI;AACtB,QAAI,GAAG,QAAQ,UAAU,wBAAkB,CAAC;AAE5C,UAAM,UAAU,6BAAM;AACrB,UAAI,CAAC,UAAU;AACd,eAAO,2BAAoB;AAAA,MAC5B;AAAA,IACD,GAJgB;AAMhB,UAAM,SAAS,wBAAC,WAAmB;AAClC,mBAAa,OAAO,OAAO,CAAC,YAAY,MAAM,CAAC;AAE/C,WAAK,MAAM,MAAM;AACjB,UAAI,MAAM,MAAM;AAEhB,UAAI,WAAW,UAAU,WAAW;AACnC,eAAO,IAAI,QAAQ,MAAM;AACzB,eAAO,MAAM;AACb,gBAAQ,SAAS,OAAO;AAAA,MACzB;AAAA,IACD,GAXe;AAaf,WAAO,KAAK,SAAS,MAAM;AAC3B,WAAO,GAAG,QAAQ,MAAM;AACxB,WAAO,KAAK,SAAS,OAAO;AAC5B,WAAO,KAAK,OAAO,OAAO;AAAA,EAC3B,CAAC;AACF;AA7EgB;","names":[]} \ No newline at end of file +{"version":3,"sources":["../src/VoiceConnection.ts","../src/DataStore.ts","../src/networking/Networking.ts","../src/util/Secretbox.ts","../src/util/util.ts","../src/networking/VoiceUDPSocket.ts","../src/networking/VoiceWebSocket.ts","../src/receive/VoiceReceiver.ts","../src/receive/AudioReceiveStream.ts","../src/audio/AudioPlayer.ts","../src/audio/AudioPlayerError.ts","../src/audio/PlayerSubscription.ts","../src/receive/SSRCMap.ts","../src/receive/SpeakingMap.ts","../src/joinVoiceChannel.ts","../src/audio/AudioResource.ts","../src/audio/TransformerGraph.ts","../src/util/generateDependencyReport.ts","../src/util/entersState.ts","../src/util/abortAfter.ts","../src/util/demuxProbe.ts","../src/index.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\nimport type { Buffer } from 'node:buffer';\nimport { EventEmitter } from 'node:events';\nimport type { GatewayVoiceServerUpdateDispatchData, GatewayVoiceStateUpdateDispatchData } from 'discord-api-types/v10';\nimport type { JoinConfig } from './DataStore';\nimport {\n\tgetVoiceConnection,\n\tcreateJoinVoiceChannelPayload,\n\ttrackVoiceConnection,\n\tuntrackVoiceConnection,\n} from './DataStore';\nimport type { AudioPlayer } from './audio/AudioPlayer';\nimport type { PlayerSubscription } from './audio/PlayerSubscription';\nimport type { VoiceWebSocket, VoiceUDPSocket } from './networking';\nimport { Networking, NetworkingStatusCode, type NetworkingState } from './networking/Networking';\nimport { VoiceReceiver } from './receive/index';\nimport type { DiscordGatewayAdapterImplementerMethods } from './util/adapter';\nimport { noop } from './util/util';\nimport type { CreateVoiceConnectionOptions } from './index';\n\n/**\n * The various status codes a voice connection can hold at any one time.\n */\nexport enum VoiceConnectionStatus {\n\t/**\n\t * The `VOICE_SERVER_UPDATE` and `VOICE_STATE_UPDATE` packets have been received, now attempting to establish a voice connection.\n\t */\n\tConnecting = 'connecting',\n\n\t/**\n\t * The voice connection has been destroyed and untracked, it cannot be reused.\n\t */\n\tDestroyed = 'destroyed',\n\n\t/**\n\t * The voice connection has either been severed or not established.\n\t */\n\tDisconnected = 'disconnected',\n\n\t/**\n\t * A voice connection has been established, and is ready to be used.\n\t */\n\tReady = 'ready',\n\n\t/**\n\t * Sending a packet to the main Discord gateway to indicate we want to change our voice state.\n\t */\n\tSignalling = 'signalling',\n}\n\n/**\n * The state that a VoiceConnection will be in when it is waiting to receive a VOICE_SERVER_UPDATE and\n * VOICE_STATE_UPDATE packet from Discord, provided by the adapter.\n */\nexport interface VoiceConnectionSignallingState {\n\tadapter: DiscordGatewayAdapterImplementerMethods;\n\tstatus: VoiceConnectionStatus.Signalling;\n\tsubscription?: PlayerSubscription | undefined;\n}\n\n/**\n * The reasons a voice connection can be in the disconnected state.\n */\nexport enum VoiceConnectionDisconnectReason {\n\t/**\n\t * When the WebSocket connection has been closed.\n\t */\n\tWebSocketClose,\n\n\t/**\n\t * When the adapter was unable to send a message requested by the VoiceConnection.\n\t */\n\tAdapterUnavailable,\n\n\t/**\n\t * When a VOICE_SERVER_UPDATE packet is received with a null endpoint, causing the connection to be severed.\n\t */\n\tEndpointRemoved,\n\n\t/**\n\t * When a manual disconnect was requested.\n\t */\n\tManual,\n}\n\n/**\n * The state that a VoiceConnection will be in when it is not connected to a Discord voice server nor is\n * it attempting to connect. You can manually attempt to reconnect using VoiceConnection#reconnect.\n */\nexport interface VoiceConnectionDisconnectedBaseState {\n\tadapter: DiscordGatewayAdapterImplementerMethods;\n\tstatus: VoiceConnectionStatus.Disconnected;\n\tsubscription?: PlayerSubscription | undefined;\n}\n\n/**\n * The state that a VoiceConnection will be in when it is not connected to a Discord voice server nor is\n * it attempting to connect. You can manually attempt to reconnect using VoiceConnection#reconnect.\n */\nexport interface VoiceConnectionDisconnectedOtherState extends VoiceConnectionDisconnectedBaseState {\n\treason: Exclude;\n}\n\n/**\n * The state that a VoiceConnection will be in when its WebSocket connection was closed.\n * You can manually attempt to reconnect using VoiceConnection#reconnect.\n */\nexport interface VoiceConnectionDisconnectedWebSocketState extends VoiceConnectionDisconnectedBaseState {\n\t/**\n\t * The close code of the WebSocket connection to the Discord voice server.\n\t */\n\tcloseCode: number;\n\n\treason: VoiceConnectionDisconnectReason.WebSocketClose;\n}\n\n/**\n * The states that a VoiceConnection can be in when it is not connected to a Discord voice server nor is\n * it attempting to connect. You can manually attempt to connect using VoiceConnection#reconnect.\n */\nexport type VoiceConnectionDisconnectedState =\n\t| VoiceConnectionDisconnectedOtherState\n\t| VoiceConnectionDisconnectedWebSocketState;\n\n/**\n * The state that a VoiceConnection will be in when it is establishing a connection to a Discord\n * voice server.\n */\nexport interface VoiceConnectionConnectingState {\n\tadapter: DiscordGatewayAdapterImplementerMethods;\n\tnetworking: Networking;\n\tstatus: VoiceConnectionStatus.Connecting;\n\tsubscription?: PlayerSubscription | undefined;\n}\n\n/**\n * The state that a VoiceConnection will be in when it has an active connection to a Discord\n * voice server.\n */\nexport interface VoiceConnectionReadyState {\n\tadapter: DiscordGatewayAdapterImplementerMethods;\n\tnetworking: Networking;\n\tstatus: VoiceConnectionStatus.Ready;\n\tsubscription?: PlayerSubscription | undefined;\n}\n\n/**\n * The state that a VoiceConnection will be in when it has been permanently been destroyed by the\n * user and untracked by the library. It cannot be reconnected, instead, a new VoiceConnection\n * needs to be established.\n */\nexport interface VoiceConnectionDestroyedState {\n\tstatus: VoiceConnectionStatus.Destroyed;\n}\n\n/**\n * The various states that a voice connection can be in.\n */\nexport type VoiceConnectionState =\n\t| VoiceConnectionConnectingState\n\t| VoiceConnectionDestroyedState\n\t| VoiceConnectionDisconnectedState\n\t| VoiceConnectionReadyState\n\t| VoiceConnectionSignallingState;\n\nexport interface VoiceConnection extends EventEmitter {\n\t/**\n\t * Emitted when there is an error emitted from the voice connection\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'error', listener: (error: Error) => void): this;\n\t/**\n\t * Emitted debugging information about the voice connection\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'debug', listener: (message: string) => void): this;\n\t/**\n\t * Emitted when the state of the voice connection changes\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'stateChange', listener: (oldState: VoiceConnectionState, newState: VoiceConnectionState) => void): this;\n\t/**\n\t * Emitted when the state of the voice connection changes to a specific status\n\t *\n\t * @eventProperty\n\t */\n\ton(\n\t\tevent: T,\n\t\tlistener: (oldState: VoiceConnectionState, newState: VoiceConnectionState & { status: T }) => void,\n\t): this;\n}\n\n/**\n * A connection to the voice server of a Guild, can be used to play audio in voice channels.\n */\nexport class VoiceConnection extends EventEmitter {\n\t/**\n\t * The number of consecutive rejoin attempts. Initially 0, and increments for each rejoin.\n\t * When a connection is successfully established, it resets to 0.\n\t */\n\tpublic rejoinAttempts: number;\n\n\t/**\n\t * The state of the voice connection.\n\t */\n\tprivate _state: VoiceConnectionState;\n\n\t/**\n\t * A configuration storing all the data needed to reconnect to a Guild's voice server.\n\t *\n\t * @internal\n\t */\n\tpublic readonly joinConfig: JoinConfig;\n\n\t/**\n\t * The two packets needed to successfully establish a voice connection. They are received\n\t * from the main Discord gateway after signalling to change the voice state.\n\t */\n\tprivate readonly packets: {\n\t\tserver: GatewayVoiceServerUpdateDispatchData | undefined;\n\t\tstate: GatewayVoiceStateUpdateDispatchData | undefined;\n\t};\n\n\t/**\n\t * The receiver of this voice connection. You should join the voice channel with `selfDeaf` set\n\t * to false for this feature to work properly.\n\t */\n\tpublic readonly receiver: VoiceReceiver;\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: ((message: string) => void) | null;\n\n\t/**\n\t * Creates a new voice connection.\n\t *\n\t * @param joinConfig - The data required to establish the voice connection\n\t * @param options - The options used to create this voice connection\n\t */\n\tpublic constructor(joinConfig: JoinConfig, options: CreateVoiceConnectionOptions) {\n\t\tsuper();\n\n\t\tthis.debug = options.debug ? (message: string) => this.emit('debug', message) : null;\n\t\tthis.rejoinAttempts = 0;\n\n\t\tthis.receiver = new VoiceReceiver(this);\n\n\t\tthis.onNetworkingClose = this.onNetworkingClose.bind(this);\n\t\tthis.onNetworkingStateChange = this.onNetworkingStateChange.bind(this);\n\t\tthis.onNetworkingError = this.onNetworkingError.bind(this);\n\t\tthis.onNetworkingDebug = this.onNetworkingDebug.bind(this);\n\n\t\tconst adapter = options.adapterCreator({\n\t\t\tonVoiceServerUpdate: (data) => this.addServerPacket(data),\n\t\t\tonVoiceStateUpdate: (data) => this.addStatePacket(data),\n\t\t\tdestroy: () => this.destroy(false),\n\t\t});\n\n\t\tthis._state = { status: VoiceConnectionStatus.Signalling, adapter };\n\n\t\tthis.packets = {\n\t\t\tserver: undefined,\n\t\t\tstate: undefined,\n\t\t};\n\n\t\tthis.joinConfig = joinConfig;\n\t}\n\n\t/**\n\t * The current state of the voice connection.\n\t */\n\tpublic get state() {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * Updates the state of the voice connection, performing clean-up operations where necessary.\n\t */\n\tpublic set state(newState: VoiceConnectionState) {\n\t\tconst oldState = this._state;\n\t\tconst oldNetworking = Reflect.get(oldState, 'networking') as Networking | undefined;\n\t\tconst newNetworking = Reflect.get(newState, 'networking') as Networking | undefined;\n\n\t\tconst oldSubscription = Reflect.get(oldState, 'subscription') as PlayerSubscription | undefined;\n\t\tconst newSubscription = Reflect.get(newState, 'subscription') as PlayerSubscription | undefined;\n\n\t\tif (oldNetworking !== newNetworking) {\n\t\t\tif (oldNetworking) {\n\t\t\t\toldNetworking.on('error', noop);\n\t\t\t\toldNetworking.off('debug', this.onNetworkingDebug);\n\t\t\t\toldNetworking.off('error', this.onNetworkingError);\n\t\t\t\toldNetworking.off('close', this.onNetworkingClose);\n\t\t\t\toldNetworking.off('stateChange', this.onNetworkingStateChange);\n\t\t\t\toldNetworking.destroy();\n\t\t\t}\n\n\t\t\tif (newNetworking) this.updateReceiveBindings(newNetworking.state, oldNetworking?.state);\n\t\t}\n\n\t\tif (newState.status === VoiceConnectionStatus.Ready) {\n\t\t\tthis.rejoinAttempts = 0;\n\t\t} else if (newState.status === VoiceConnectionStatus.Destroyed) {\n\t\t\tfor (const stream of this.receiver.subscriptions.values()) {\n\t\t\t\tif (!stream.destroyed) stream.destroy();\n\t\t\t}\n\t\t}\n\n\t\t// If destroyed, the adapter can also be destroyed so it can be cleaned up by the user\n\t\tif (oldState.status !== VoiceConnectionStatus.Destroyed && newState.status === VoiceConnectionStatus.Destroyed) {\n\t\t\toldState.adapter.destroy();\n\t\t}\n\n\t\tthis._state = newState;\n\n\t\tif (oldSubscription && oldSubscription !== newSubscription) {\n\t\t\toldSubscription.unsubscribe();\n\t\t}\n\n\t\tthis.emit('stateChange', oldState, newState);\n\t\tif (oldState.status !== newState.status) {\n\t\t\tthis.emit(newState.status, oldState, newState as any);\n\t\t}\n\t}\n\n\t/**\n\t * Registers a `VOICE_SERVER_UPDATE` packet to the voice connection. This will cause it to reconnect using the\n\t * new data provided in the packet.\n\t *\n\t * @param packet - The received `VOICE_SERVER_UPDATE` packet\n\t */\n\tprivate addServerPacket(packet: GatewayVoiceServerUpdateDispatchData) {\n\t\tthis.packets.server = packet;\n\t\tif (packet.endpoint) {\n\t\t\tthis.configureNetworking();\n\t\t} else if (this.state.status !== VoiceConnectionStatus.Destroyed) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.EndpointRemoved,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Registers a `VOICE_STATE_UPDATE` packet to the voice connection. Most importantly, it stores the id of the\n\t * channel that the client is connected to.\n\t *\n\t * @param packet - The received `VOICE_STATE_UPDATE` packet\n\t */\n\tprivate addStatePacket(packet: GatewayVoiceStateUpdateDispatchData) {\n\t\tthis.packets.state = packet;\n\n\t\tif (packet.self_deaf !== undefined) this.joinConfig.selfDeaf = packet.self_deaf;\n\t\tif (packet.self_mute !== undefined) this.joinConfig.selfMute = packet.self_mute;\n\t\tif (packet.channel_id) this.joinConfig.channelId = packet.channel_id;\n\t\t/*\n\t\t\tthe channel_id being null doesn't necessarily mean it was intended for the client to leave the voice channel\n\t\t\tas it may have disconnected due to network failure. This will be gracefully handled once the voice websocket\n\t\t\tdies, and then it is up to the user to decide how they wish to handle this.\n\t\t*/\n\t}\n\n\t/**\n\t * Called when the networking state changes, and the new ws/udp packet/message handlers need to be rebound\n\t * to the new instances.\n\t *\n\t * @param newState - The new networking state\n\t * @param oldState - The old networking state, if there is one\n\t */\n\tprivate updateReceiveBindings(newState: NetworkingState, oldState?: NetworkingState) {\n\t\tconst oldWs = Reflect.get(oldState ?? {}, 'ws') as VoiceWebSocket | undefined;\n\t\tconst newWs = Reflect.get(newState, 'ws') as VoiceWebSocket | undefined;\n\t\tconst oldUdp = Reflect.get(oldState ?? {}, 'udp') as VoiceUDPSocket | undefined;\n\t\tconst newUdp = Reflect.get(newState, 'udp') as VoiceUDPSocket | undefined;\n\n\t\tif (oldWs !== newWs) {\n\t\t\toldWs?.off('packet', this.receiver.onWsPacket);\n\t\t\tnewWs?.on('packet', this.receiver.onWsPacket);\n\t\t}\n\n\t\tif (oldUdp !== newUdp) {\n\t\t\toldUdp?.off('message', this.receiver.onUdpMessage);\n\t\t\tnewUdp?.on('message', this.receiver.onUdpMessage);\n\t\t}\n\n\t\tthis.receiver.connectionData = Reflect.get(newState, 'connectionData') ?? {};\n\t}\n\n\t/**\n\t * Attempts to configure a networking instance for this voice connection using the received packets.\n\t * Both packets are required, and any existing networking instance will be destroyed.\n\t *\n\t * @remarks\n\t * This is called when the voice server of the connection changes, e.g. if the bot is moved into a\n\t * different channel in the same guild but has a different voice server. In this instance, the connection\n\t * needs to be re-established to the new voice server.\n\t *\n\t * The connection will transition to the Connecting state when this is called.\n\t */\n\tpublic configureNetworking() {\n\t\tconst { server, state } = this.packets;\n\t\tif (!server || !state || this.state.status === VoiceConnectionStatus.Destroyed || !server.endpoint) return;\n\n\t\tconst networking = new Networking(\n\t\t\t{\n\t\t\t\tendpoint: server.endpoint,\n\t\t\t\tserverId: server.guild_id,\n\t\t\t\ttoken: server.token,\n\t\t\t\tsessionId: state.session_id,\n\t\t\t\tuserId: state.user_id,\n\t\t\t},\n\t\t\tBoolean(this.debug),\n\t\t);\n\n\t\tnetworking.once('close', this.onNetworkingClose);\n\t\tnetworking.on('stateChange', this.onNetworkingStateChange);\n\t\tnetworking.on('error', this.onNetworkingError);\n\t\tnetworking.on('debug', this.onNetworkingDebug);\n\n\t\tthis.state = {\n\t\t\t...this.state,\n\t\t\tstatus: VoiceConnectionStatus.Connecting,\n\t\t\tnetworking,\n\t\t};\n\t}\n\n\t/**\n\t * Called when the networking instance for this connection closes. If the close code is 4014 (do not reconnect),\n\t * the voice connection will transition to the Disconnected state which will store the close code. You can\n\t * decide whether or not to reconnect when this occurs by listening for the state change and calling reconnect().\n\t *\n\t * @remarks\n\t * If the close code was anything other than 4014, it is likely that the closing was not intended, and so the\n\t * VoiceConnection will signal to Discord that it would like to rejoin the channel. This automatically attempts\n\t * to re-establish the connection. This would be seen as a transition from the Ready state to the Signalling state.\n\t * @param code - The close code\n\t */\n\tprivate onNetworkingClose(code: number) {\n\t\tif (this.state.status === VoiceConnectionStatus.Destroyed) return;\n\t\t// If networking closes, try to connect to the voice channel again.\n\t\tif (code === 4_014) {\n\t\t\t// Disconnected - networking is already destroyed here\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.WebSocketClose,\n\t\t\t\tcloseCode: code,\n\t\t\t};\n\t\t} else {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Signalling,\n\t\t\t};\n\t\t\tthis.rejoinAttempts++;\n\t\t\tif (!this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) {\n\t\t\t\tthis.state = {\n\t\t\t\t\t...this.state,\n\t\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Called when the state of the networking instance changes. This is used to derive the state of the voice connection.\n\t *\n\t * @param oldState - The previous state\n\t * @param newState - The new state\n\t */\n\tprivate onNetworkingStateChange(oldState: NetworkingState, newState: NetworkingState) {\n\t\tthis.updateReceiveBindings(newState, oldState);\n\t\tif (oldState.code === newState.code) return;\n\t\tif (this.state.status !== VoiceConnectionStatus.Connecting && this.state.status !== VoiceConnectionStatus.Ready)\n\t\t\treturn;\n\n\t\tif (newState.code === NetworkingStatusCode.Ready) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Ready,\n\t\t\t};\n\t\t} else if (newState.code !== NetworkingStatusCode.Closed) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Connecting,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Propagates errors from the underlying network instance.\n\t *\n\t * @param error - The error to propagate\n\t */\n\tprivate onNetworkingError(error: Error) {\n\t\tthis.emit('error', error);\n\t}\n\n\t/**\n\t * Propagates debug messages from the underlying network instance.\n\t *\n\t * @param message - The debug message to propagate\n\t */\n\tprivate onNetworkingDebug(message: string) {\n\t\tthis.debug?.(`[NW] ${message}`);\n\t}\n\n\t/**\n\t * Prepares an audio packet for dispatch.\n\t *\n\t * @param buffer - The Opus packet to prepare\n\t */\n\tpublic prepareAudioPacket(buffer: Buffer) {\n\t\tconst state = this.state;\n\t\tif (state.status !== VoiceConnectionStatus.Ready) return;\n\t\treturn state.networking.prepareAudioPacket(buffer);\n\t}\n\n\t/**\n\t * Dispatches the previously prepared audio packet (if any)\n\t */\n\tpublic dispatchAudio() {\n\t\tconst state = this.state;\n\t\tif (state.status !== VoiceConnectionStatus.Ready) return;\n\t\treturn state.networking.dispatchAudio();\n\t}\n\n\t/**\n\t * Prepares an audio packet and dispatches it immediately.\n\t *\n\t * @param buffer - The Opus packet to play\n\t */\n\tpublic playOpusPacket(buffer: Buffer) {\n\t\tconst state = this.state;\n\t\tif (state.status !== VoiceConnectionStatus.Ready) return;\n\t\tstate.networking.prepareAudioPacket(buffer);\n\t\treturn state.networking.dispatchAudio();\n\t}\n\n\t/**\n\t * Destroys the VoiceConnection, preventing it from connecting to voice again.\n\t * This method should be called when you no longer require the VoiceConnection to\n\t * prevent memory leaks.\n\t *\n\t * @param adapterAvailable - Whether the adapter can be used\n\t */\n\tpublic destroy(adapterAvailable = true) {\n\t\tif (this.state.status === VoiceConnectionStatus.Destroyed) {\n\t\t\tthrow new Error('Cannot destroy VoiceConnection - it has already been destroyed');\n\t\t}\n\n\t\tif (getVoiceConnection(this.joinConfig.guildId, this.joinConfig.group) === this) {\n\t\t\tuntrackVoiceConnection(this);\n\t\t}\n\n\t\tif (adapterAvailable) {\n\t\t\tthis.state.adapter.sendPayload(createJoinVoiceChannelPayload({ ...this.joinConfig, channelId: null }));\n\t\t}\n\n\t\tthis.state = {\n\t\t\tstatus: VoiceConnectionStatus.Destroyed,\n\t\t};\n\t}\n\n\t/**\n\t * Disconnects the VoiceConnection, allowing the possibility of rejoining later on.\n\t *\n\t * @returns `true` if the connection was successfully disconnected\n\t */\n\tpublic disconnect() {\n\t\tif (\n\t\t\tthis.state.status === VoiceConnectionStatus.Destroyed ||\n\t\t\tthis.state.status === VoiceConnectionStatus.Signalling\n\t\t) {\n\t\t\treturn false;\n\t\t}\n\n\t\tthis.joinConfig.channelId = null;\n\t\tif (!this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) {\n\t\t\tthis.state = {\n\t\t\t\tadapter: this.state.adapter,\n\t\t\t\tsubscription: this.state.subscription,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t\t};\n\t\t\treturn false;\n\t\t}\n\n\t\tthis.state = {\n\t\t\tadapter: this.state.adapter,\n\t\t\treason: VoiceConnectionDisconnectReason.Manual,\n\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t};\n\t\treturn true;\n\t}\n\n\t/**\n\t * Attempts to rejoin (better explanation soon:tm:)\n\t *\n\t * @remarks\n\t * Calling this method successfully will automatically increment the `rejoinAttempts` counter,\n\t * which you can use to inform whether or not you'd like to keep attempting to reconnect your\n\t * voice connection.\n\t *\n\t * A state transition from Disconnected to Signalling will be observed when this is called.\n\t */\n\tpublic rejoin(joinConfig?: Omit) {\n\t\tif (this.state.status === VoiceConnectionStatus.Destroyed) {\n\t\t\treturn false;\n\t\t}\n\n\t\tconst notReady = this.state.status !== VoiceConnectionStatus.Ready;\n\n\t\tif (notReady) this.rejoinAttempts++;\n\t\tObject.assign(this.joinConfig, joinConfig);\n\t\tif (this.state.adapter.sendPayload(createJoinVoiceChannelPayload(this.joinConfig))) {\n\t\t\tif (notReady) {\n\t\t\t\tthis.state = {\n\t\t\t\t\t...this.state,\n\t\t\t\t\tstatus: VoiceConnectionStatus.Signalling,\n\t\t\t\t};\n\t\t\t}\n\n\t\t\treturn true;\n\t\t}\n\n\t\tthis.state = {\n\t\t\tadapter: this.state.adapter,\n\t\t\tsubscription: this.state.subscription,\n\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t};\n\t\treturn false;\n\t}\n\n\t/**\n\t * Updates the speaking status of the voice connection. This is used when audio players are done playing audio,\n\t * and need to signal that the connection is no longer playing audio.\n\t *\n\t * @param enabled - Whether or not to show as speaking\n\t */\n\tpublic setSpeaking(enabled: boolean) {\n\t\tif (this.state.status !== VoiceConnectionStatus.Ready) return false;\n\t\t// eslint-disable-next-line @typescript-eslint/no-confusing-void-expression\n\t\treturn this.state.networking.setSpeaking(enabled);\n\t}\n\n\t/**\n\t * Subscribes to an audio player, allowing the player to play audio on this voice connection.\n\t *\n\t * @param player - The audio player to subscribe to\n\t * @returns The created subscription\n\t */\n\tpublic subscribe(player: AudioPlayer) {\n\t\tif (this.state.status === VoiceConnectionStatus.Destroyed) return;\n\n\t\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\t\tconst subscription = player['subscribe'](this);\n\n\t\tthis.state = {\n\t\t\t...this.state,\n\t\t\tsubscription,\n\t\t};\n\n\t\treturn subscription;\n\t}\n\n\t/**\n\t * The latest ping (in milliseconds) for the WebSocket connection and audio playback for this voice\n\t * connection, if this data is available.\n\t *\n\t * @remarks\n\t * For this data to be available, the VoiceConnection must be in the Ready state, and its underlying\n\t * WebSocket connection and UDP socket must have had at least one ping-pong exchange.\n\t */\n\tpublic get ping() {\n\t\tif (\n\t\t\tthis.state.status === VoiceConnectionStatus.Ready &&\n\t\t\tthis.state.networking.state.code === NetworkingStatusCode.Ready\n\t\t) {\n\t\t\treturn {\n\t\t\t\tws: this.state.networking.state.ws.ping,\n\t\t\t\tudp: this.state.networking.state.udp.ping,\n\t\t\t};\n\t\t}\n\n\t\treturn {\n\t\t\tws: undefined,\n\t\t\tudp: undefined,\n\t\t};\n\t}\n\n\t/**\n\t * Called when a subscription of this voice connection to an audio player is removed.\n\t *\n\t * @param subscription - The removed subscription\n\t */\n\tprotected onSubscriptionRemoved(subscription: PlayerSubscription) {\n\t\tif (this.state.status !== VoiceConnectionStatus.Destroyed && this.state.subscription === subscription) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tsubscription: undefined,\n\t\t\t};\n\t\t}\n\t}\n}\n\n/**\n * Creates a new voice connection.\n *\n * @param joinConfig - The data required to establish the voice connection\n * @param options - The options to use when joining the voice channel\n */\nexport function createVoiceConnection(joinConfig: JoinConfig, options: CreateVoiceConnectionOptions) {\n\tconst payload = createJoinVoiceChannelPayload(joinConfig);\n\tconst existing = getVoiceConnection(joinConfig.guildId, joinConfig.group);\n\tif (existing && existing.state.status !== VoiceConnectionStatus.Destroyed) {\n\t\tif (existing.state.status === VoiceConnectionStatus.Disconnected) {\n\t\t\texisting.rejoin({\n\t\t\t\tchannelId: joinConfig.channelId,\n\t\t\t\tselfDeaf: joinConfig.selfDeaf,\n\t\t\t\tselfMute: joinConfig.selfMute,\n\t\t\t});\n\t\t} else if (!existing.state.adapter.sendPayload(payload)) {\n\t\t\texisting.state = {\n\t\t\t\t...existing.state,\n\t\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t\t};\n\t\t}\n\n\t\treturn existing;\n\t}\n\n\tconst voiceConnection = new VoiceConnection(joinConfig, options);\n\ttrackVoiceConnection(voiceConnection);\n\tif (\n\t\tvoiceConnection.state.status !== VoiceConnectionStatus.Destroyed &&\n\t\t!voiceConnection.state.adapter.sendPayload(payload)\n\t) {\n\t\tvoiceConnection.state = {\n\t\t\t...voiceConnection.state,\n\t\t\tstatus: VoiceConnectionStatus.Disconnected,\n\t\t\treason: VoiceConnectionDisconnectReason.AdapterUnavailable,\n\t\t};\n\t}\n\n\treturn voiceConnection;\n}\n","import { GatewayOpcodes } from 'discord-api-types/v10';\nimport type { VoiceConnection } from './VoiceConnection';\nimport type { AudioPlayer } from './audio/index';\n\nexport interface JoinConfig {\n\tchannelId: string | null;\n\tgroup: string;\n\tguildId: string;\n\tselfDeaf: boolean;\n\tselfMute: boolean;\n}\n\n/**\n * Sends a voice state update to the main websocket shard of a guild, to indicate joining/leaving/moving across\n * voice channels.\n *\n * @param config - The configuration to use when joining the voice channel\n */\nexport function createJoinVoiceChannelPayload(config: JoinConfig) {\n\treturn {\n\t\top: GatewayOpcodes.VoiceStateUpdate,\n\t\t// eslint-disable-next-line id-length\n\t\td: {\n\t\t\tguild_id: config.guildId,\n\t\t\tchannel_id: config.channelId,\n\t\t\tself_deaf: config.selfDeaf,\n\t\t\tself_mute: config.selfMute,\n\t\t},\n\t};\n}\n\n// Voice Connections\nconst groups = new Map>();\ngroups.set('default', new Map());\n\nfunction getOrCreateGroup(group: string) {\n\tconst existing = groups.get(group);\n\tif (existing) return existing;\n\tconst map = new Map();\n\tgroups.set(group, map);\n\treturn map;\n}\n\n/**\n * Retrieves the map of group names to maps of voice connections. By default, all voice connections\n * are created under the 'default' group.\n *\n * @returns The group map\n */\nexport function getGroups() {\n\treturn groups;\n}\n\n/**\n * Retrieves all the voice connections under the 'default' group.\n *\n * @param group - The group to look up\n * @returns The map of voice connections\n */\nexport function getVoiceConnections(group?: 'default'): Map;\n\n/**\n * Retrieves all the voice connections under the given group name.\n *\n * @param group - The group to look up\n * @returns The map of voice connections\n */\nexport function getVoiceConnections(group: string): Map | undefined;\n\n/**\n * Retrieves all the voice connections under the given group name. Defaults to the 'default' group.\n *\n * @param group - The group to look up\n * @returns The map of voice connections\n */\nexport function getVoiceConnections(group = 'default') {\n\treturn groups.get(group);\n}\n\n/**\n * Finds a voice connection with the given guild id and group. Defaults to the 'default' group.\n *\n * @param guildId - The guild id of the voice connection\n * @param group - the group that the voice connection was registered with\n * @returns The voice connection, if it exists\n */\nexport function getVoiceConnection(guildId: string, group = 'default') {\n\treturn getVoiceConnections(group)?.get(guildId);\n}\n\nexport function untrackVoiceConnection(voiceConnection: VoiceConnection) {\n\treturn getVoiceConnections(voiceConnection.joinConfig.group)?.delete(voiceConnection.joinConfig.guildId);\n}\n\nexport function trackVoiceConnection(voiceConnection: VoiceConnection) {\n\treturn getOrCreateGroup(voiceConnection.joinConfig.group).set(voiceConnection.joinConfig.guildId, voiceConnection);\n}\n\n// Audio Players\n\n// Each audio packet is 20ms long\nconst FRAME_LENGTH = 20;\n\nlet audioCycleInterval: NodeJS.Timeout | undefined;\nlet nextTime = -1;\n\n/**\n * A list of created audio players that are still active and haven't been destroyed.\n */\nconst audioPlayers: AudioPlayer[] = [];\n\n/**\n * Called roughly every 20 milliseconds. Dispatches audio from all players, and then gets the players to prepare\n * the next audio frame.\n */\nfunction audioCycleStep() {\n\tif (nextTime === -1) return;\n\n\tnextTime += FRAME_LENGTH;\n\tconst available = audioPlayers.filter((player) => player.checkPlayable());\n\n\tfor (const player of available) {\n\t\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\t\tplayer['_stepDispatch']();\n\t}\n\n\tprepareNextAudioFrame(available);\n}\n\n/**\n * Recursively gets the players that have been passed as parameters to prepare audio frames that can be played\n * at the start of the next cycle.\n */\nfunction prepareNextAudioFrame(players: AudioPlayer[]) {\n\tconst nextPlayer = players.shift();\n\n\tif (!nextPlayer) {\n\t\tif (nextTime !== -1) {\n\t\t\taudioCycleInterval = setTimeout(() => audioCycleStep(), nextTime - Date.now());\n\t\t}\n\n\t\treturn;\n\t}\n\n\t// eslint-disable-next-line @typescript-eslint/dot-notation\n\tnextPlayer['_stepPrepare']();\n\n\t// setImmediate to avoid long audio player chains blocking other scheduled tasks\n\tsetImmediate(() => prepareNextAudioFrame(players));\n}\n\n/**\n * Checks whether or not the given audio player is being driven by the data store clock.\n *\n * @param target - The target to test for\n * @returns `true` if it is being tracked, `false` otherwise\n */\nexport function hasAudioPlayer(target: AudioPlayer) {\n\treturn audioPlayers.includes(target);\n}\n\n/**\n * Adds an audio player to the data store tracking list, if it isn't already there.\n *\n * @param player - The player to track\n */\nexport function addAudioPlayer(player: AudioPlayer) {\n\tif (hasAudioPlayer(player)) return player;\n\taudioPlayers.push(player);\n\tif (audioPlayers.length === 1) {\n\t\tnextTime = Date.now();\n\t\tsetImmediate(() => audioCycleStep());\n\t}\n\n\treturn player;\n}\n\n/**\n * Removes an audio player from the data store tracking list, if it is present there.\n */\nexport function deleteAudioPlayer(player: AudioPlayer) {\n\tconst index = audioPlayers.indexOf(player);\n\tif (index === -1) return;\n\taudioPlayers.splice(index, 1);\n\tif (audioPlayers.length === 0) {\n\t\tnextTime = -1;\n\t\tif (audioCycleInterval !== undefined) clearTimeout(audioCycleInterval);\n\t}\n}\n","/* eslint-disable jsdoc/check-param-names */\n/* eslint-disable id-length */\n/* eslint-disable @typescript-eslint/unbound-method */\nimport { Buffer } from 'node:buffer';\nimport { EventEmitter } from 'node:events';\nimport { VoiceOpcodes } from 'discord-api-types/voice/v4';\nimport type { CloseEvent } from 'ws';\nimport * as secretbox from '../util/Secretbox';\nimport { noop } from '../util/util';\nimport { VoiceUDPSocket } from './VoiceUDPSocket';\nimport { VoiceWebSocket } from './VoiceWebSocket';\n\n// The number of audio channels required by Discord\nconst CHANNELS = 2;\nconst TIMESTAMP_INC = (48_000 / 100) * CHANNELS;\nconst MAX_NONCE_SIZE = 2 ** 32 - 1;\n\nexport const SUPPORTED_ENCRYPTION_MODES = ['xsalsa20_poly1305_lite', 'xsalsa20_poly1305_suffix', 'xsalsa20_poly1305'];\n\n/**\n * The different statuses that a networking instance can hold. The order\n * of the states between OpeningWs and Ready is chronological (first the\n * instance enters OpeningWs, then it enters Identifying etc.)\n */\nexport enum NetworkingStatusCode {\n\tOpeningWs,\n\tIdentifying,\n\tUdpHandshaking,\n\tSelectingProtocol,\n\tReady,\n\tResuming,\n\tClosed,\n}\n\n/**\n * The initial Networking state. Instances will be in this state when a WebSocket connection to a Discord\n * voice gateway is being opened.\n */\nexport interface NetworkingOpeningWsState {\n\tcode: NetworkingStatusCode.OpeningWs;\n\tconnectionOptions: ConnectionOptions;\n\tws: VoiceWebSocket;\n}\n\n/**\n * The state that a Networking instance will be in when it is attempting to authorize itself.\n */\nexport interface NetworkingIdentifyingState {\n\tcode: NetworkingStatusCode.Identifying;\n\tconnectionOptions: ConnectionOptions;\n\tws: VoiceWebSocket;\n}\n\n/**\n * The state that a Networking instance will be in when opening a UDP connection to the IP and port provided\n * by Discord, as well as performing IP discovery.\n */\nexport interface NetworkingUdpHandshakingState {\n\tcode: NetworkingStatusCode.UdpHandshaking;\n\tconnectionData: Pick;\n\tconnectionOptions: ConnectionOptions;\n\tudp: VoiceUDPSocket;\n\tws: VoiceWebSocket;\n}\n\n/**\n * The state that a Networking instance will be in when selecting an encryption protocol for audio packets.\n */\nexport interface NetworkingSelectingProtocolState {\n\tcode: NetworkingStatusCode.SelectingProtocol;\n\tconnectionData: Pick;\n\tconnectionOptions: ConnectionOptions;\n\tudp: VoiceUDPSocket;\n\tws: VoiceWebSocket;\n}\n\n/**\n * The state that a Networking instance will be in when it has a fully established connection to a Discord\n * voice server.\n */\nexport interface NetworkingReadyState {\n\tcode: NetworkingStatusCode.Ready;\n\tconnectionData: ConnectionData;\n\tconnectionOptions: ConnectionOptions;\n\tpreparedPacket?: Buffer | undefined;\n\tudp: VoiceUDPSocket;\n\tws: VoiceWebSocket;\n}\n\n/**\n * The state that a Networking instance will be in when its connection has been dropped unexpectedly, and it\n * is attempting to resume an existing session.\n */\nexport interface NetworkingResumingState {\n\tcode: NetworkingStatusCode.Resuming;\n\tconnectionData: ConnectionData;\n\tconnectionOptions: ConnectionOptions;\n\tpreparedPacket?: Buffer | undefined;\n\tudp: VoiceUDPSocket;\n\tws: VoiceWebSocket;\n}\n\n/**\n * The state that a Networking instance will be in when it has been destroyed. It cannot be recovered from this\n * state.\n */\nexport interface NetworkingClosedState {\n\tcode: NetworkingStatusCode.Closed;\n}\n\n/**\n * The various states that a networking instance can be in.\n */\nexport type NetworkingState =\n\t| NetworkingClosedState\n\t| NetworkingIdentifyingState\n\t| NetworkingOpeningWsState\n\t| NetworkingReadyState\n\t| NetworkingResumingState\n\t| NetworkingSelectingProtocolState\n\t| NetworkingUdpHandshakingState;\n\n/**\n * Details required to connect to the Discord voice gateway. These details\n * are first received on the main bot gateway, in the form of VOICE_SERVER_UPDATE\n * and VOICE_STATE_UPDATE packets.\n */\ninterface ConnectionOptions {\n\tendpoint: string;\n\tserverId: string;\n\tsessionId: string;\n\ttoken: string;\n\tuserId: string;\n}\n\n/**\n * Information about the current connection, e.g. which encryption mode is to be used on\n * the connection, timing information for playback of streams.\n */\nexport interface ConnectionData {\n\tencryptionMode: string;\n\tnonce: number;\n\tnonceBuffer: Buffer;\n\tpacketsPlayed: number;\n\tsecretKey: Uint8Array;\n\tsequence: number;\n\tspeaking: boolean;\n\tssrc: number;\n\ttimestamp: number;\n}\n\n/**\n * An empty buffer that is reused in packet encryption by many different networking instances.\n */\nconst nonce = Buffer.alloc(24);\n\nexport interface Networking extends EventEmitter {\n\t/**\n\t * Debug event for Networking.\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'debug', listener: (message: string) => void): this;\n\ton(event: 'error', listener: (error: Error) => void): this;\n\ton(event: 'stateChange', listener: (oldState: NetworkingState, newState: NetworkingState) => void): this;\n\ton(event: 'close', listener: (code: number) => void): this;\n}\n\n/**\n * Stringifies a NetworkingState.\n *\n * @param state - The state to stringify\n */\nfunction stringifyState(state: NetworkingState) {\n\treturn JSON.stringify({\n\t\t...state,\n\t\tws: Reflect.has(state, 'ws'),\n\t\tudp: Reflect.has(state, 'udp'),\n\t});\n}\n\n/**\n * Chooses an encryption mode from a list of given options. Chooses the most preferred option.\n *\n * @param options - The available encryption options\n */\nfunction chooseEncryptionMode(options: string[]): string {\n\tconst option = options.find((option) => SUPPORTED_ENCRYPTION_MODES.includes(option));\n\tif (!option) {\n\t\tthrow new Error(`No compatible encryption modes. Available include: ${options.join(', ')}`);\n\t}\n\n\treturn option;\n}\n\n/**\n * Returns a random number that is in the range of n bits.\n *\n * @param numberOfBits - The number of bits\n */\nfunction randomNBit(numberOfBits: number) {\n\treturn Math.floor(Math.random() * 2 ** numberOfBits);\n}\n\n/**\n * Manages the networking required to maintain a voice connection and dispatch audio packets\n */\nexport class Networking extends EventEmitter {\n\tprivate _state: NetworkingState;\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: ((message: string) => void) | null;\n\n\t/**\n\t * Creates a new Networking instance.\n\t */\n\tpublic constructor(options: ConnectionOptions, debug: boolean) {\n\t\tsuper();\n\n\t\tthis.onWsOpen = this.onWsOpen.bind(this);\n\t\tthis.onChildError = this.onChildError.bind(this);\n\t\tthis.onWsPacket = this.onWsPacket.bind(this);\n\t\tthis.onWsClose = this.onWsClose.bind(this);\n\t\tthis.onWsDebug = this.onWsDebug.bind(this);\n\t\tthis.onUdpDebug = this.onUdpDebug.bind(this);\n\t\tthis.onUdpClose = this.onUdpClose.bind(this);\n\n\t\tthis.debug = debug ? (message: string) => this.emit('debug', message) : null;\n\n\t\tthis._state = {\n\t\t\tcode: NetworkingStatusCode.OpeningWs,\n\t\t\tws: this.createWebSocket(options.endpoint),\n\t\t\tconnectionOptions: options,\n\t\t};\n\t}\n\n\t/**\n\t * Destroys the Networking instance, transitioning it into the Closed state.\n\t */\n\tpublic destroy() {\n\t\tthis.state = {\n\t\t\tcode: NetworkingStatusCode.Closed,\n\t\t};\n\t}\n\n\t/**\n\t * The current state of the networking instance.\n\t */\n\tpublic get state(): NetworkingState {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * Sets a new state for the networking instance, performing clean-up operations where necessary.\n\t */\n\tpublic set state(newState: NetworkingState) {\n\t\tconst oldWs = Reflect.get(this._state, 'ws') as VoiceWebSocket | undefined;\n\t\tconst newWs = Reflect.get(newState, 'ws') as VoiceWebSocket | undefined;\n\t\tif (oldWs && oldWs !== newWs) {\n\t\t\t// The old WebSocket is being freed - remove all handlers from it\n\t\t\toldWs.off('debug', this.onWsDebug);\n\t\t\toldWs.on('error', noop);\n\t\t\toldWs.off('error', this.onChildError);\n\t\t\toldWs.off('open', this.onWsOpen);\n\t\t\toldWs.off('packet', this.onWsPacket);\n\t\t\toldWs.off('close', this.onWsClose);\n\t\t\toldWs.destroy();\n\t\t}\n\n\t\tconst oldUdp = Reflect.get(this._state, 'udp') as VoiceUDPSocket | undefined;\n\t\tconst newUdp = Reflect.get(newState, 'udp') as VoiceUDPSocket | undefined;\n\n\t\tif (oldUdp && oldUdp !== newUdp) {\n\t\t\toldUdp.on('error', noop);\n\t\t\toldUdp.off('error', this.onChildError);\n\t\t\toldUdp.off('close', this.onUdpClose);\n\t\t\toldUdp.off('debug', this.onUdpDebug);\n\t\t\toldUdp.destroy();\n\t\t}\n\n\t\tconst oldState = this._state;\n\t\tthis._state = newState;\n\t\tthis.emit('stateChange', oldState, newState);\n\n\t\tthis.debug?.(`state change:\\nfrom ${stringifyState(oldState)}\\nto ${stringifyState(newState)}`);\n\t}\n\n\t/**\n\t * Creates a new WebSocket to a Discord Voice gateway.\n\t *\n\t * @param endpoint - The endpoint to connect to\n\t */\n\tprivate createWebSocket(endpoint: string) {\n\t\tconst ws = new VoiceWebSocket(`wss://${endpoint}?v=4`, Boolean(this.debug));\n\n\t\tws.on('error', this.onChildError);\n\t\tws.once('open', this.onWsOpen);\n\t\tws.on('packet', this.onWsPacket);\n\t\tws.once('close', this.onWsClose);\n\t\tws.on('debug', this.onWsDebug);\n\n\t\treturn ws;\n\t}\n\n\t/**\n\t * Propagates errors from the children VoiceWebSocket and VoiceUDPSocket.\n\t *\n\t * @param error - The error that was emitted by a child\n\t */\n\tprivate onChildError(error: Error) {\n\t\tthis.emit('error', error);\n\t}\n\n\t/**\n\t * Called when the WebSocket opens. Depending on the state that the instance is in,\n\t * it will either identify with a new session, or it will attempt to resume an existing session.\n\t */\n\tprivate onWsOpen() {\n\t\tif (this.state.code === NetworkingStatusCode.OpeningWs) {\n\t\t\tconst packet = {\n\t\t\t\top: VoiceOpcodes.Identify,\n\t\t\t\td: {\n\t\t\t\t\tserver_id: this.state.connectionOptions.serverId,\n\t\t\t\t\tuser_id: this.state.connectionOptions.userId,\n\t\t\t\t\tsession_id: this.state.connectionOptions.sessionId,\n\t\t\t\t\ttoken: this.state.connectionOptions.token,\n\t\t\t\t},\n\t\t\t};\n\t\t\tthis.state.ws.sendPacket(packet);\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Identifying,\n\t\t\t};\n\t\t} else if (this.state.code === NetworkingStatusCode.Resuming) {\n\t\t\tconst packet = {\n\t\t\t\top: VoiceOpcodes.Resume,\n\t\t\t\td: {\n\t\t\t\t\tserver_id: this.state.connectionOptions.serverId,\n\t\t\t\t\tsession_id: this.state.connectionOptions.sessionId,\n\t\t\t\t\ttoken: this.state.connectionOptions.token,\n\t\t\t\t},\n\t\t\t};\n\t\t\tthis.state.ws.sendPacket(packet);\n\t\t}\n\t}\n\n\t/**\n\t * Called when the WebSocket closes. Based on the reason for closing (given by the code parameter),\n\t * the instance will either attempt to resume, or enter the closed state and emit a 'close' event\n\t * with the close code, allowing the user to decide whether or not they would like to reconnect.\n\t *\n\t * @param code - The close code\n\t */\n\tprivate onWsClose({ code }: CloseEvent) {\n\t\tconst canResume = code === 4_015 || code < 4_000;\n\t\tif (canResume && this.state.code === NetworkingStatusCode.Ready) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Resuming,\n\t\t\t\tws: this.createWebSocket(this.state.connectionOptions.endpoint),\n\t\t\t};\n\t\t} else if (this.state.code !== NetworkingStatusCode.Closed) {\n\t\t\tthis.destroy();\n\t\t\tthis.emit('close', code);\n\t\t}\n\t}\n\n\t/**\n\t * Called when the UDP socket has closed itself if it has stopped receiving replies from Discord.\n\t */\n\tprivate onUdpClose() {\n\t\tif (this.state.code === NetworkingStatusCode.Ready) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Resuming,\n\t\t\t\tws: this.createWebSocket(this.state.connectionOptions.endpoint),\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Called when a packet is received on the connection's WebSocket.\n\t *\n\t * @param packet - The received packet\n\t */\n\tprivate onWsPacket(packet: any) {\n\t\tif (packet.op === VoiceOpcodes.Hello && this.state.code !== NetworkingStatusCode.Closed) {\n\t\t\tthis.state.ws.setHeartbeatInterval(packet.d.heartbeat_interval);\n\t\t} else if (packet.op === VoiceOpcodes.Ready && this.state.code === NetworkingStatusCode.Identifying) {\n\t\t\tconst { ip, port, ssrc, modes } = packet.d;\n\n\t\t\tconst udp = new VoiceUDPSocket({ ip, port });\n\t\t\tudp.on('error', this.onChildError);\n\t\t\tudp.on('debug', this.onUdpDebug);\n\t\t\tudp.once('close', this.onUdpClose);\n\t\t\tudp\n\t\t\t\t.performIPDiscovery(ssrc)\n\t\t\t\t// eslint-disable-next-line promise/prefer-await-to-then\n\t\t\t\t.then((localConfig) => {\n\t\t\t\t\tif (this.state.code !== NetworkingStatusCode.UdpHandshaking) return;\n\t\t\t\t\tthis.state.ws.sendPacket({\n\t\t\t\t\t\top: VoiceOpcodes.SelectProtocol,\n\t\t\t\t\t\td: {\n\t\t\t\t\t\t\tprotocol: 'udp',\n\t\t\t\t\t\t\tdata: {\n\t\t\t\t\t\t\t\taddress: localConfig.ip,\n\t\t\t\t\t\t\t\tport: localConfig.port,\n\t\t\t\t\t\t\t\tmode: chooseEncryptionMode(modes),\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t},\n\t\t\t\t\t});\n\t\t\t\t\tthis.state = {\n\t\t\t\t\t\t...this.state,\n\t\t\t\t\t\tcode: NetworkingStatusCode.SelectingProtocol,\n\t\t\t\t\t};\n\t\t\t\t})\n\t\t\t\t// eslint-disable-next-line promise/prefer-await-to-then, promise/prefer-await-to-callbacks\n\t\t\t\t.catch((error: Error) => this.emit('error', error));\n\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.UdpHandshaking,\n\t\t\t\tudp,\n\t\t\t\tconnectionData: {\n\t\t\t\t\tssrc,\n\t\t\t\t},\n\t\t\t};\n\t\t} else if (\n\t\t\tpacket.op === VoiceOpcodes.SessionDescription &&\n\t\t\tthis.state.code === NetworkingStatusCode.SelectingProtocol\n\t\t) {\n\t\t\tconst { mode: encryptionMode, secret_key: secretKey } = packet.d;\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Ready,\n\t\t\t\tconnectionData: {\n\t\t\t\t\t...this.state.connectionData,\n\t\t\t\t\tencryptionMode,\n\t\t\t\t\tsecretKey: new Uint8Array(secretKey),\n\t\t\t\t\tsequence: randomNBit(16),\n\t\t\t\t\ttimestamp: randomNBit(32),\n\t\t\t\t\tnonce: 0,\n\t\t\t\t\tnonceBuffer: Buffer.alloc(24),\n\t\t\t\t\tspeaking: false,\n\t\t\t\t\tpacketsPlayed: 0,\n\t\t\t\t},\n\t\t\t};\n\t\t} else if (packet.op === VoiceOpcodes.Resumed && this.state.code === NetworkingStatusCode.Resuming) {\n\t\t\tthis.state = {\n\t\t\t\t...this.state,\n\t\t\t\tcode: NetworkingStatusCode.Ready,\n\t\t\t};\n\t\t\tthis.state.connectionData.speaking = false;\n\t\t}\n\t}\n\n\t/**\n\t * Propagates debug messages from the child WebSocket.\n\t *\n\t * @param message - The emitted debug message\n\t */\n\tprivate onWsDebug(message: string) {\n\t\tthis.debug?.(`[WS] ${message}`);\n\t}\n\n\t/**\n\t * Propagates debug messages from the child UDPSocket.\n\t *\n\t * @param message - The emitted debug message\n\t */\n\tprivate onUdpDebug(message: string) {\n\t\tthis.debug?.(`[UDP] ${message}`);\n\t}\n\n\t/**\n\t * Prepares an Opus packet for playback. This includes attaching metadata to it and encrypting it.\n\t * It will be stored within the instance, and can be played by dispatchAudio()\n\t *\n\t * @remarks\n\t * Calling this method while there is already a prepared audio packet that has not yet been dispatched\n\t * will overwrite the existing audio packet. This should be avoided.\n\t * @param opusPacket - The Opus packet to encrypt\n\t * @returns The audio packet that was prepared\n\t */\n\tpublic prepareAudioPacket(opusPacket: Buffer) {\n\t\tconst state = this.state;\n\t\tif (state.code !== NetworkingStatusCode.Ready) return;\n\t\tstate.preparedPacket = this.createAudioPacket(opusPacket, state.connectionData);\n\t\treturn state.preparedPacket;\n\t}\n\n\t/**\n\t * Dispatches the audio packet previously prepared by prepareAudioPacket(opusPacket). The audio packet\n\t * is consumed and cannot be dispatched again.\n\t */\n\tpublic dispatchAudio() {\n\t\tconst state = this.state;\n\t\tif (state.code !== NetworkingStatusCode.Ready) return false;\n\t\tif (state.preparedPacket !== undefined) {\n\t\t\tthis.playAudioPacket(state.preparedPacket);\n\t\t\tstate.preparedPacket = undefined;\n\t\t\treturn true;\n\t\t}\n\n\t\treturn false;\n\t}\n\n\t/**\n\t * Plays an audio packet, updating timing metadata used for playback.\n\t *\n\t * @param audioPacket - The audio packet to play\n\t */\n\tprivate playAudioPacket(audioPacket: Buffer) {\n\t\tconst state = this.state;\n\t\tif (state.code !== NetworkingStatusCode.Ready) return;\n\t\tconst { connectionData } = state;\n\t\tconnectionData.packetsPlayed++;\n\t\tconnectionData.sequence++;\n\t\tconnectionData.timestamp += TIMESTAMP_INC;\n\t\tif (connectionData.sequence >= 2 ** 16) connectionData.sequence = 0;\n\t\tif (connectionData.timestamp >= 2 ** 32) connectionData.timestamp = 0;\n\t\tthis.setSpeaking(true);\n\t\tstate.udp.send(audioPacket);\n\t}\n\n\t/**\n\t * Sends a packet to the voice gateway indicating that the client has start/stopped sending\n\t * audio.\n\t *\n\t * @param speaking - Whether or not the client should be shown as speaking\n\t */\n\tpublic setSpeaking(speaking: boolean) {\n\t\tconst state = this.state;\n\t\tif (state.code !== NetworkingStatusCode.Ready) return;\n\t\tif (state.connectionData.speaking === speaking) return;\n\t\tstate.connectionData.speaking = speaking;\n\t\tstate.ws.sendPacket({\n\t\t\top: VoiceOpcodes.Speaking,\n\t\t\td: {\n\t\t\t\tspeaking: speaking ? 1 : 0,\n\t\t\t\tdelay: 0,\n\t\t\t\tssrc: state.connectionData.ssrc,\n\t\t\t},\n\t\t});\n\t}\n\n\t/**\n\t * Creates a new audio packet from an Opus packet. This involves encrypting the packet,\n\t * then prepending a header that includes metadata.\n\t *\n\t * @param opusPacket - The Opus packet to prepare\n\t * @param connectionData - The current connection data of the instance\n\t */\n\tprivate createAudioPacket(opusPacket: Buffer, connectionData: ConnectionData) {\n\t\tconst packetBuffer = Buffer.alloc(12);\n\t\tpacketBuffer[0] = 0x80;\n\t\tpacketBuffer[1] = 0x78;\n\n\t\tconst { sequence, timestamp, ssrc } = connectionData;\n\n\t\tpacketBuffer.writeUIntBE(sequence, 2, 2);\n\t\tpacketBuffer.writeUIntBE(timestamp, 4, 4);\n\t\tpacketBuffer.writeUIntBE(ssrc, 8, 4);\n\n\t\tpacketBuffer.copy(nonce, 0, 0, 12);\n\t\treturn Buffer.concat([packetBuffer, ...this.encryptOpusPacket(opusPacket, connectionData)]);\n\t}\n\n\t/**\n\t * Encrypts an Opus packet using the format agreed upon by the instance and Discord.\n\t *\n\t * @param opusPacket - The Opus packet to encrypt\n\t * @param connectionData - The current connection data of the instance\n\t */\n\tprivate encryptOpusPacket(opusPacket: Buffer, connectionData: ConnectionData) {\n\t\tconst { secretKey, encryptionMode } = connectionData;\n\n\t\tif (encryptionMode === 'xsalsa20_poly1305_lite') {\n\t\t\tconnectionData.nonce++;\n\t\t\tif (connectionData.nonce > MAX_NONCE_SIZE) connectionData.nonce = 0;\n\t\t\tconnectionData.nonceBuffer.writeUInt32BE(connectionData.nonce, 0);\n\t\t\treturn [\n\t\t\t\tsecretbox.methods.close(opusPacket, connectionData.nonceBuffer, secretKey),\n\t\t\t\tconnectionData.nonceBuffer.slice(0, 4),\n\t\t\t];\n\t\t} else if (encryptionMode === 'xsalsa20_poly1305_suffix') {\n\t\t\tconst random = secretbox.methods.random(24, connectionData.nonceBuffer);\n\t\t\treturn [secretbox.methods.close(opusPacket, random, secretKey), random];\n\t\t}\n\n\t\treturn [secretbox.methods.close(opusPacket, nonce, secretKey)];\n\t}\n}\n","import { Buffer } from 'node:buffer';\n\ninterface Methods {\n\tclose(opusPacket: Buffer, nonce: Buffer, secretKey: Uint8Array): Buffer;\n\topen(buffer: Buffer, nonce: Buffer, secretKey: Uint8Array): Buffer | null;\n\trandom(bytes: number, nonce: Buffer): Buffer;\n}\n\nconst libs = {\n\t'sodium-native': (sodium: any): Methods => ({\n\t\topen: (buffer: Buffer, nonce: Buffer, secretKey: Uint8Array) => {\n\t\t\tif (buffer) {\n\t\t\t\tconst output = Buffer.allocUnsafe(buffer.length - sodium.crypto_box_MACBYTES);\n\t\t\t\tif (sodium.crypto_secretbox_open_easy(output, buffer, nonce, secretKey)) return output;\n\t\t\t}\n\n\t\t\treturn null;\n\t\t},\n\t\tclose: (opusPacket: Buffer, nonce: Buffer, secretKey: Uint8Array) => {\n\t\t\t// eslint-disable-next-line @typescript-eslint/restrict-plus-operands\n\t\t\tconst output = Buffer.allocUnsafe(opusPacket.length + sodium.crypto_box_MACBYTES);\n\t\t\tsodium.crypto_secretbox_easy(output, opusPacket, nonce, secretKey);\n\t\t\treturn output;\n\t\t},\n\t\trandom: (num: number, buffer: Buffer = Buffer.allocUnsafe(num)) => {\n\t\t\tsodium.randombytes_buf(buffer);\n\t\t\treturn buffer;\n\t\t},\n\t}),\n\tsodium: (sodium: any): Methods => ({\n\t\topen: sodium.api.crypto_secretbox_open_easy,\n\t\tclose: sodium.api.crypto_secretbox_easy,\n\t\trandom: (num: number, buffer: Buffer = Buffer.allocUnsafe(num)) => {\n\t\t\tsodium.api.randombytes_buf(buffer);\n\t\t\treturn buffer;\n\t\t},\n\t}),\n\t'libsodium-wrappers': (sodium: any): Methods => ({\n\t\topen: sodium.crypto_secretbox_open_easy,\n\t\tclose: sodium.crypto_secretbox_easy,\n\t\trandom: sodium.randombytes_buf,\n\t}),\n\ttweetnacl: (tweetnacl: any): Methods => ({\n\t\topen: tweetnacl.secretbox.open,\n\t\tclose: tweetnacl.secretbox,\n\t\trandom: tweetnacl.randomBytes,\n\t}),\n} as const;\n\nconst fallbackError = () => {\n\tthrow new Error(\n\t\t`Cannot play audio as no valid encryption package is installed.\n- Install sodium, libsodium-wrappers, or tweetnacl.\n- Use the generateDependencyReport() function for more information.\\n`,\n\t);\n};\n\nconst methods: Methods = {\n\topen: fallbackError,\n\tclose: fallbackError,\n\trandom: fallbackError,\n};\n\nvoid (async () => {\n\tfor (const libName of Object.keys(libs) as (keyof typeof libs)[]) {\n\t\ttry {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires\n\t\t\tconst lib = require(libName);\n\t\t\tif (libName === 'libsodium-wrappers' && lib.ready) await lib.ready;\n\t\t\tObject.assign(methods, libs[libName](lib));\n\t\t\tbreak;\n\t\t} catch {}\n\t}\n})();\n\nexport { methods };\n","export const noop = () => {};\n","import { Buffer } from 'node:buffer';\nimport { createSocket, type Socket } from 'node:dgram';\nimport { EventEmitter } from 'node:events';\nimport { isIPv4 } from 'node:net';\n\n/**\n * Stores an IP address and port. Used to store socket details for the local client as well as\n * for Discord.\n */\nexport interface SocketConfig {\n\tip: string;\n\tport: number;\n}\n\n/**\n * Parses the response from Discord to aid with local IP discovery.\n *\n * @param message - The received message\n */\nexport function parseLocalPacket(message: Buffer): SocketConfig {\n\tconst packet = Buffer.from(message);\n\n\tconst ip = packet.slice(8, packet.indexOf(0, 8)).toString('utf8');\n\n\tif (!isIPv4(ip)) {\n\t\tthrow new Error('Malformed IP address');\n\t}\n\n\tconst port = packet.readUInt16BE(packet.length - 2);\n\n\treturn { ip, port };\n}\n\n/**\n * The interval in milliseconds at which keep alive datagrams are sent.\n */\nconst KEEP_ALIVE_INTERVAL = 5e3;\n\n/**\n * The maximum value of the keep alive counter.\n */\nconst MAX_COUNTER_VALUE = 2 ** 32 - 1;\n\nexport interface VoiceUDPSocket extends EventEmitter {\n\ton(event: 'error', listener: (error: Error) => void): this;\n\ton(event: 'close', listener: () => void): this;\n\ton(event: 'debug', listener: (message: string) => void): this;\n\ton(event: 'message', listener: (message: Buffer) => void): this;\n}\n\n/**\n * Manages the UDP networking for a voice connection.\n */\nexport class VoiceUDPSocket extends EventEmitter {\n\t/**\n\t * The underlying network Socket for the VoiceUDPSocket.\n\t */\n\tprivate readonly socket: Socket;\n\n\t/**\n\t * The socket details for Discord (remote)\n\t */\n\tprivate readonly remote: SocketConfig;\n\n\t/**\n\t * The counter used in the keep alive mechanism.\n\t */\n\tprivate keepAliveCounter = 0;\n\n\t/**\n\t * The buffer used to write the keep alive counter into.\n\t */\n\tprivate readonly keepAliveBuffer: Buffer;\n\n\t/**\n\t * The Node.js interval for the keep-alive mechanism.\n\t */\n\tprivate readonly keepAliveInterval: NodeJS.Timeout;\n\n\t/**\n\t * The time taken to receive a response to keep alive messages.\n\t *\n\t * @deprecated This field is no longer updated as keep alive messages are no longer tracked.\n\t */\n\tpublic ping?: number;\n\n\t/**\n\t * Creates a new VoiceUDPSocket.\n\t *\n\t * @param remote - Details of the remote socket\n\t */\n\tpublic constructor(remote: SocketConfig) {\n\t\tsuper();\n\t\tthis.socket = createSocket('udp4');\n\t\tthis.socket.on('error', (error: Error) => this.emit('error', error));\n\t\tthis.socket.on('message', (buffer: Buffer) => this.onMessage(buffer));\n\t\tthis.socket.on('close', () => this.emit('close'));\n\t\tthis.remote = remote;\n\t\tthis.keepAliveBuffer = Buffer.alloc(8);\n\t\tthis.keepAliveInterval = setInterval(() => this.keepAlive(), KEEP_ALIVE_INTERVAL);\n\t\tsetImmediate(() => this.keepAlive());\n\t}\n\n\t/**\n\t * Called when a message is received on the UDP socket.\n\t *\n\t * @param buffer - The received buffer\n\t */\n\tprivate onMessage(buffer: Buffer): void {\n\t\t// Propagate the message\n\t\tthis.emit('message', buffer);\n\t}\n\n\t/**\n\t * Called at a regular interval to check whether we are still able to send datagrams to Discord.\n\t */\n\tprivate keepAlive() {\n\t\tthis.keepAliveBuffer.writeUInt32LE(this.keepAliveCounter, 0);\n\t\tthis.send(this.keepAliveBuffer);\n\t\tthis.keepAliveCounter++;\n\t\tif (this.keepAliveCounter > MAX_COUNTER_VALUE) {\n\t\t\tthis.keepAliveCounter = 0;\n\t\t}\n\t}\n\n\t/**\n\t * Sends a buffer to Discord.\n\t *\n\t * @param buffer - The buffer to send\n\t */\n\tpublic send(buffer: Buffer) {\n\t\tthis.socket.send(buffer, this.remote.port, this.remote.ip);\n\t}\n\n\t/**\n\t * Closes the socket, the instance will not be able to be reused.\n\t */\n\tpublic destroy() {\n\t\ttry {\n\t\t\tthis.socket.close();\n\t\t} catch {}\n\n\t\tclearInterval(this.keepAliveInterval);\n\t}\n\n\t/**\n\t * Performs IP discovery to discover the local address and port to be used for the voice connection.\n\t *\n\t * @param ssrc - The SSRC received from Discord\n\t */\n\tpublic async performIPDiscovery(ssrc: number): Promise {\n\t\treturn new Promise((resolve, reject) => {\n\t\t\tconst listener = (message: Buffer) => {\n\t\t\t\ttry {\n\t\t\t\t\tif (message.readUInt16BE(0) !== 2) return;\n\t\t\t\t\tconst packet = parseLocalPacket(message);\n\t\t\t\t\tthis.socket.off('message', listener);\n\t\t\t\t\tresolve(packet);\n\t\t\t\t} catch {}\n\t\t\t};\n\n\t\t\tthis.socket.on('message', listener);\n\t\t\tthis.socket.once('close', () => reject(new Error('Cannot perform IP discovery - socket closed')));\n\n\t\t\tconst discoveryBuffer = Buffer.alloc(74);\n\n\t\t\tdiscoveryBuffer.writeUInt16BE(1, 0);\n\t\t\tdiscoveryBuffer.writeUInt16BE(70, 2);\n\t\t\tdiscoveryBuffer.writeUInt32BE(ssrc, 4);\n\t\t\tthis.send(discoveryBuffer);\n\t\t});\n\t}\n}\n","import { EventEmitter } from 'node:events';\nimport { VoiceOpcodes } from 'discord-api-types/voice/v4';\nimport WebSocket, { type MessageEvent } from 'ws';\n\nexport interface VoiceWebSocket extends EventEmitter {\n\ton(event: 'error', listener: (error: Error) => void): this;\n\ton(event: 'open', listener: (event: WebSocket.Event) => void): this;\n\ton(event: 'close', listener: (event: WebSocket.CloseEvent) => void): this;\n\t/**\n\t * Debug event for VoiceWebSocket.\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'debug', listener: (message: string) => void): this;\n\t/**\n\t * Packet event.\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'packet', listener: (packet: any) => void): this;\n}\n\n/**\n * An extension of the WebSocket class to provide helper functionality when interacting\n * with the Discord Voice gateway.\n */\nexport class VoiceWebSocket extends EventEmitter {\n\t/**\n\t * The current heartbeat interval, if any.\n\t */\n\tprivate heartbeatInterval?: NodeJS.Timeout;\n\n\t/**\n\t * The time (milliseconds since UNIX epoch) that the last heartbeat acknowledgement packet was received.\n\t * This is set to 0 if an acknowledgement packet hasn't been received yet.\n\t */\n\tprivate lastHeartbeatAck: number;\n\n\t/**\n\t * The time (milliseconds since UNIX epoch) that the last heartbeat was sent. This is set to 0 if a heartbeat\n\t * hasn't been sent yet.\n\t */\n\tprivate lastHeartbeatSend: number;\n\n\t/**\n\t * The number of consecutively missed heartbeats.\n\t */\n\tprivate missedHeartbeats = 0;\n\n\t/**\n\t * The last recorded ping.\n\t */\n\tpublic ping?: number;\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: ((message: string) => void) | null;\n\n\t/**\n\t * The underlying WebSocket of this wrapper.\n\t */\n\tprivate readonly ws: WebSocket;\n\n\t/**\n\t * Creates a new VoiceWebSocket.\n\t *\n\t * @param address - The address to connect to\n\t */\n\tpublic constructor(address: string, debug: boolean) {\n\t\tsuper();\n\t\tthis.ws = new WebSocket(address);\n\t\tthis.ws.onmessage = (err) => this.onMessage(err);\n\t\tthis.ws.onopen = (err) => this.emit('open', err);\n\t\tthis.ws.onerror = (err: Error | WebSocket.ErrorEvent) => this.emit('error', err instanceof Error ? err : err.error);\n\t\tthis.ws.onclose = (err) => this.emit('close', err);\n\n\t\tthis.lastHeartbeatAck = 0;\n\t\tthis.lastHeartbeatSend = 0;\n\n\t\tthis.debug = debug ? (message: string) => this.emit('debug', message) : null;\n\t}\n\n\t/**\n\t * Destroys the VoiceWebSocket. The heartbeat interval is cleared, and the connection is closed.\n\t */\n\tpublic destroy() {\n\t\ttry {\n\t\t\tthis.debug?.('destroyed');\n\t\t\tthis.setHeartbeatInterval(-1);\n\t\t\tthis.ws.close(1_000);\n\t\t} catch (error) {\n\t\t\tconst err = error as Error;\n\t\t\tthis.emit('error', err);\n\t\t}\n\t}\n\n\t/**\n\t * Handles message events on the WebSocket. Attempts to JSON parse the messages and emit them\n\t * as packets.\n\t *\n\t * @param event - The message event\n\t */\n\tpublic onMessage(event: MessageEvent) {\n\t\tif (typeof event.data !== 'string') return;\n\n\t\tthis.debug?.(`<< ${event.data}`);\n\n\t\tlet packet: any;\n\t\ttry {\n\t\t\tpacket = JSON.parse(event.data);\n\t\t} catch (error) {\n\t\t\tconst err = error as Error;\n\t\t\tthis.emit('error', err);\n\t\t\treturn;\n\t\t}\n\n\t\tif (packet.op === VoiceOpcodes.HeartbeatAck) {\n\t\t\tthis.lastHeartbeatAck = Date.now();\n\t\t\tthis.missedHeartbeats = 0;\n\t\t\tthis.ping = this.lastHeartbeatAck - this.lastHeartbeatSend;\n\t\t}\n\n\t\tthis.emit('packet', packet);\n\t}\n\n\t/**\n\t * Sends a JSON-stringifiable packet over the WebSocket.\n\t *\n\t * @param packet - The packet to send\n\t */\n\tpublic sendPacket(packet: any) {\n\t\ttry {\n\t\t\tconst stringified = JSON.stringify(packet);\n\t\t\tthis.debug?.(`>> ${stringified}`);\n\t\t\tthis.ws.send(stringified);\n\t\t\treturn;\n\t\t} catch (error) {\n\t\t\tconst err = error as Error;\n\t\t\tthis.emit('error', err);\n\t\t}\n\t}\n\n\t/**\n\t * Sends a heartbeat over the WebSocket.\n\t */\n\tprivate sendHeartbeat() {\n\t\tthis.lastHeartbeatSend = Date.now();\n\t\tthis.missedHeartbeats++;\n\t\tconst nonce = this.lastHeartbeatSend;\n\t\tthis.sendPacket({\n\t\t\top: VoiceOpcodes.Heartbeat,\n\t\t\t// eslint-disable-next-line id-length\n\t\t\td: nonce,\n\t\t});\n\t}\n\n\t/**\n\t * Sets/clears an interval to send heartbeats over the WebSocket.\n\t *\n\t * @param ms - The interval in milliseconds. If negative, the interval will be unset\n\t */\n\tpublic setHeartbeatInterval(ms: number) {\n\t\tif (this.heartbeatInterval !== undefined) clearInterval(this.heartbeatInterval);\n\t\tif (ms > 0) {\n\t\t\tthis.heartbeatInterval = setInterval(() => {\n\t\t\t\tif (this.lastHeartbeatSend !== 0 && this.missedHeartbeats >= 3) {\n\t\t\t\t\t// Missed too many heartbeats - disconnect\n\t\t\t\t\tthis.ws.close();\n\t\t\t\t\tthis.setHeartbeatInterval(-1);\n\t\t\t\t}\n\n\t\t\t\tthis.sendHeartbeat();\n\t\t\t}, ms);\n\t\t}\n\t}\n}\n","/* eslint-disable jsdoc/check-param-names */\nimport { Buffer } from 'node:buffer';\nimport { VoiceOpcodes } from 'discord-api-types/voice/v4';\nimport type { VoiceConnection } from '../VoiceConnection';\nimport type { ConnectionData } from '../networking/Networking';\nimport { methods } from '../util/Secretbox';\nimport {\n\tAudioReceiveStream,\n\tcreateDefaultAudioReceiveStreamOptions,\n\ttype AudioReceiveStreamOptions,\n} from './AudioReceiveStream';\nimport { SSRCMap } from './SSRCMap';\nimport { SpeakingMap } from './SpeakingMap';\n\n/**\n * Attaches to a VoiceConnection, allowing you to receive audio packets from other\n * users that are speaking.\n *\n * @beta\n */\nexport class VoiceReceiver {\n\t/**\n\t * The attached connection of this receiver.\n\t */\n\tpublic readonly voiceConnection;\n\n\t/**\n\t * Maps SSRCs to Discord user ids.\n\t */\n\tpublic readonly ssrcMap: SSRCMap;\n\n\t/**\n\t * The current audio subscriptions of this receiver.\n\t */\n\tpublic readonly subscriptions: Map;\n\n\t/**\n\t * The connection data of the receiver.\n\t *\n\t * @internal\n\t */\n\tpublic connectionData: Partial;\n\n\t/**\n\t * The speaking map of the receiver.\n\t */\n\tpublic readonly speaking: SpeakingMap;\n\n\tpublic constructor(voiceConnection: VoiceConnection) {\n\t\tthis.voiceConnection = voiceConnection;\n\t\tthis.ssrcMap = new SSRCMap();\n\t\tthis.speaking = new SpeakingMap();\n\t\tthis.subscriptions = new Map();\n\t\tthis.connectionData = {};\n\n\t\tthis.onWsPacket = this.onWsPacket.bind(this);\n\t\tthis.onUdpMessage = this.onUdpMessage.bind(this);\n\t}\n\n\t/**\n\t * Called when a packet is received on the attached connection's WebSocket.\n\t *\n\t * @param packet - The received packet\n\t * @internal\n\t */\n\tpublic onWsPacket(packet: any) {\n\t\tif (packet.op === VoiceOpcodes.ClientDisconnect && typeof packet.d?.user_id === 'string') {\n\t\t\tthis.ssrcMap.delete(packet.d.user_id);\n\t\t} else if (\n\t\t\tpacket.op === VoiceOpcodes.Speaking &&\n\t\t\ttypeof packet.d?.user_id === 'string' &&\n\t\t\ttypeof packet.d?.ssrc === 'number'\n\t\t) {\n\t\t\tthis.ssrcMap.update({ userId: packet.d.user_id, audioSSRC: packet.d.ssrc });\n\t\t} else if (\n\t\t\tpacket.op === VoiceOpcodes.ClientConnect &&\n\t\t\ttypeof packet.d?.user_id === 'string' &&\n\t\t\ttypeof packet.d?.audio_ssrc === 'number'\n\t\t) {\n\t\t\tthis.ssrcMap.update({\n\t\t\t\tuserId: packet.d.user_id,\n\t\t\t\taudioSSRC: packet.d.audio_ssrc,\n\t\t\t\tvideoSSRC: packet.d.video_ssrc === 0 ? undefined : packet.d.video_ssrc,\n\t\t\t});\n\t\t}\n\t}\n\n\tprivate decrypt(buffer: Buffer, mode: string, nonce: Buffer, secretKey: Uint8Array) {\n\t\t// Choose correct nonce depending on encryption\n\t\tlet end;\n\t\tif (mode === 'xsalsa20_poly1305_lite') {\n\t\t\tbuffer.copy(nonce, 0, buffer.length - 4);\n\t\t\tend = buffer.length - 4;\n\t\t} else if (mode === 'xsalsa20_poly1305_suffix') {\n\t\t\tbuffer.copy(nonce, 0, buffer.length - 24);\n\t\t\tend = buffer.length - 24;\n\t\t} else {\n\t\t\tbuffer.copy(nonce, 0, 0, 12);\n\t\t}\n\n\t\t// Open packet\n\t\tconst decrypted = methods.open(buffer.slice(12, end), nonce, secretKey);\n\t\tif (!decrypted) return;\n\t\treturn Buffer.from(decrypted);\n\t}\n\n\t/**\n\t * Parses an audio packet, decrypting it to yield an Opus packet.\n\t *\n\t * @param buffer - The buffer to parse\n\t * @param mode - The encryption mode\n\t * @param nonce - The nonce buffer used by the connection for encryption\n\t * @param secretKey - The secret key used by the connection for encryption\n\t * @returns The parsed Opus packet\n\t */\n\tprivate parsePacket(buffer: Buffer, mode: string, nonce: Buffer, secretKey: Uint8Array) {\n\t\tlet packet = this.decrypt(buffer, mode, nonce, secretKey);\n\t\tif (!packet) return;\n\n\t\t// Strip RTP Header Extensions (one-byte only)\n\t\tif (packet[0] === 0xbe && packet[1] === 0xde) {\n\t\t\tconst headerExtensionLength = packet.readUInt16BE(2);\n\t\t\tpacket = packet.subarray(4 + 4 * headerExtensionLength);\n\t\t}\n\n\t\treturn packet;\n\t}\n\n\t/**\n\t * Called when the UDP socket of the attached connection receives a message.\n\t *\n\t * @param msg - The received message\n\t * @internal\n\t */\n\tpublic onUdpMessage(msg: Buffer) {\n\t\tif (msg.length <= 8) return;\n\t\tconst ssrc = msg.readUInt32BE(8);\n\n\t\tconst userData = this.ssrcMap.get(ssrc);\n\t\tif (!userData) return;\n\n\t\tthis.speaking.onPacket(userData.userId);\n\n\t\tconst stream = this.subscriptions.get(userData.userId);\n\t\tif (!stream) return;\n\n\t\tif (this.connectionData.encryptionMode && this.connectionData.nonceBuffer && this.connectionData.secretKey) {\n\t\t\tconst packet = this.parsePacket(\n\t\t\t\tmsg,\n\t\t\t\tthis.connectionData.encryptionMode,\n\t\t\t\tthis.connectionData.nonceBuffer,\n\t\t\t\tthis.connectionData.secretKey,\n\t\t\t);\n\t\t\tif (packet) {\n\t\t\t\tstream.push(packet);\n\t\t\t} else {\n\t\t\t\tstream.destroy(new Error('Failed to parse packet'));\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Creates a subscription for the given user id.\n\t *\n\t * @param target - The id of the user to subscribe to\n\t * @returns A readable stream of Opus packets received from the target\n\t */\n\tpublic subscribe(userId: string, options?: Partial) {\n\t\tconst existing = this.subscriptions.get(userId);\n\t\tif (existing) return existing;\n\n\t\tconst stream = new AudioReceiveStream({\n\t\t\t...createDefaultAudioReceiveStreamOptions(),\n\t\t\t...options,\n\t\t});\n\n\t\tstream.once('close', () => this.subscriptions.delete(userId));\n\t\tthis.subscriptions.set(userId, stream);\n\t\treturn stream;\n\t}\n}\n","import type { Buffer } from 'node:buffer';\nimport { Readable, type ReadableOptions } from 'node:stream';\nimport { SILENCE_FRAME } from '../audio/AudioPlayer';\n\n/**\n * The different behaviors an audio receive stream can have for deciding when to end.\n */\nexport enum EndBehaviorType {\n\t/**\n\t * The stream will only end when manually destroyed.\n\t */\n\tManual,\n\n\t/**\n\t * The stream will end after a given time period of silence/no audio packets.\n\t */\n\tAfterSilence,\n\n\t/**\n\t * The stream will end after a given time period of no audio packets.\n\t */\n\tAfterInactivity,\n}\n\nexport type EndBehavior =\n\t| {\n\t\t\tbehavior: EndBehaviorType.AfterInactivity | EndBehaviorType.AfterSilence;\n\t\t\tduration: number;\n\t }\n\t| {\n\t\t\tbehavior: EndBehaviorType.Manual;\n\t };\n\nexport interface AudioReceiveStreamOptions extends ReadableOptions {\n\tend: EndBehavior;\n}\n\nexport function createDefaultAudioReceiveStreamOptions(): AudioReceiveStreamOptions {\n\treturn {\n\t\tend: {\n\t\t\tbehavior: EndBehaviorType.Manual,\n\t\t},\n\t};\n}\n\n/**\n * A readable stream of Opus packets received from a specific entity\n * in a Discord voice connection.\n */\nexport class AudioReceiveStream extends Readable {\n\t/**\n\t * The end behavior of the receive stream.\n\t */\n\tpublic readonly end: EndBehavior;\n\n\tprivate endTimeout?: NodeJS.Timeout;\n\n\tpublic constructor({ end, ...options }: AudioReceiveStreamOptions) {\n\t\tsuper({\n\t\t\t...options,\n\t\t\tobjectMode: true,\n\t\t});\n\n\t\tthis.end = end;\n\t}\n\n\tpublic override push(buffer: Buffer | null) {\n\t\tif (\n\t\t\tbuffer &&\n\t\t\t(this.end.behavior === EndBehaviorType.AfterInactivity ||\n\t\t\t\t(this.end.behavior === EndBehaviorType.AfterSilence &&\n\t\t\t\t\t(buffer.compare(SILENCE_FRAME) !== 0 || this.endTimeout === undefined)))\n\t\t) {\n\t\t\tthis.renewEndTimeout(this.end);\n\t\t}\n\n\t\treturn super.push(buffer);\n\t}\n\n\tprivate renewEndTimeout(end: EndBehavior & { duration: number }) {\n\t\tif (this.endTimeout) {\n\t\t\tclearTimeout(this.endTimeout);\n\t\t}\n\n\t\tthis.endTimeout = setTimeout(() => this.push(null), end.duration);\n\t}\n\n\tpublic override _read() {}\n}\n","/* eslint-disable @typescript-eslint/prefer-ts-expect-error, @typescript-eslint/method-signature-style */\nimport { Buffer } from 'node:buffer';\nimport { EventEmitter } from 'node:events';\nimport { addAudioPlayer, deleteAudioPlayer } from '../DataStore';\nimport { VoiceConnectionStatus, type VoiceConnection } from '../VoiceConnection';\nimport { noop } from '../util/util';\nimport { AudioPlayerError } from './AudioPlayerError';\nimport type { AudioResource } from './AudioResource';\nimport { PlayerSubscription } from './PlayerSubscription';\n\n// The Opus \"silent\" frame\nexport const SILENCE_FRAME = Buffer.from([0xf8, 0xff, 0xfe]);\n\n/**\n * Describes the behavior of the player when an audio packet is played but there are no available\n * voice connections to play to.\n */\nexport enum NoSubscriberBehavior {\n\t/**\n\t * Pauses playing the stream until a voice connection becomes available.\n\t */\n\tPause = 'pause',\n\n\t/**\n\t * Continues to play through the resource regardless.\n\t */\n\tPlay = 'play',\n\n\t/**\n\t * The player stops and enters the Idle state.\n\t */\n\tStop = 'stop',\n}\n\nexport enum AudioPlayerStatus {\n\t/**\n\t * When the player has paused itself. Only possible with the \"pause\" no subscriber behavior.\n\t */\n\tAutoPaused = 'autopaused',\n\n\t/**\n\t * When the player is waiting for an audio resource to become readable before transitioning to Playing.\n\t */\n\tBuffering = 'buffering',\n\n\t/**\n\t * When there is currently no resource for the player to be playing.\n\t */\n\tIdle = 'idle',\n\n\t/**\n\t * When the player has been manually paused.\n\t */\n\tPaused = 'paused',\n\n\t/**\n\t * When the player is actively playing an audio resource.\n\t */\n\tPlaying = 'playing',\n}\n\n/**\n * Options that can be passed when creating an audio player, used to specify its behavior.\n */\nexport interface CreateAudioPlayerOptions {\n\tbehaviors?: {\n\t\tmaxMissedFrames?: number;\n\t\tnoSubscriber?: NoSubscriberBehavior;\n\t};\n\tdebug?: boolean;\n}\n\n/**\n * The state that an AudioPlayer is in when it has no resource to play. This is the starting state.\n */\nexport interface AudioPlayerIdleState {\n\tstatus: AudioPlayerStatus.Idle;\n}\n\n/**\n * The state that an AudioPlayer is in when it is waiting for a resource to become readable. Once this\n * happens, the AudioPlayer will enter the Playing state. If the resource ends/errors before this, then\n * it will re-enter the Idle state.\n */\nexport interface AudioPlayerBufferingState {\n\tonFailureCallback: () => void;\n\tonReadableCallback: () => void;\n\tonStreamError: (error: Error) => void;\n\t/**\n\t * The resource that the AudioPlayer is waiting for\n\t */\n\tresource: AudioResource;\n\tstatus: AudioPlayerStatus.Buffering;\n}\n\n/**\n * The state that an AudioPlayer is in when it is actively playing an AudioResource. When playback ends,\n * it will enter the Idle state.\n */\nexport interface AudioPlayerPlayingState {\n\t/**\n\t * The number of consecutive times that the audio resource has been unable to provide an Opus frame.\n\t */\n\tmissedFrames: number;\n\tonStreamError: (error: Error) => void;\n\n\t/**\n\t * The playback duration in milliseconds of the current audio resource. This includes filler silence packets\n\t * that have been played when the resource was buffering.\n\t */\n\tplaybackDuration: number;\n\n\t/**\n\t * The resource that is being played.\n\t */\n\tresource: AudioResource;\n\n\tstatus: AudioPlayerStatus.Playing;\n}\n\n/**\n * The state that an AudioPlayer is in when it has either been explicitly paused by the user, or done\n * automatically by the AudioPlayer itself if there are no available subscribers.\n */\nexport interface AudioPlayerPausedState {\n\tonStreamError: (error: Error) => void;\n\t/**\n\t * The playback duration in milliseconds of the current audio resource. This includes filler silence packets\n\t * that have been played when the resource was buffering.\n\t */\n\tplaybackDuration: number;\n\n\t/**\n\t * The current resource of the audio player.\n\t */\n\tresource: AudioResource;\n\n\t/**\n\t * How many silence packets still need to be played to avoid audio interpolation due to the stream suddenly pausing.\n\t */\n\tsilencePacketsRemaining: number;\n\n\tstatus: AudioPlayerStatus.AutoPaused | AudioPlayerStatus.Paused;\n}\n\n/**\n * The various states that the player can be in.\n */\nexport type AudioPlayerState =\n\t| AudioPlayerBufferingState\n\t| AudioPlayerIdleState\n\t| AudioPlayerPausedState\n\t| AudioPlayerPlayingState;\n\nexport interface AudioPlayer extends EventEmitter {\n\t/**\n\t * Emitted when there is an error emitted from the audio resource played by the audio player\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'error', listener: (error: AudioPlayerError) => void): this;\n\t/**\n\t * Emitted debugging information about the audio player\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'debug', listener: (message: string) => void): this;\n\t/**\n\t * Emitted when the state of the audio player changes\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'stateChange', listener: (oldState: AudioPlayerState, newState: AudioPlayerState) => void): this;\n\t/**\n\t * Emitted when the audio player is subscribed to a voice connection\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'subscribe' | 'unsubscribe', listener: (subscription: PlayerSubscription) => void): this;\n\t/**\n\t * Emitted when the status of state changes to a specific status\n\t *\n\t * @eventProperty\n\t */\n\ton(\n\t\tevent: T,\n\t\tlistener: (oldState: AudioPlayerState, newState: AudioPlayerState & { status: T }) => void,\n\t): this;\n}\n\n/**\n * Stringifies an AudioPlayerState instance.\n *\n * @param state - The state to stringify\n */\nfunction stringifyState(state: AudioPlayerState) {\n\treturn JSON.stringify({\n\t\t...state,\n\t\tresource: Reflect.has(state, 'resource'),\n\t\tstepTimeout: Reflect.has(state, 'stepTimeout'),\n\t});\n}\n\n/**\n * Used to play audio resources (i.e. tracks, streams) to voice connections.\n *\n * @remarks\n * Audio players are designed to be re-used - even if a resource has finished playing, the player itself\n * can still be used.\n *\n * The AudioPlayer drives the timing of playback, and therefore is unaffected by voice connections\n * becoming unavailable. Its behavior in these scenarios can be configured.\n */\nexport class AudioPlayer extends EventEmitter {\n\t/**\n\t * The state that the AudioPlayer is in.\n\t */\n\tprivate _state: AudioPlayerState;\n\n\t/**\n\t * A list of VoiceConnections that are registered to this AudioPlayer. The player will attempt to play audio\n\t * to the streams in this list.\n\t */\n\tprivate readonly subscribers: PlayerSubscription[] = [];\n\n\t/**\n\t * The behavior that the player should follow when it enters certain situations.\n\t */\n\tprivate readonly behaviors: {\n\t\tmaxMissedFrames: number;\n\t\tnoSubscriber: NoSubscriberBehavior;\n\t};\n\n\t/**\n\t * The debug logger function, if debugging is enabled.\n\t */\n\tprivate readonly debug: ((message: string) => void) | null;\n\n\t/**\n\t * Creates a new AudioPlayer.\n\t */\n\tpublic constructor(options: CreateAudioPlayerOptions = {}) {\n\t\tsuper();\n\t\tthis._state = { status: AudioPlayerStatus.Idle };\n\t\tthis.behaviors = {\n\t\t\tnoSubscriber: NoSubscriberBehavior.Pause,\n\t\t\tmaxMissedFrames: 5,\n\t\t\t...options.behaviors,\n\t\t};\n\t\tthis.debug = options.debug === false ? null : (message: string) => this.emit('debug', message);\n\t}\n\n\t/**\n\t * A list of subscribed voice connections that can currently receive audio to play.\n\t */\n\tpublic get playable() {\n\t\treturn this.subscribers\n\t\t\t.filter(({ connection }) => connection.state.status === VoiceConnectionStatus.Ready)\n\t\t\t.map(({ connection }) => connection);\n\t}\n\n\t/**\n\t * Subscribes a VoiceConnection to the audio player's play list. If the VoiceConnection is already subscribed,\n\t * then the existing subscription is used.\n\t *\n\t * @remarks\n\t * This method should not be directly called. Instead, use VoiceConnection#subscribe.\n\t * @param connection - The connection to subscribe\n\t * @returns The new subscription if the voice connection is not yet subscribed, otherwise the existing subscription\n\t */\n\t// @ts-ignore\n\tprivate subscribe(connection: VoiceConnection) {\n\t\tconst existingSubscription = this.subscribers.find((subscription) => subscription.connection === connection);\n\t\tif (!existingSubscription) {\n\t\t\tconst subscription = new PlayerSubscription(connection, this);\n\t\t\tthis.subscribers.push(subscription);\n\t\t\tsetImmediate(() => this.emit('subscribe', subscription));\n\t\t\treturn subscription;\n\t\t}\n\n\t\treturn existingSubscription;\n\t}\n\n\t/**\n\t * Unsubscribes a subscription - i.e. removes a voice connection from the play list of the audio player.\n\t *\n\t * @remarks\n\t * This method should not be directly called. Instead, use PlayerSubscription#unsubscribe.\n\t * @param subscription - The subscription to remove\n\t * @returns Whether or not the subscription existed on the player and was removed\n\t */\n\t// @ts-ignore\n\tprivate unsubscribe(subscription: PlayerSubscription) {\n\t\tconst index = this.subscribers.indexOf(subscription);\n\t\tconst exists = index !== -1;\n\t\tif (exists) {\n\t\t\tthis.subscribers.splice(index, 1);\n\t\t\tsubscription.connection.setSpeaking(false);\n\t\t\tthis.emit('unsubscribe', subscription);\n\t\t}\n\n\t\treturn exists;\n\t}\n\n\t/**\n\t * The state that the player is in.\n\t */\n\tpublic get state() {\n\t\treturn this._state;\n\t}\n\n\t/**\n\t * Sets a new state for the player, performing clean-up operations where necessary.\n\t */\n\tpublic set state(newState: AudioPlayerState) {\n\t\tconst oldState = this._state;\n\t\tconst newResource = Reflect.get(newState, 'resource') as AudioResource | undefined;\n\n\t\tif (oldState.status !== AudioPlayerStatus.Idle && oldState.resource !== newResource) {\n\t\t\toldState.resource.playStream.on('error', noop);\n\t\t\toldState.resource.playStream.off('error', oldState.onStreamError);\n\t\t\toldState.resource.audioPlayer = undefined;\n\t\t\toldState.resource.playStream.destroy();\n\t\t\toldState.resource.playStream.read(); // required to ensure buffered data is drained, prevents memory leak\n\t\t}\n\n\t\t// When leaving the Buffering state (or buffering a new resource), then remove the event listeners from it\n\t\tif (\n\t\t\toldState.status === AudioPlayerStatus.Buffering &&\n\t\t\t(newState.status !== AudioPlayerStatus.Buffering || newState.resource !== oldState.resource)\n\t\t) {\n\t\t\toldState.resource.playStream.off('end', oldState.onFailureCallback);\n\t\t\toldState.resource.playStream.off('close', oldState.onFailureCallback);\n\t\t\toldState.resource.playStream.off('finish', oldState.onFailureCallback);\n\t\t\toldState.resource.playStream.off('readable', oldState.onReadableCallback);\n\t\t}\n\n\t\t// transitioning into an idle should ensure that connections stop speaking\n\t\tif (newState.status === AudioPlayerStatus.Idle) {\n\t\t\tthis._signalStopSpeaking();\n\t\t\tdeleteAudioPlayer(this);\n\t\t}\n\n\t\t// attach to the global audio player timer\n\t\tif (newResource) {\n\t\t\taddAudioPlayer(this);\n\t\t}\n\n\t\t// playing -> playing state changes should still transition if a resource changed (seems like it would be useful!)\n\t\tconst didChangeResources =\n\t\t\toldState.status !== AudioPlayerStatus.Idle &&\n\t\t\tnewState.status === AudioPlayerStatus.Playing &&\n\t\t\toldState.resource !== newState.resource;\n\n\t\tthis._state = newState;\n\n\t\tthis.emit('stateChange', oldState, this._state);\n\t\tif (oldState.status !== newState.status || didChangeResources) {\n\t\t\tthis.emit(newState.status, oldState, this._state as any);\n\t\t}\n\n\t\tthis.debug?.(`state change:\\nfrom ${stringifyState(oldState)}\\nto ${stringifyState(newState)}`);\n\t}\n\n\t/**\n\t * Plays a new resource on the player. If the player is already playing a resource, the existing resource is destroyed\n\t * (it cannot be reused, even in another player) and is replaced with the new resource.\n\t *\n\t * @remarks\n\t * The player will transition to the Playing state once playback begins, and will return to the Idle state once\n\t * playback is ended.\n\t *\n\t * If the player was previously playing a resource and this method is called, the player will not transition to the\n\t * Idle state during the swap over.\n\t * @param resource - The resource to play\n\t * @throws Will throw if attempting to play an audio resource that has already ended, or is being played by another player\n\t */\n\tpublic play(resource: AudioResource) {\n\t\tif (resource.ended) {\n\t\t\tthrow new Error('Cannot play a resource that has already ended.');\n\t\t}\n\n\t\tif (resource.audioPlayer) {\n\t\t\tif (resource.audioPlayer === this) {\n\t\t\t\treturn;\n\t\t\t}\n\n\t\t\tthrow new Error('Resource is already being played by another audio player.');\n\t\t}\n\n\t\tresource.audioPlayer = this;\n\n\t\t// Attach error listeners to the stream that will propagate the error and then return to the Idle\n\t\t// state if the resource is still being used.\n\t\tconst onStreamError = (error: Error) => {\n\t\t\tif (this.state.status !== AudioPlayerStatus.Idle) {\n\t\t\t\tthis.emit('error', new AudioPlayerError(error, this.state.resource));\n\t\t\t}\n\n\t\t\tif (this.state.status !== AudioPlayerStatus.Idle && this.state.resource === resource) {\n\t\t\t\tthis.state = {\n\t\t\t\t\tstatus: AudioPlayerStatus.Idle,\n\t\t\t\t};\n\t\t\t}\n\t\t};\n\n\t\tresource.playStream.once('error', onStreamError);\n\n\t\tif (resource.started) {\n\t\t\tthis.state = {\n\t\t\t\tstatus: AudioPlayerStatus.Playing,\n\t\t\t\tmissedFrames: 0,\n\t\t\t\tplaybackDuration: 0,\n\t\t\t\tresource,\n\t\t\t\tonStreamError,\n\t\t\t};\n\t\t} else {\n\t\t\tconst onReadableCallback = () => {\n\t\t\t\tif (this.state.status === AudioPlayerStatus.Buffering && this.state.resource === resource) {\n\t\t\t\t\tthis.state = {\n\t\t\t\t\t\tstatus: AudioPlayerStatus.Playing,\n\t\t\t\t\t\tmissedFrames: 0,\n\t\t\t\t\t\tplaybackDuration: 0,\n\t\t\t\t\t\tresource,\n\t\t\t\t\t\tonStreamError,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tconst onFailureCallback = () => {\n\t\t\t\tif (this.state.status === AudioPlayerStatus.Buffering && this.state.resource === resource) {\n\t\t\t\t\tthis.state = {\n\t\t\t\t\t\tstatus: AudioPlayerStatus.Idle,\n\t\t\t\t\t};\n\t\t\t\t}\n\t\t\t};\n\n\t\t\tresource.playStream.once('readable', onReadableCallback);\n\n\t\t\tresource.playStream.once('end', onFailureCallback);\n\t\t\tresource.playStream.once('close', onFailureCallback);\n\t\t\tresource.playStream.once('finish', onFailureCallback);\n\n\t\t\tthis.state = {\n\t\t\t\tstatus: AudioPlayerStatus.Buffering,\n\t\t\t\tresource,\n\t\t\t\tonReadableCallback,\n\t\t\t\tonFailureCallback,\n\t\t\t\tonStreamError,\n\t\t\t};\n\t\t}\n\t}\n\n\t/**\n\t * Pauses playback of the current resource, if any.\n\t *\n\t * @param interpolateSilence - If true, the player will play 5 packets of silence after pausing to prevent audio glitches\n\t * @returns `true` if the player was successfully paused, otherwise `false`\n\t */\n\tpublic pause(interpolateSilence = true) {\n\t\tif (this.state.status !== AudioPlayerStatus.Playing) return false;\n\t\tthis.state = {\n\t\t\t...this.state,\n\t\t\tstatus: AudioPlayerStatus.Paused,\n\t\t\tsilencePacketsRemaining: interpolateSilence ? 5 : 0,\n\t\t};\n\t\treturn true;\n\t}\n\n\t/**\n\t * Unpauses playback of the current resource, if any.\n\t *\n\t * @returns `true` if the player was successfully unpaused, otherwise `false`\n\t */\n\tpublic unpause() {\n\t\tif (this.state.status !== AudioPlayerStatus.Paused) return false;\n\t\tthis.state = {\n\t\t\t...this.state,\n\t\t\tstatus: AudioPlayerStatus.Playing,\n\t\t\tmissedFrames: 0,\n\t\t};\n\t\treturn true;\n\t}\n\n\t/**\n\t * Stops playback of the current resource and destroys the resource. The player will either transition to the Idle state,\n\t * or remain in its current state until the silence padding frames of the resource have been played.\n\t *\n\t * @param force - If true, will force the player to enter the Idle state even if the resource has silence padding frames\n\t * @returns `true` if the player will come to a stop, otherwise `false`\n\t */\n\tpublic stop(force = false) {\n\t\tif (this.state.status === AudioPlayerStatus.Idle) return false;\n\t\tif (force || this.state.resource.silencePaddingFrames === 0) {\n\t\t\tthis.state = {\n\t\t\t\tstatus: AudioPlayerStatus.Idle,\n\t\t\t};\n\t\t} else if (this.state.resource.silenceRemaining === -1) {\n\t\t\tthis.state.resource.silenceRemaining = this.state.resource.silencePaddingFrames;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Checks whether the underlying resource (if any) is playable (readable)\n\t *\n\t * @returns `true` if the resource is playable, otherwise `false`\n\t */\n\tpublic checkPlayable() {\n\t\tconst state = this._state;\n\t\tif (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) return false;\n\n\t\t// If the stream has been destroyed or is no longer readable, then transition to the Idle state.\n\t\tif (!state.resource.readable) {\n\t\t\tthis.state = {\n\t\t\t\tstatus: AudioPlayerStatus.Idle,\n\t\t\t};\n\t\t\treturn false;\n\t\t}\n\n\t\treturn true;\n\t}\n\n\t/**\n\t * Called roughly every 20ms by the global audio player timer. Dispatches any audio packets that are buffered\n\t * by the active connections of this audio player.\n\t */\n\t// @ts-ignore\n\tprivate _stepDispatch() {\n\t\tconst state = this._state;\n\n\t\t// Guard against the Idle state\n\t\tif (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) return;\n\n\t\t// Dispatch any audio packets that were prepared in the previous cycle\n\t\tfor (const connection of this.playable) {\n\t\t\tconnection.dispatchAudio();\n\t\t}\n\t}\n\n\t/**\n\t * Called roughly every 20ms by the global audio player timer. Attempts to read an audio packet from the\n\t * underlying resource of the stream, and then has all the active connections of the audio player prepare it\n\t * (encrypt it, append header data) so that it is ready to play at the start of the next cycle.\n\t */\n\t// @ts-ignore\n\tprivate _stepPrepare() {\n\t\tconst state = this._state;\n\n\t\t// Guard against the Idle state\n\t\tif (state.status === AudioPlayerStatus.Idle || state.status === AudioPlayerStatus.Buffering) return;\n\n\t\t// List of connections that can receive the packet\n\t\tconst playable = this.playable;\n\n\t\t/* If the player was previously in the AutoPaused state, check to see whether there are newly available\n\t\t connections, allowing us to transition out of the AutoPaused state back into the Playing state */\n\t\tif (state.status === AudioPlayerStatus.AutoPaused && playable.length > 0) {\n\t\t\tthis.state = {\n\t\t\t\t...state,\n\t\t\t\tstatus: AudioPlayerStatus.Playing,\n\t\t\t\tmissedFrames: 0,\n\t\t\t};\n\t\t}\n\n\t\t/* If the player is (auto)paused, check to see whether silence packets should be played and\n\t\t set a timeout to begin the next cycle, ending the current cycle here. */\n\t\tif (state.status === AudioPlayerStatus.Paused || state.status === AudioPlayerStatus.AutoPaused) {\n\t\t\tif (state.silencePacketsRemaining > 0) {\n\t\t\t\tstate.silencePacketsRemaining--;\n\t\t\t\tthis._preparePacket(SILENCE_FRAME, playable, state);\n\t\t\t\tif (state.silencePacketsRemaining === 0) {\n\t\t\t\t\tthis._signalStopSpeaking();\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn;\n\t\t}\n\n\t\t// If there are no available connections in this cycle, observe the configured \"no subscriber\" behavior.\n\t\tif (playable.length === 0) {\n\t\t\tif (this.behaviors.noSubscriber === NoSubscriberBehavior.Pause) {\n\t\t\t\tthis.state = {\n\t\t\t\t\t...state,\n\t\t\t\t\tstatus: AudioPlayerStatus.AutoPaused,\n\t\t\t\t\tsilencePacketsRemaining: 5,\n\t\t\t\t};\n\t\t\t\treturn;\n\t\t\t} else if (this.behaviors.noSubscriber === NoSubscriberBehavior.Stop) {\n\t\t\t\tthis.stop(true);\n\t\t\t}\n\t\t}\n\n\t\t/**\n\t\t * Attempt to read an Opus packet from the resource. If there isn't an available packet,\n\t\t * play a silence packet. If there are 5 consecutive cycles with failed reads, then the\n\t\t * playback will end.\n\t\t */\n\t\tconst packet: Buffer | null = state.resource.read();\n\n\t\tif (state.status === AudioPlayerStatus.Playing) {\n\t\t\tif (packet) {\n\t\t\t\tthis._preparePacket(packet, playable, state);\n\t\t\t\tstate.missedFrames = 0;\n\t\t\t} else {\n\t\t\t\tthis._preparePacket(SILENCE_FRAME, playable, state);\n\t\t\t\tstate.missedFrames++;\n\t\t\t\tif (state.missedFrames >= this.behaviors.maxMissedFrames) {\n\t\t\t\t\tthis.stop();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Signals to all the subscribed connections that they should send a packet to Discord indicating\n\t * they are no longer speaking. Called once playback of a resource ends.\n\t */\n\tprivate _signalStopSpeaking() {\n\t\tfor (const { connection } of this.subscribers) {\n\t\t\tconnection.setSpeaking(false);\n\t\t}\n\t}\n\n\t/**\n\t * Instructs the given connections to each prepare this packet to be played at the start of the\n\t * next cycle.\n\t *\n\t * @param packet - The Opus packet to be prepared by each receiver\n\t * @param receivers - The connections that should play this packet\n\t */\n\tprivate _preparePacket(\n\t\tpacket: Buffer,\n\t\treceivers: VoiceConnection[],\n\t\tstate: AudioPlayerPausedState | AudioPlayerPlayingState,\n\t) {\n\t\tstate.playbackDuration += 20;\n\t\tfor (const connection of receivers) {\n\t\t\tconnection.prepareAudioPacket(packet);\n\t\t}\n\t}\n}\n\n/**\n * Creates a new AudioPlayer to be used.\n */\nexport function createAudioPlayer(options?: CreateAudioPlayerOptions) {\n\treturn new AudioPlayer(options);\n}\n","import type { AudioResource } from './AudioResource';\n\n/**\n * An error emitted by an AudioPlayer. Contains an attached resource to aid with\n * debugging and identifying where the error came from.\n */\nexport class AudioPlayerError extends Error {\n\t/**\n\t * The resource associated with the audio player at the time the error was thrown.\n\t */\n\tpublic readonly resource: AudioResource;\n\n\tpublic constructor(error: Error, resource: AudioResource) {\n\t\tsuper(error.message);\n\t\tthis.resource = resource;\n\t\tthis.name = error.name;\n\t\tthis.stack = error.stack!;\n\t}\n}\n","/* eslint-disable @typescript-eslint/dot-notation */\nimport type { VoiceConnection } from '../VoiceConnection';\nimport type { AudioPlayer } from './AudioPlayer';\n\n/**\n * Represents a subscription of a voice connection to an audio player, allowing\n * the audio player to play audio on the voice connection.\n */\nexport class PlayerSubscription {\n\t/**\n\t * The voice connection of this subscription.\n\t */\n\tpublic readonly connection: VoiceConnection;\n\n\t/**\n\t * The audio player of this subscription.\n\t */\n\tpublic readonly player: AudioPlayer;\n\n\tpublic constructor(connection: VoiceConnection, player: AudioPlayer) {\n\t\tthis.connection = connection;\n\t\tthis.player = player;\n\t}\n\n\t/**\n\t * Unsubscribes the connection from the audio player, meaning that the\n\t * audio player cannot stream audio to it until a new subscription is made.\n\t */\n\tpublic unsubscribe() {\n\t\tthis.connection['onSubscriptionRemoved'](this);\n\t\tthis.player['unsubscribe'](this);\n\t}\n}\n","import { EventEmitter } from 'node:events';\n\n/**\n * The known data for a user in a Discord voice connection.\n */\nexport interface VoiceUserData {\n\t/**\n\t * The SSRC of the user's audio stream.\n\t */\n\taudioSSRC: number;\n\n\t/**\n\t * The Discord user id of the user.\n\t */\n\tuserId: string;\n\n\t/**\n\t * The SSRC of the user's video stream (if one exists)\n\t * Cannot be 0. If undefined, the user has no video stream.\n\t */\n\tvideoSSRC?: number;\n}\n\nexport interface SSRCMap extends EventEmitter {\n\ton(event: 'create', listener: (newData: VoiceUserData) => void): this;\n\ton(event: 'update', listener: (oldData: VoiceUserData | undefined, newData: VoiceUserData) => void): this;\n\ton(event: 'delete', listener: (deletedData: VoiceUserData) => void): this;\n}\n\n/**\n * Maps audio SSRCs to data of users in voice connections.\n */\nexport class SSRCMap extends EventEmitter {\n\t/**\n\t * The underlying map.\n\t */\n\tprivate readonly map: Map;\n\n\tpublic constructor() {\n\t\tsuper();\n\t\tthis.map = new Map();\n\t}\n\n\t/**\n\t * Updates the map with new user data\n\t *\n\t * @param data - The data to update with\n\t */\n\tpublic update(data: VoiceUserData) {\n\t\tconst existing = this.map.get(data.audioSSRC);\n\n\t\tconst newValue = {\n\t\t\t...this.map.get(data.audioSSRC),\n\t\t\t...data,\n\t\t};\n\n\t\tthis.map.set(data.audioSSRC, newValue);\n\t\tif (!existing) this.emit('create', newValue);\n\t\tthis.emit('update', existing, newValue);\n\t}\n\n\t/**\n\t * Gets the stored voice data of a user.\n\t *\n\t * @param target - The target, either their user id or audio SSRC\n\t */\n\tpublic get(target: number | string) {\n\t\tif (typeof target === 'number') {\n\t\t\treturn this.map.get(target);\n\t\t}\n\n\t\tfor (const data of this.map.values()) {\n\t\t\tif (data.userId === target) {\n\t\t\t\treturn data;\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n\n\t/**\n\t * Deletes the stored voice data about a user.\n\t *\n\t * @param target - The target of the delete operation, either their audio SSRC or user id\n\t * @returns The data that was deleted, if any\n\t */\n\tpublic delete(target: number | string) {\n\t\tif (typeof target === 'number') {\n\t\t\tconst existing = this.map.get(target);\n\t\t\tif (existing) {\n\t\t\t\tthis.map.delete(target);\n\t\t\t\tthis.emit('delete', existing);\n\t\t\t}\n\n\t\t\treturn existing;\n\t\t}\n\n\t\tfor (const [audioSSRC, data] of this.map.entries()) {\n\t\t\tif (data.userId === target) {\n\t\t\t\tthis.map.delete(audioSSRC);\n\t\t\t\tthis.emit('delete', data);\n\t\t\t\treturn data;\n\t\t\t}\n\t\t}\n\n\t\treturn undefined;\n\t}\n}\n","/* eslint-disable @typescript-eslint/unified-signatures */\nimport { EventEmitter } from 'node:events';\n\nexport interface SpeakingMap extends EventEmitter {\n\t/**\n\t * Emitted when a user starts speaking.\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'start', listener: (userId: string) => void): this;\n\n\t/**\n\t * Emitted when a user ends speaking.\n\t *\n\t * @eventProperty\n\t */\n\ton(event: 'end', listener: (userId: string) => void): this;\n}\n\n/**\n * Tracks the speaking states of users in a voice channel.\n */\nexport class SpeakingMap extends EventEmitter {\n\t/**\n\t * The delay after a packet is received from a user until they're marked as not speaking anymore.\n\t */\n\tpublic static readonly DELAY = 100;\n\n\t/**\n\t * The currently speaking users, mapped to the milliseconds since UNIX epoch at which they started speaking.\n\t */\n\tpublic readonly users: Map;\n\n\tprivate readonly speakingTimeouts: Map;\n\n\tpublic constructor() {\n\t\tsuper();\n\t\tthis.users = new Map();\n\t\tthis.speakingTimeouts = new Map();\n\t}\n\n\tpublic onPacket(userId: string) {\n\t\tconst timeout = this.speakingTimeouts.get(userId);\n\t\tif (timeout) {\n\t\t\tclearTimeout(timeout);\n\t\t} else {\n\t\t\tthis.users.set(userId, Date.now());\n\t\t\tthis.emit('start', userId);\n\t\t}\n\n\t\tthis.startTimeout(userId);\n\t}\n\n\tprivate startTimeout(userId: string) {\n\t\tthis.speakingTimeouts.set(\n\t\t\tuserId,\n\t\t\tsetTimeout(() => {\n\t\t\t\tthis.emit('end', userId);\n\t\t\t\tthis.speakingTimeouts.delete(userId);\n\t\t\t\tthis.users.delete(userId);\n\t\t\t}, SpeakingMap.DELAY),\n\t\t);\n\t}\n}\n","import type { JoinConfig } from './DataStore';\nimport { createVoiceConnection } from './VoiceConnection';\nimport type { DiscordGatewayAdapterCreator } from './util/adapter';\n\n/**\n * The options that can be given when creating a voice connection.\n */\nexport interface CreateVoiceConnectionOptions {\n\tadapterCreator: DiscordGatewayAdapterCreator;\n\n\t/**\n\t * If true, debug messages will be enabled for the voice connection and its\n\t * related components. Defaults to false.\n\t */\n\tdebug?: boolean | undefined;\n}\n\n/**\n * The options that can be given when joining a voice channel.\n */\nexport interface JoinVoiceChannelOptions {\n\t/**\n\t * The id of the Discord voice channel to join.\n\t */\n\tchannelId: string;\n\n\t/**\n\t * An optional group identifier for the voice connection.\n\t */\n\tgroup?: string;\n\n\t/**\n\t * The id of the guild that the voice channel belongs to.\n\t */\n\tguildId: string;\n\n\t/**\n\t * Whether to join the channel deafened (defaults to true)\n\t */\n\tselfDeaf?: boolean;\n\n\t/**\n\t * Whether to join the channel muted (defaults to true)\n\t */\n\tselfMute?: boolean;\n}\n\n/**\n * Creates a VoiceConnection to a Discord voice channel.\n *\n * @param options - the options for joining the voice channel\n */\nexport function joinVoiceChannel(options: CreateVoiceConnectionOptions & JoinVoiceChannelOptions) {\n\tconst joinConfig: JoinConfig = {\n\t\tselfDeaf: true,\n\t\tselfMute: false,\n\t\tgroup: 'default',\n\t\t...options,\n\t};\n\n\treturn createVoiceConnection(joinConfig, {\n\t\tadapterCreator: options.adapterCreator,\n\t\tdebug: options.debug,\n\t});\n}\n","import type { Buffer } from 'node:buffer';\nimport { pipeline, type Readable } from 'node:stream';\nimport prism from 'prism-media';\nimport { noop } from '../util/util';\nimport { SILENCE_FRAME, type AudioPlayer } from './AudioPlayer';\nimport { findPipeline, StreamType, TransformerType, type Edge } from './TransformerGraph';\n\n/**\n * Options that are set when creating a new audio resource.\n *\n * @typeParam T - the type for the metadata (if any) of the audio resource\n */\nexport interface CreateAudioResourceOptions {\n\t/**\n\t * Whether or not inline volume should be enabled. If enabled, you will be able to change the volume\n\t * of the stream on-the-fly. However, this also increases the performance cost of playback. Defaults to `false`.\n\t */\n\tinlineVolume?: boolean;\n\n\t/**\n\t * The type of the input stream. Defaults to `StreamType.Arbitrary`.\n\t */\n\tinputType?: StreamType;\n\n\t/**\n\t * Optional metadata that can be attached to the resource (e.g. track title, random id).\n\t * This is useful for identification purposes when the resource is passed around in events.\n\t * See {@link AudioResource.metadata}\n\t */\n\tmetadata?: T;\n\n\t/**\n\t * The number of silence frames to append to the end of the resource's audio stream, to prevent interpolation glitches.\n\t * Defaults to 5.\n\t */\n\tsilencePaddingFrames?: number;\n}\n\n/**\n * Represents an audio resource that can be played by an audio player.\n *\n * @typeParam T - the type for the metadata (if any) of the audio resource\n */\nexport class AudioResource {\n\t/**\n\t * An object-mode Readable stream that emits Opus packets. This is what is played by audio players.\n\t */\n\tpublic readonly playStream: Readable;\n\n\t/**\n\t * The pipeline used to convert the input stream into a playable format. For example, this may\n\t * contain an FFmpeg component for arbitrary inputs, and it may contain a VolumeTransformer component\n\t * for resources with inline volume transformation enabled.\n\t */\n\tpublic readonly edges: readonly Edge[];\n\n\t/**\n\t * Optional metadata that can be used to identify the resource.\n\t */\n\tpublic metadata: T;\n\n\t/**\n\t * If the resource was created with inline volume transformation enabled, then this will be a\n\t * prism-media VolumeTransformer. You can use this to alter the volume of the stream.\n\t */\n\tpublic readonly volume?: prism.VolumeTransformer;\n\n\t/**\n\t * If using an Opus encoder to create this audio resource, then this will be a prism-media opus.Encoder.\n\t * You can use this to control settings such as bitrate, FEC, PLP.\n\t */\n\tpublic readonly encoder?: prism.opus.Encoder;\n\n\t/**\n\t * The audio player that the resource is subscribed to, if any.\n\t */\n\tpublic audioPlayer?: AudioPlayer | undefined;\n\n\t/**\n\t * The playback duration of this audio resource, given in milliseconds.\n\t */\n\tpublic playbackDuration = 0;\n\n\t/**\n\t * Whether or not the stream for this resource has started (data has become readable)\n\t */\n\tpublic started = false;\n\n\t/**\n\t * The number of silence frames to append to the end of the resource's audio stream, to prevent interpolation glitches.\n\t */\n\tpublic readonly silencePaddingFrames: number;\n\n\t/**\n\t * The number of remaining silence frames to play. If -1, the frames have not yet started playing.\n\t */\n\tpublic silenceRemaining = -1;\n\n\tpublic constructor(edges: readonly Edge[], streams: readonly Readable[], metadata: T, silencePaddingFrames: number) {\n\t\tthis.edges = edges;\n\t\tthis.playStream = streams.length > 1 ? (pipeline(streams, noop) as any as Readable) : streams[0]!;\n\t\tthis.metadata = metadata;\n\t\tthis.silencePaddingFrames = silencePaddingFrames;\n\n\t\tfor (const stream of streams) {\n\t\t\tif (stream instanceof prism.VolumeTransformer) {\n\t\t\t\tthis.volume = stream;\n\t\t\t} else if (stream instanceof prism.opus.Encoder) {\n\t\t\t\tthis.encoder = stream;\n\t\t\t}\n\t\t}\n\n\t\tthis.playStream.once('readable', () => (this.started = true));\n\t}\n\n\t/**\n\t * Whether this resource is readable. If the underlying resource is no longer readable, this will still return true\n\t * while there are silence padding frames left to play.\n\t */\n\tpublic get readable() {\n\t\tif (this.silenceRemaining === 0) return false;\n\t\tconst real = this.playStream.readable;\n\t\tif (!real) {\n\t\t\tif (this.silenceRemaining === -1) this.silenceRemaining = this.silencePaddingFrames;\n\t\t\treturn this.silenceRemaining !== 0;\n\t\t}\n\n\t\treturn real;\n\t}\n\n\t/**\n\t * Whether this resource has ended or not.\n\t */\n\tpublic get ended() {\n\t\treturn this.playStream.readableEnded || this.playStream.destroyed || this.silenceRemaining === 0;\n\t}\n\n\t/**\n\t * Attempts to read an Opus packet from the audio resource. If a packet is available, the playbackDuration\n\t * is incremented.\n\t *\n\t * @remarks\n\t * It is advisable to check that the playStream is readable before calling this method. While no runtime\n\t * errors will be thrown, you should check that the resource is still available before attempting to\n\t * read from it.\n\t * @internal\n\t */\n\tpublic read(): Buffer | null {\n\t\tif (this.silenceRemaining === 0) {\n\t\t\treturn null;\n\t\t} else if (this.silenceRemaining > 0) {\n\t\t\tthis.silenceRemaining--;\n\t\t\treturn SILENCE_FRAME;\n\t\t}\n\n\t\tconst packet = this.playStream.read() as Buffer | null;\n\t\tif (packet) {\n\t\t\tthis.playbackDuration += 20;\n\t\t}\n\n\t\treturn packet;\n\t}\n}\n\n/**\n * Ensures that a path contains at least one volume transforming component.\n *\n * @param path - The path to validate constraints on\n */\nexport const VOLUME_CONSTRAINT = (path: Edge[]) => path.some((edge) => edge.type === TransformerType.InlineVolume);\n\nexport const NO_CONSTRAINT = () => true;\n\n/**\n * Tries to infer the type of a stream to aid with transcoder pipelining.\n *\n * @param stream - The stream to infer the type of\n */\nexport function inferStreamType(stream: Readable): {\n\thasVolume: boolean;\n\tstreamType: StreamType;\n} {\n\tif (stream instanceof prism.opus.Encoder) {\n\t\treturn { streamType: StreamType.Opus, hasVolume: false };\n\t} else if (stream instanceof prism.opus.Decoder) {\n\t\treturn { streamType: StreamType.Raw, hasVolume: false };\n\t} else if (stream instanceof prism.VolumeTransformer) {\n\t\treturn { streamType: StreamType.Raw, hasVolume: true };\n\t} else if (stream instanceof prism.opus.OggDemuxer) {\n\t\treturn { streamType: StreamType.Opus, hasVolume: false };\n\t} else if (stream instanceof prism.opus.WebmDemuxer) {\n\t\treturn { streamType: StreamType.Opus, hasVolume: false };\n\t}\n\n\treturn { streamType: StreamType.Arbitrary, hasVolume: false };\n}\n\n/**\n * Creates an audio resource that can be played by audio players.\n *\n * @remarks\n * If the input is given as a string, then the inputType option will be overridden and FFmpeg will be used.\n *\n * If the input is not in the correct format, then a pipeline of transcoders and transformers will be created\n * to ensure that the resultant stream is in the correct format for playback. This could involve using FFmpeg,\n * Opus transcoders, and Ogg/WebM demuxers.\n * @param input - The resource to play\n * @param options - Configurable options for creating the resource\n * @typeParam T - the type for the metadata (if any) of the audio resource\n */\nexport function createAudioResource(\n\tinput: Readable | string,\n\toptions: CreateAudioResourceOptions &\n\t\tPick<\n\t\t\tT extends null | undefined ? CreateAudioResourceOptions : Required>,\n\t\t\t'metadata'\n\t\t>,\n): AudioResource;\n\n/**\n * Creates an audio resource that can be played by audio players.\n *\n * @remarks\n * If the input is given as a string, then the inputType option will be overridden and FFmpeg will be used.\n *\n * If the input is not in the correct format, then a pipeline of transcoders and transformers will be created\n * to ensure that the resultant stream is in the correct format for playback. This could involve using FFmpeg,\n * Opus transcoders, and Ogg/WebM demuxers.\n * @param input - The resource to play\n * @param options - Configurable options for creating the resource\n * @typeParam T - the type for the metadata (if any) of the audio resource\n */\nexport function createAudioResource(\n\tinput: Readable | string,\n\toptions?: Omit, 'metadata'>,\n): AudioResource;\n\n/**\n * Creates an audio resource that can be played by audio players.\n *\n * @remarks\n * If the input is given as a string, then the inputType option will be overridden and FFmpeg will be used.\n *\n * If the input is not in the correct format, then a pipeline of transcoders and transformers will be created\n * to ensure that the resultant stream is in the correct format for playback. This could involve using FFmpeg,\n * Opus transcoders, and Ogg/WebM demuxers.\n * @param input - The resource to play\n * @param options - Configurable options for creating the resource\n * @typeParam T - the type for the metadata (if any) of the audio resource\n */\nexport function createAudioResource(\n\tinput: Readable | string,\n\toptions: CreateAudioResourceOptions = {},\n): AudioResource {\n\tlet inputType = options.inputType;\n\tlet needsInlineVolume = Boolean(options.inlineVolume);\n\n\t// string inputs can only be used with FFmpeg\n\tif (typeof input === 'string') {\n\t\tinputType = StreamType.Arbitrary;\n\t} else if (inputType === undefined) {\n\t\tconst analysis = inferStreamType(input);\n\t\tinputType = analysis.streamType;\n\t\tneedsInlineVolume = needsInlineVolume && !analysis.hasVolume;\n\t}\n\n\tconst transformerPipeline = findPipeline(inputType, needsInlineVolume ? VOLUME_CONSTRAINT : NO_CONSTRAINT);\n\n\tif (transformerPipeline.length === 0) {\n\t\tif (typeof input === 'string') throw new Error(`Invalid pipeline constructed for string resource '${input}'`);\n\t\t// No adjustments required\n\t\treturn new AudioResource([], [input], (options.metadata ?? null) as T, options.silencePaddingFrames ?? 5);\n\t}\n\n\tconst streams = transformerPipeline.map((edge) => edge.transformer(input));\n\tif (typeof input !== 'string') streams.unshift(input);\n\n\treturn new AudioResource(\n\t\ttransformerPipeline,\n\t\tstreams,\n\t\t(options.metadata ?? null) as T,\n\t\toptions.silencePaddingFrames ?? 5,\n\t);\n}\n","import type { Readable } from 'node:stream';\nimport prism from 'prism-media';\n\n/**\n * This module creates a Transformer Graph to figure out what the most efficient way\n * of transforming the input stream into something playable would be.\n */\n\nconst FFMPEG_PCM_ARGUMENTS = ['-analyzeduration', '0', '-loglevel', '0', '-f', 's16le', '-ar', '48000', '-ac', '2'];\nconst FFMPEG_OPUS_ARGUMENTS = [\n\t'-analyzeduration',\n\t'0',\n\t'-loglevel',\n\t'0',\n\t'-acodec',\n\t'libopus',\n\t'-f',\n\t'opus',\n\t'-ar',\n\t'48000',\n\t'-ac',\n\t'2',\n];\n\n/**\n * The different types of stream that can exist within the pipeline.\n *\n * @remarks\n * - `Arbitrary` - the type of the stream at this point is unknown.\n * - `Raw` - the stream at this point is s16le PCM.\n * - `OggOpus` - the stream at this point is Opus audio encoded in an Ogg wrapper.\n * - `WebmOpus` - the stream at this point is Opus audio encoded in a WebM wrapper.\n * - `Opus` - the stream at this point is Opus audio, and the stream is in object-mode. This is ready to play.\n */\nexport enum StreamType {\n\tArbitrary = 'arbitrary',\n\tOggOpus = 'ogg/opus',\n\tOpus = 'opus',\n\tRaw = 'raw',\n\tWebmOpus = 'webm/opus',\n}\n\n/**\n * The different types of transformers that can exist within the pipeline.\n */\nexport enum TransformerType {\n\tFFmpegOgg = 'ffmpeg ogg',\n\tFFmpegPCM = 'ffmpeg pcm',\n\tInlineVolume = 'volume transformer',\n\tOggOpusDemuxer = 'ogg/opus demuxer',\n\tOpusDecoder = 'opus decoder',\n\tOpusEncoder = 'opus encoder',\n\tWebmOpusDemuxer = 'webm/opus demuxer',\n}\n\n/**\n * Represents a pathway from one stream type to another using a transformer.\n */\nexport interface Edge {\n\tcost: number;\n\tfrom: Node;\n\tto: Node;\n\ttransformer(input: Readable | string): Readable;\n\ttype: TransformerType;\n}\n\n/**\n * Represents a type of stream within the graph, e.g. an Opus stream, or a stream of raw audio.\n */\nexport class Node {\n\t/**\n\t * The outbound edges from this node.\n\t */\n\tpublic readonly edges: Edge[] = [];\n\n\t/**\n\t * The type of stream for this node.\n\t */\n\tpublic readonly type: StreamType;\n\n\tpublic constructor(type: StreamType) {\n\t\tthis.type = type;\n\t}\n\n\t/**\n\t * Creates an outbound edge from this node.\n\t *\n\t * @param edge - The edge to create\n\t */\n\tpublic addEdge(edge: Omit) {\n\t\tthis.edges.push({ ...edge, from: this });\n\t}\n}\n\n// Create a node for each stream type\nconst NODES = new Map();\nfor (const streamType of Object.values(StreamType)) {\n\tNODES.set(streamType, new Node(streamType));\n}\n\n/**\n * Gets a node from its stream type.\n *\n * @param type - The stream type of the target node\n */\nexport function getNode(type: StreamType) {\n\tconst node = NODES.get(type);\n\tif (!node) throw new Error(`Node type '${type}' does not exist!`);\n\treturn node;\n}\n\ngetNode(StreamType.Raw).addEdge({\n\ttype: TransformerType.OpusEncoder,\n\tto: getNode(StreamType.Opus),\n\tcost: 1.5,\n\ttransformer: () => new prism.opus.Encoder({ rate: 48_000, channels: 2, frameSize: 960 }),\n});\n\ngetNode(StreamType.Opus).addEdge({\n\ttype: TransformerType.OpusDecoder,\n\tto: getNode(StreamType.Raw),\n\tcost: 1.5,\n\ttransformer: () => new prism.opus.Decoder({ rate: 48_000, channels: 2, frameSize: 960 }),\n});\n\ngetNode(StreamType.OggOpus).addEdge({\n\ttype: TransformerType.OggOpusDemuxer,\n\tto: getNode(StreamType.Opus),\n\tcost: 1,\n\ttransformer: () => new prism.opus.OggDemuxer(),\n});\n\ngetNode(StreamType.WebmOpus).addEdge({\n\ttype: TransformerType.WebmOpusDemuxer,\n\tto: getNode(StreamType.Opus),\n\tcost: 1,\n\ttransformer: () => new prism.opus.WebmDemuxer(),\n});\n\nconst FFMPEG_PCM_EDGE: Omit = {\n\ttype: TransformerType.FFmpegPCM,\n\tto: getNode(StreamType.Raw),\n\tcost: 2,\n\ttransformer: (input) =>\n\t\tnew prism.FFmpeg({\n\t\t\targs: typeof input === 'string' ? ['-i', input, ...FFMPEG_PCM_ARGUMENTS] : FFMPEG_PCM_ARGUMENTS,\n\t\t}),\n};\n\ngetNode(StreamType.Arbitrary).addEdge(FFMPEG_PCM_EDGE);\ngetNode(StreamType.OggOpus).addEdge(FFMPEG_PCM_EDGE);\ngetNode(StreamType.WebmOpus).addEdge(FFMPEG_PCM_EDGE);\n\ngetNode(StreamType.Raw).addEdge({\n\ttype: TransformerType.InlineVolume,\n\tto: getNode(StreamType.Raw),\n\tcost: 0.5,\n\ttransformer: () => new prism.VolumeTransformer({ type: 's16le' }),\n});\n\n// Try to enable FFmpeg Ogg optimizations\nfunction canEnableFFmpegOptimizations(): boolean {\n\ttry {\n\t\treturn prism.FFmpeg.getInfo().output.includes('--enable-libopus');\n\t} catch {}\n\n\treturn false;\n}\n\nif (canEnableFFmpegOptimizations()) {\n\tconst FFMPEG_OGG_EDGE: Omit = {\n\t\ttype: TransformerType.FFmpegOgg,\n\t\tto: getNode(StreamType.OggOpus),\n\t\tcost: 2,\n\t\ttransformer: (input) =>\n\t\t\tnew prism.FFmpeg({\n\t\t\t\targs: typeof input === 'string' ? ['-i', input, ...FFMPEG_OPUS_ARGUMENTS] : FFMPEG_OPUS_ARGUMENTS,\n\t\t\t}),\n\t};\n\tgetNode(StreamType.Arbitrary).addEdge(FFMPEG_OGG_EDGE);\n\t// Include Ogg and WebM as well in case they have different sampling rates or are mono instead of stereo\n\t// at the moment, this will not do anything. However, if/when detection for correct Opus headers is\n\t// implemented, this will help inform the voice engine that it is able to transcode the audio.\n\tgetNode(StreamType.OggOpus).addEdge(FFMPEG_OGG_EDGE);\n\tgetNode(StreamType.WebmOpus).addEdge(FFMPEG_OGG_EDGE);\n}\n\n/**\n * Represents a step in the path from node A to node B.\n */\ninterface Step {\n\t/**\n\t * The cost of the steps after this step.\n\t */\n\tcost: number;\n\n\t/**\n\t * The edge associated with this step.\n\t */\n\tedge?: Edge;\n\n\t/**\n\t * The next step.\n\t */\n\tnext?: Step;\n}\n\n/**\n * Finds the shortest cost path from node A to node B.\n *\n * @param from - The start node\n * @param constraints - Extra validation for a potential solution. Takes a path, returns true if the path is valid\n * @param goal - The target node\n * @param path - The running path\n * @param depth - The number of remaining recursions\n */\nfunction findPath(\n\tfrom: Node,\n\tconstraints: (path: Edge[]) => boolean,\n\tgoal = getNode(StreamType.Opus),\n\tpath: Edge[] = [],\n\tdepth = 5,\n): Step {\n\tif (from === goal && constraints(path)) {\n\t\treturn { cost: 0 };\n\t} else if (depth === 0) {\n\t\treturn { cost: Number.POSITIVE_INFINITY };\n\t}\n\n\tlet currentBest: Step | undefined;\n\tfor (const edge of from.edges) {\n\t\tif (currentBest && edge.cost > currentBest.cost) continue;\n\t\tconst next = findPath(edge.to, constraints, goal, [...path, edge], depth - 1);\n\t\tconst cost = edge.cost + next.cost;\n\t\tif (!currentBest || cost < currentBest.cost) {\n\t\t\tcurrentBest = { cost, edge, next };\n\t\t}\n\t}\n\n\treturn currentBest ?? { cost: Number.POSITIVE_INFINITY };\n}\n\n/**\n * Takes the solution from findPath and assembles it into a list of edges.\n *\n * @param step - The first step of the path\n */\nfunction constructPipeline(step: Step) {\n\tconst edges = [];\n\tlet current: Step | undefined = step;\n\twhile (current?.edge) {\n\t\tedges.push(current.edge);\n\t\tcurrent = current.next;\n\t}\n\n\treturn edges;\n}\n\n/**\n * Finds the lowest-cost pipeline to convert the input stream type into an Opus stream.\n *\n * @param from - The stream type to start from\n * @param constraint - Extra constraints that may be imposed on potential solution\n */\nexport function findPipeline(from: StreamType, constraint: (path: Edge[]) => boolean) {\n\treturn constructPipeline(findPath(getNode(from), constraint));\n}\n","/* eslint-disable @typescript-eslint/no-var-requires */\n/* eslint-disable @typescript-eslint/no-require-imports */\nimport { resolve, dirname } from 'node:path';\nimport prism from 'prism-media';\n\n/**\n * Tries to find the package.json file for a given module.\n *\n * @param dir - The directory to look in\n * @param packageName - The name of the package to look for\n * @param depth - The maximum recursion depth\n */\nfunction findPackageJSON(\n\tdir: string,\n\tpackageName: string,\n\tdepth: number,\n): { name: string; version: string } | undefined {\n\tif (depth === 0) return undefined;\n\tconst attemptedPath = resolve(dir, './package.json');\n\ttry {\n\t\tconst pkg = require(attemptedPath);\n\t\tif (pkg.name !== packageName) throw new Error('package.json does not match');\n\t\treturn pkg;\n\t} catch {\n\t\treturn findPackageJSON(resolve(dir, '..'), packageName, depth - 1);\n\t}\n}\n\n/**\n * Tries to find the version of a dependency.\n *\n * @param name - The package to find the version of\n */\nfunction version(name: string): string {\n\ttry {\n\t\tif (name === '@discordjs/voice') {\n\t\t\treturn '0.16.0';\n\t\t}\n\n\t\tconst pkg = findPackageJSON(dirname(require.resolve(name)), name, 3);\n\t\treturn pkg?.version ?? 'not found';\n\t} catch {\n\t\treturn 'not found';\n\t}\n}\n\n/**\n * Generates a report of the dependencies used by the \\@discordjs/voice module.\n * Useful for debugging.\n */\nexport function generateDependencyReport() {\n\tconst report = [];\n\tconst addVersion = (name: string) => report.push(`- ${name}: ${version(name)}`);\n\t// general\n\treport.push('Core Dependencies');\n\taddVersion('@discordjs/voice');\n\taddVersion('prism-media');\n\treport.push('');\n\n\t// opus\n\treport.push('Opus Libraries');\n\taddVersion('@discordjs/opus');\n\taddVersion('opusscript');\n\treport.push('');\n\n\t// encryption\n\treport.push('Encryption Libraries');\n\taddVersion('sodium-native');\n\taddVersion('sodium');\n\taddVersion('libsodium-wrappers');\n\taddVersion('tweetnacl');\n\treport.push('');\n\n\t// ffmpeg\n\treport.push('FFmpeg');\n\ttry {\n\t\tconst info = prism.FFmpeg.getInfo();\n\t\treport.push(`- version: ${info.version}`);\n\t\treport.push(`- libopus: ${info.output.includes('--enable-libopus') ? 'yes' : 'no'}`);\n\t} catch {\n\t\treport.push('- not found');\n\t}\n\n\treturn ['-'.repeat(50), ...report, '-'.repeat(50)].join('\\n');\n}\n","import { type EventEmitter, once } from 'node:events';\nimport type { VoiceConnection, VoiceConnectionStatus } from '../VoiceConnection';\nimport type { AudioPlayer, AudioPlayerStatus } from '../audio/AudioPlayer';\nimport { abortAfter } from './abortAfter';\n\n/**\n * Allows a voice connection a specified amount of time to enter a given state, otherwise rejects with an error.\n *\n * @param target - The voice connection that we want to observe the state change for\n * @param status - The status that the voice connection should be in\n * @param timeoutOrSignal - The maximum time we are allowing for this to occur, or a signal that will abort the operation\n */\nexport function entersState(\n\ttarget: VoiceConnection,\n\tstatus: VoiceConnectionStatus,\n\ttimeoutOrSignal: AbortSignal | number,\n): Promise;\n\n/**\n * Allows an audio player a specified amount of time to enter a given state, otherwise rejects with an error.\n *\n * @param target - The audio player that we want to observe the state change for\n * @param status - The status that the audio player should be in\n * @param timeoutOrSignal - The maximum time we are allowing for this to occur, or a signal that will abort the operation\n */\nexport function entersState(\n\ttarget: AudioPlayer,\n\tstatus: AudioPlayerStatus,\n\ttimeoutOrSignal: AbortSignal | number,\n): Promise;\n\n/**\n * Allows a target a specified amount of time to enter a given state, otherwise rejects with an error.\n *\n * @param target - The object that we want to observe the state change for\n * @param status - The status that the target should be in\n * @param timeoutOrSignal - The maximum time we are allowing for this to occur, or a signal that will abort the operation\n */\nexport async function entersState(\n\ttarget: T,\n\tstatus: AudioPlayerStatus | VoiceConnectionStatus,\n\ttimeoutOrSignal: AbortSignal | number,\n) {\n\tif (target.state.status !== status) {\n\t\tconst [ac, signal] =\n\t\t\ttypeof timeoutOrSignal === 'number' ? abortAfter(timeoutOrSignal) : [undefined, timeoutOrSignal];\n\t\ttry {\n\t\t\tawait once(target as EventEmitter, status, { signal });\n\t\t} finally {\n\t\t\tac?.abort();\n\t\t}\n\t}\n\n\treturn target;\n}\n","/**\n * Creates an abort controller that aborts after the given time.\n *\n * @param delay - The time in milliseconds to wait before aborting\n */\nexport function abortAfter(delay: number): [AbortController, AbortSignal] {\n\tconst ac = new AbortController();\n\tconst timeout = setTimeout(() => ac.abort(), delay);\n\t// @ts-expect-error: No type for timeout\n\tac.signal.addEventListener('abort', () => clearTimeout(timeout));\n\treturn [ac, ac.signal];\n}\n","import { Buffer } from 'node:buffer';\nimport process from 'node:process';\nimport { Readable } from 'node:stream';\nimport prism from 'prism-media';\nimport { StreamType } from '..';\nimport { noop } from './util';\n\n/**\n * Takes an Opus Head, and verifies whether the associated Opus audio is suitable to play in a Discord voice channel.\n *\n * @param opusHead - The Opus Head to validate\n * @returns `true` if suitable to play in a Discord voice channel, otherwise `false`\n */\nexport function validateDiscordOpusHead(opusHead: Buffer): boolean {\n\tconst channels = opusHead.readUInt8(9);\n\tconst sampleRate = opusHead.readUInt32LE(12);\n\treturn channels === 2 && sampleRate === 48_000;\n}\n\n/**\n * The resulting information after probing an audio stream\n */\nexport interface ProbeInfo {\n\t/**\n\t * The readable audio stream to use. You should use this rather than the input stream, as the probing\n\t * function can sometimes read the input stream to its end and cause the stream to close.\n\t */\n\tstream: Readable;\n\n\t/**\n\t * The recommended stream type for this audio stream.\n\t */\n\ttype: StreamType;\n}\n\n/**\n * Attempt to probe a readable stream to figure out whether it can be demuxed using an Ogg or WebM Opus demuxer.\n *\n * @param stream - The readable stream to probe\n * @param probeSize - The number of bytes to attempt to read before giving up on the probe\n * @param validator - The Opus Head validator function\n * @experimental\n */\nexport async function demuxProbe(\n\tstream: Readable,\n\tprobeSize = 1_024,\n\tvalidator = validateDiscordOpusHead,\n): Promise {\n\treturn new Promise((resolve, reject) => {\n\t\t// Preconditions\n\t\tif (stream.readableObjectMode) {\n\t\t\treject(new Error('Cannot probe a readable stream in object mode'));\n\t\t\treturn;\n\t\t}\n\n\t\tif (stream.readableEnded) {\n\t\t\treject(new Error('Cannot probe a stream that has ended'));\n\t\t\treturn;\n\t\t}\n\n\t\tlet readBuffer = Buffer.alloc(0);\n\n\t\tlet resolved: StreamType | undefined;\n\n\t\tconst finish = (type: StreamType) => {\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\t\tstream.off('data', onData);\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\t\tstream.off('close', onClose);\n\t\t\t// eslint-disable-next-line @typescript-eslint/no-use-before-define\n\t\t\tstream.off('end', onClose);\n\t\t\tstream.pause();\n\t\t\tresolved = type;\n\t\t\tif (stream.readableEnded) {\n\t\t\t\tresolve({\n\t\t\t\t\tstream: Readable.from(readBuffer),\n\t\t\t\t\ttype,\n\t\t\t\t});\n\t\t\t} else {\n\t\t\t\tif (readBuffer.length > 0) {\n\t\t\t\t\tstream.push(readBuffer);\n\t\t\t\t}\n\n\t\t\t\tresolve({\n\t\t\t\t\tstream,\n\t\t\t\t\ttype,\n\t\t\t\t});\n\t\t\t}\n\t\t};\n\n\t\tconst foundHead = (type: StreamType) => (head: Buffer) => {\n\t\t\tif (validator(head)) {\n\t\t\t\tfinish(type);\n\t\t\t}\n\t\t};\n\n\t\tconst webm = new prism.opus.WebmDemuxer();\n\t\twebm.once('error', noop);\n\t\twebm.on('head', foundHead(StreamType.WebmOpus));\n\n\t\tconst ogg = new prism.opus.OggDemuxer();\n\t\togg.once('error', noop);\n\t\togg.on('head', foundHead(StreamType.OggOpus));\n\n\t\tconst onClose = () => {\n\t\t\tif (!resolved) {\n\t\t\t\tfinish(StreamType.Arbitrary);\n\t\t\t}\n\t\t};\n\n\t\tconst onData = (buffer: Buffer) => {\n\t\t\treadBuffer = Buffer.concat([readBuffer, buffer]);\n\n\t\t\twebm.write(buffer);\n\t\t\togg.write(buffer);\n\n\t\t\tif (readBuffer.length >= probeSize) {\n\t\t\t\tstream.off('data', onData);\n\t\t\t\tstream.pause();\n\t\t\t\tprocess.nextTick(onClose);\n\t\t\t}\n\t\t};\n\n\t\tstream.once('error', reject);\n\t\tstream.on('data', onData);\n\t\tstream.once('close', onClose);\n\t\tstream.once('end', onClose);\n\t});\n}\n","export * from './joinVoiceChannel';\nexport * from './audio/index';\nexport * from './util/index';\nexport * from './receive/index';\n\nexport {\n\tVoiceConnection,\n\ttype VoiceConnectionState,\n\tVoiceConnectionStatus,\n\ttype VoiceConnectionConnectingState,\n\ttype VoiceConnectionDestroyedState,\n\ttype VoiceConnectionDisconnectedState,\n\ttype VoiceConnectionDisconnectedBaseState,\n\ttype VoiceConnectionDisconnectedOtherState,\n\ttype VoiceConnectionDisconnectedWebSocketState,\n\tVoiceConnectionDisconnectReason,\n\ttype VoiceConnectionReadyState,\n\ttype VoiceConnectionSignallingState,\n} from './VoiceConnection';\n\nexport { type JoinConfig, getVoiceConnection, getVoiceConnections, getGroups } from './DataStore';\n\n/**\n * The {@link https://github.com/discordjs/discord.js/blob/main/packages/voice/#readme | @discordjs/voice} version\n * that you are currently using.\n */\n// This needs to explicitly be `string` so it is not typed as a \"const string\" that gets injected by esbuild\nexport const version = '0.16.0' as string;\n"],"mappings":";;;;;;;;;;;;;;;;AAEA,SAAS,gBAAAA,qBAAoB;;;ACF7B,SAAS,sBAAsB;AAkBxB,SAAS,8BAA8B,QAAoB;AACjE,SAAO;AAAA,IACN,IAAI,eAAe;AAAA;AAAA,IAEnB,GAAG;AAA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WAAO,KAAK,OAAO,OAAO;AAAA,EAC3B,CAAC;AACF;AArFsB;;;AChBf,IAAMG,WAAU;","names":["EventEmitter","Buffer","EventEmitter","VoiceOpcodes","Buffer","nonce","Buffer","Buffer","Buffer","resolve","EventEmitter","EventEmitter","nonce","Buffer","option","EventEmitter","VoiceOpcodes","Buffer","VoiceOpcodes","Buffer","EventEmitter","Buffer","NoSubscriberBehavior","AudioPlayerStatus","stringifyState","EventEmitter","EndBehaviorType","EventEmitter","EventEmitter","EventEmitter","EventEmitter","VoiceOpcodes","nonce","Buffer","VoiceConnectionStatus","VoiceConnectionDisconnectReason","EventEmitter","prism","StreamType","prism","prism","prism","Buffer","Readable","prism","resolve","Buffer","Readable","prism","version"]} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/LICENSE b/node_modules/@discordjs/voice/node_modules/discord-api-types/LICENSE deleted file mode 100644 index a8b1694..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2020 vladfrangu - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/README.md b/node_modules/@discordjs/voice/node_modules/discord-api-types/README.md deleted file mode 100644 index f33c5df..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/README.md +++ /dev/null @@ -1,105 +0,0 @@ -# Discord API Types - -[![discord-api-types](https://raw.githubusercontent.com/discordjs/discord-api-types/main/website/static/svgs/logo_long_blurple.svg)](https://github.com/discordjs/discord-api-types) - -[![GitHub](https://img.shields.io/github/license/discordjs/discord-api-types)](https://github.com/discordjs/discord-api-types/blob/main/LICENSE.md) -[![npm](https://img.shields.io/npm/v/discord-api-types?color=crimson&logo=npm)](https://www.npmjs.com/package/discord-api-types) -[![deno](https://img.shields.io/npm/v/discord-api-types?color=blue&label=deno&logo=deno)](https://deno.land/x/discord_api_types) -[![Patreon Donate](https://img.shields.io/badge/patreon-donate-brightgreen.svg?label=Donate%20with%20Patreon&logo=patreon&colorB=F96854&link=https://www.patreon.com/vladfrangu)](https://www.patreon.com/vladfrangu) -[![Ko-fi Donate](https://img.shields.io/badge/kofi-donate-brightgreen.svg?label=Donate%20with%20Ko-fi&logo=ko-fi&colorB=F16061&link=https://ko-fi.com/wolfgalvlad&logoColor=FFFFFF)](https://ko-fi.com/wolfgalvlad) -[![GitHub Sponsors](https://img.shields.io/badge/patreon-donate-brightgreen.svg?label=Sponsor%20through%20GitHub&logo=github&colorB=F96854&link=https://github.com/sponsors/vladfrangu)](https://github.com/sponsors/vladfrangu) -[![Powered by Vercel](https://raw.githubusercontent.com/discordjs/discord-api-types/main/website/static/powered-by-vercel.svg)](https://vercel.com?utm_source=discordjs&utm_campaign=oss) - -Simple type definitions for the [Discord API](https://discord.com/developers/docs/intro). - -## Installation - -Install with [npm](https://www.npmjs.com/) / [yarn](https://yarnpkg.com) / [pnpm](https://pnpm.js.org/): - -```sh -npm install discord-api-types -yarn add discord-api-types -pnpm add discord-api-types -``` - -### Usage - -You can only import this module by specifying the API version you want to target. Append `/v*` to the import path, where the `*` represents the API version. Below are some examples - -```js -const { APIUser } = require('discord-api-types/v10'); -``` - -```ts -// TypeScript/ES Module support -import { APIUser } from 'discord-api-types/v10'; -``` - -You may also import just certain parts of the module that you need. The possible values are: `globals`, `gateway`, `gateway/v*`, `payloads`, `payloads/v*`, `rest`, `rest/v*`, `rpc`, `rpc/v*`, `utils`, `utils/v*`, `voice`, and `voice/v*`. Below are some examples - -```js -const { GatewayVersion } = require('discord-api-types/gateway/v10'); -``` - -```ts -// TypeScript/ES Module support -import { GatewayVersion } from 'discord-api-types/gateway/v10'; -``` - -> _**Note:** The `v*` exports (`discord-api-types/v*`) include the appropriate version of `gateway`, `payloads`, `rest`, `rpc`, and `utils` you specified, alongside the `globals` exports_ - -### Deno - -We also provide typings compatible with the [deno](https://deno.land/) runtime. You have 3 ways you can import them: - -1. Directly from GitHub - -```ts -// Importing a specific API version -import { APIUser } from 'https://raw.githubusercontent.com/discordjs/discord-api-types/main/deno/v10.ts'; -``` - -2. From [deno.land/x](https://deno.land/x) - -```ts -// Importing a specific API version -import { APIUser } from 'https://deno.land/x/discord_api_types/v10.ts'; -``` - -3. From [skypack.dev](https://www.skypack.dev/) - -```ts -// Importing a specific API version -import { APIUser } from 'https://cdn.skypack.dev/discord-api-types/v10?dts'; -``` - -## Project Structure - -The exports of each API version is split into three main parts: - -- Everything exported with the `API` prefix represents a payload you may get from the REST API _or_ the Gateway. - -- Everything exported with the `Gateway` prefix represents data that ONLY comes from or is directly related to the Gateway. - -- Everything exported with the `REST` prefix represents data that ONLY comes from or is directly related to the REST API. - - - For endpoint options, they will follow the following structure: `REST` where the type represents what it will return. - - - For example, `RESTPostAPIChannelMessageJSONBody` or `RESTGetAPIGatewayBotInfoResult`. - - - Some exported types (specifically OAuth2 related ones) may not respect this entire structure due to the nature of the fields. They will start with either `RESTOAuth2` or with something similar to `RESTOAuth2` - - - If a type ends with `Result`, then it represents the expected result by calling its accompanying route. - - - Types that are exported as `never` usually mean the result will be a `204 No Content`, so you can safely ignore it. This does **not** account for errors. - -- Anything else that is miscellaneous will be exported based on what it represents (for example the `REST` route object). - -- There may be types exported that are identical for all versions. These will be exported as is and can be found in the `globals` file. They will still be prefixed accordingly as described above. - -**A note about how types are documented**: This package will add types only for known and documented properties that are present in Discord's [API Documentation repository](https://github.com/discord/discord-api-docs), -that are mentioned in an open pull request, or known through other means _and have received the green light to be used_. -Anything else will not be documented (for example client only types). - -With that aside, we may allow certain types that are not documented in the [API Documentation repository](https://github.com/discord/discord-api-docs) on a case by case basis. -They will be documented with an `@unstable` tag and are not subject with the same versioning rules. diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/common.d.ts b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/common.d.ts deleted file mode 100644 index d8bcf32..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/common.d.ts +++ /dev/null @@ -1,9 +0,0 @@ -/** - * https://discord.com/developers/docs/topics/gateway#connecting-gateway-url-params - */ -export interface GatewayURLQuery { - v: string; - encoding: 'json' | 'etf'; - compress?: 'zlib-stream'; -} -//# sourceMappingURL=common.d.ts.map \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/common.d.ts.map b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/common.d.ts.map deleted file mode 100644 index 59c2f60..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/common.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"common.d.ts","sourceRoot":"","sources":["common.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,WAAW,eAAe;IAC/B,CAAC,EAAE,MAAM,CAAC;IACV,QAAQ,EAAE,MAAM,GAAG,KAAK,CAAC;IACzB,QAAQ,CAAC,EAAE,aAAa,CAAC;CACzB"} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/common.js b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/common.js deleted file mode 100644 index 023264f..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/common.js +++ /dev/null @@ -1,3 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/common.js.map b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/common.js.map deleted file mode 100644 index d0f541d..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/common.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"common.js","sourceRoot":"","sources":["common.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/index.d.ts b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/index.d.ts deleted file mode 100644 index 73b8353..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/index.d.ts +++ /dev/null @@ -1,2 +0,0 @@ -export * from './v10'; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/index.d.ts.map b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/index.d.ts.map deleted file mode 100644 index ff50635..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAGA,cAAc,OAAO,CAAC"} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/index.js b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/index.js deleted file mode 100644 index cdf95e3..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/index.js +++ /dev/null @@ -1,20 +0,0 @@ -"use strict"; -// This file exports all the types available in the recommended gateway version -// Thereby, things MAY break in the future. Try sticking to imports from a specific version -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -__exportStar(require("./v10"), exports); -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/index.js.map b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/index.js.map deleted file mode 100644 index d432448..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";AAAA,+EAA+E;AAC/E,2FAA2F;;;;;;;;;;;;;;;;AAE3F,wCAAsB"} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/index.mjs b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/index.mjs deleted file mode 100644 index fd4ff25..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/index.mjs +++ /dev/null @@ -1,8 +0,0 @@ -import mod from "./index.js"; - -export default mod; -export const GatewayCloseCodes = mod.GatewayCloseCodes; -export const GatewayDispatchEvents = mod.GatewayDispatchEvents; -export const GatewayIntentBits = mod.GatewayIntentBits; -export const GatewayOpcodes = mod.GatewayOpcodes; -export const GatewayVersion = mod.GatewayVersion; diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v10.d.ts b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v10.d.ts deleted file mode 100644 index 310b184..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v10.d.ts +++ /dev/null @@ -1,1471 +0,0 @@ -/** - * Types extracted from https://discord.com/developers/docs/topics/gateway - */ -import type { Snowflake } from '../globals'; -import type { GatewayPresenceUpdate } from '../payloads/v10/gateway'; -import type { APIApplication, APIChannel, APIEmoji, APIGuild, APIGuildIntegration, APIGuildMember, APIGuildScheduledEvent, APIInteraction, APIMessage, APIRole, APIStageInstance, APISticker, APIThreadChannel, APIThreadMember, APIUnavailableGuild, APIUser, GatewayActivity, GatewayPresenceUpdate as RawGatewayPresenceUpdate, GatewayThreadListSync as RawGatewayThreadListSync, GatewayThreadMembersUpdate as RawGatewayThreadMembersUpdate, GatewayVoiceState, InviteTargetType, PresenceUpdateStatus } from '../payloads/v10/index'; -import type { Nullable } from '../utils/internals'; -export * from './common'; -export declare const GatewayVersion = "10"; -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-opcodes - */ -export declare enum GatewayOpcodes { - /** - * An event was dispatched - */ - Dispatch = 0, - /** - * A bidirectional opcode to maintain an active gateway connection. - * Fired periodically by the client, or fired by the gateway to request an immediate heartbeat from the client. - */ - Heartbeat = 1, - /** - * Starts a new session during the initial handshake - */ - Identify = 2, - /** - * Update the client's presence - */ - PresenceUpdate = 3, - /** - * Used to join/leave or move between voice channels - */ - VoiceStateUpdate = 4, - /** - * Resume a previous session that was disconnected - */ - Resume = 6, - /** - * You should attempt to reconnect and resume immediately - */ - Reconnect = 7, - /** - * Request information about offline guild members in a large guild - */ - RequestGuildMembers = 8, - /** - * The session has been invalidated. You should reconnect and identify/resume accordingly - */ - InvalidSession = 9, - /** - * Sent immediately after connecting, contains the `heartbeat_interval` to use - */ - Hello = 10, - /** - * Sent in response to receiving a heartbeat to acknowledge that it has been received - */ - HeartbeatAck = 11 -} -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-close-event-codes - */ -export declare enum GatewayCloseCodes { - /** - * We're not sure what went wrong. Try reconnecting? - */ - UnknownError = 4000, - /** - * You sent an invalid Gateway opcode or an invalid payload for an opcode. Don't do that! - * - * See https://discord.com/developers/docs/topics/gateway#payloads-and-opcodes - */ - UnknownOpcode = 4001, - /** - * You sent an invalid payload to us. Don't do that! - * - * See https://discord.com/developers/docs/topics/gateway#sending-payloads - */ - DecodeError = 4002, - /** - * You sent us a payload prior to identifying - * - * See https://discord.com/developers/docs/topics/gateway#identify - */ - NotAuthenticated = 4003, - /** - * The account token sent with your identify payload is incorrect - * - * See https://discord.com/developers/docs/topics/gateway#identify - */ - AuthenticationFailed = 4004, - /** - * You sent more than one identify payload. Don't do that! - */ - AlreadyAuthenticated = 4005, - /** - * The sequence sent when resuming the session was invalid. Reconnect and start a new session - * - * See https://discord.com/developers/docs/topics/gateway#resume - */ - InvalidSeq = 4007, - /** - * Woah nelly! You're sending payloads to us too quickly. Slow it down! You will be disconnected on receiving this - */ - RateLimited = 4008, - /** - * Your session timed out. Reconnect and start a new one - */ - SessionTimedOut = 4009, - /** - * You sent us an invalid shard when identifying - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - InvalidShard = 4010, - /** - * The session would have handled too many guilds - you are required to shard your connection in order to connect - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - ShardingRequired = 4011, - /** - * You sent an invalid version for the gateway - */ - InvalidAPIVersion = 4012, - /** - * You sent an invalid intent for a Gateway Intent. You may have incorrectly calculated the bitwise value - * - * See https://discord.com/developers/docs/topics/gateway#gateway-intents - */ - InvalidIntents = 4013, - /** - * You sent a disallowed intent for a Gateway Intent. You may have tried to specify an intent that you have not - * enabled or are not whitelisted for - * - * See https://discord.com/developers/docs/topics/gateway#gateway-intents - * - * See https://discord.com/developers/docs/topics/gateway#privileged-intents - */ - DisallowedIntents = 4014 -} -/** - * https://discord.com/developers/docs/topics/gateway#list-of-intents - */ -export declare enum GatewayIntentBits { - Guilds = 1, - GuildMembers = 2, - GuildBans = 4, - GuildEmojisAndStickers = 8, - GuildIntegrations = 16, - GuildWebhooks = 32, - GuildInvites = 64, - GuildVoiceStates = 128, - GuildPresences = 256, - GuildMessages = 512, - GuildMessageReactions = 1024, - GuildMessageTyping = 2048, - DirectMessages = 4096, - DirectMessageReactions = 8192, - DirectMessageTyping = 16384, - MessageContent = 32768, - GuildScheduledEvents = 65536 -} -/** - * https://discord.com/developers/docs/topics/gateway#commands-and-events-gateway-events - */ -export declare enum GatewayDispatchEvents { - ApplicationCommandPermissionsUpdate = "APPLICATION_COMMAND_PERMISSIONS_UPDATE", - ChannelCreate = "CHANNEL_CREATE", - ChannelDelete = "CHANNEL_DELETE", - ChannelPinsUpdate = "CHANNEL_PINS_UPDATE", - ChannelUpdate = "CHANNEL_UPDATE", - GuildBanAdd = "GUILD_BAN_ADD", - GuildBanRemove = "GUILD_BAN_REMOVE", - GuildCreate = "GUILD_CREATE", - GuildDelete = "GUILD_DELETE", - GuildEmojisUpdate = "GUILD_EMOJIS_UPDATE", - GuildIntegrationsUpdate = "GUILD_INTEGRATIONS_UPDATE", - GuildMemberAdd = "GUILD_MEMBER_ADD", - GuildMemberRemove = "GUILD_MEMBER_REMOVE", - GuildMembersChunk = "GUILD_MEMBERS_CHUNK", - GuildMemberUpdate = "GUILD_MEMBER_UPDATE", - GuildRoleCreate = "GUILD_ROLE_CREATE", - GuildRoleDelete = "GUILD_ROLE_DELETE", - GuildRoleUpdate = "GUILD_ROLE_UPDATE", - GuildStickersUpdate = "GUILD_STICKERS_UPDATE", - GuildUpdate = "GUILD_UPDATE", - IntegrationCreate = "INTEGRATION_CREATE", - IntegrationDelete = "INTEGRATION_DELETE", - IntegrationUpdate = "INTEGRATION_UPDATE", - InteractionCreate = "INTERACTION_CREATE", - InviteCreate = "INVITE_CREATE", - InviteDelete = "INVITE_DELETE", - MessageCreate = "MESSAGE_CREATE", - MessageDelete = "MESSAGE_DELETE", - MessageDeleteBulk = "MESSAGE_DELETE_BULK", - MessageReactionAdd = "MESSAGE_REACTION_ADD", - MessageReactionRemove = "MESSAGE_REACTION_REMOVE", - MessageReactionRemoveAll = "MESSAGE_REACTION_REMOVE_ALL", - MessageReactionRemoveEmoji = "MESSAGE_REACTION_REMOVE_EMOJI", - MessageUpdate = "MESSAGE_UPDATE", - PresenceUpdate = "PRESENCE_UPDATE", - StageInstanceCreate = "STAGE_INSTANCE_CREATE", - StageInstanceDelete = "STAGE_INSTANCE_DELETE", - StageInstanceUpdate = "STAGE_INSTANCE_UPDATE", - Ready = "READY", - Resumed = "RESUMED", - ThreadCreate = "THREAD_CREATE", - ThreadDelete = "THREAD_DELETE", - ThreadListSync = "THREAD_LIST_SYNC", - ThreadMembersUpdate = "THREAD_MEMBERS_UPDATE", - ThreadMemberUpdate = "THREAD_MEMBER_UPDATE", - ThreadUpdate = "THREAD_UPDATE", - TypingStart = "TYPING_START", - UserUpdate = "USER_UPDATE", - VoiceServerUpdate = "VOICE_SERVER_UPDATE", - VoiceStateUpdate = "VOICE_STATE_UPDATE", - WebhooksUpdate = "WEBHOOKS_UPDATE", - GuildScheduledEventCreate = "GUILD_SCHEDULED_EVENT_CREATE", - GuildScheduledEventUpdate = "GUILD_SCHEDULED_EVENT_UPDATE", - GuildScheduledEventDelete = "GUILD_SCHEDULED_EVENT_DELETE", - GuildScheduledEventUserAdd = "GUILD_SCHEDULED_EVENT_USER_ADD", - GuildScheduledEventUserRemove = "GUILD_SCHEDULED_EVENT_USER_REMOVE" -} -export declare type GatewaySendPayload = GatewayHeartbeat | GatewayIdentify | GatewayUpdatePresence | GatewayVoiceStateUpdate | GatewayResume | GatewayRequestGuildMembers; -export declare type GatewayReceivePayload = GatewayHello | GatewayHeartbeatRequest | GatewayHeartbeatAck | GatewayInvalidSession | GatewayReconnect | GatewayDispatchPayload; -export declare type GatewayDispatchPayload = GatewayChannelModifyDispatch | GatewayChannelPinsUpdateDispatch | GatewayGuildBanModifyDispatch | GatewayGuildCreateDispatch | GatewayGuildDeleteDispatch | GatewayGuildEmojisUpdateDispatch | GatewayGuildIntegrationsUpdateDispatch | GatewayGuildMemberAddDispatch | GatewayGuildMemberRemoveDispatch | GatewayGuildMembersChunkDispatch | GatewayGuildMemberUpdateDispatch | GatewayGuildModifyDispatch | GatewayGuildRoleDeleteDispatch | GatewayGuildRoleModifyDispatch | GatewayGuildScheduledEventCreateDispatch | GatewayGuildScheduledEventUpdateDispatch | GatewayGuildScheduledEventDeleteDispatch | GatewayGuildScheduledEventUserAddDispatch | GatewayGuildScheduledEventUserRemoveDispatch | GatewayGuildStickersUpdateDispatch | GatewayIntegrationCreateDispatch | GatewayIntegrationDeleteDispatch | GatewayIntegrationUpdateDispatch | GatewayInteractionCreateDispatch | GatewayInviteCreateDispatch | GatewayInviteDeleteDispatch | GatewayMessageCreateDispatch | GatewayMessageDeleteBulkDispatch | GatewayMessageDeleteDispatch | GatewayMessageReactionAddDispatch | GatewayMessageReactionRemoveAllDispatch | GatewayMessageReactionRemoveDispatch | GatewayMessageReactionRemoveEmojiDispatch | GatewayMessageUpdateDispatch | GatewayPresenceUpdateDispatch | GatewayStageInstanceCreateDispatch | GatewayStageInstanceDeleteDispatch | GatewayStageInstanceUpdateDispatch | GatewayReadyDispatch | GatewayResumedDispatch | GatewayThreadListSyncDispatch | GatewayThreadMembersUpdateDispatch | GatewayThreadMemberUpdateDispatch | GatewayThreadModifyDispatch | GatewayTypingStartDispatch | GatewayUserUpdateDispatch | GatewayVoiceServerUpdateDispatch | GatewayVoiceStateUpdateDispatch | GatewayWebhooksUpdateDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#hello - */ -export interface GatewayHello extends NonDispatchPayload { - op: GatewayOpcodes.Hello; - d: GatewayHelloData; -} -/** - * https://discord.com/developers/docs/topics/gateway#hello - */ -export interface GatewayHelloData { - /** - * The interval (in milliseconds) the client should heartbeat with - */ - heartbeat_interval: number; -} -/** - * https://discord.com/developers/docs/topics/gateway#heartbeating - */ -export interface GatewayHeartbeatRequest extends NonDispatchPayload { - op: GatewayOpcodes.Heartbeat; - d: never; -} -/** - * https://discord.com/developers/docs/topics/gateway#heartbeating-example-gateway-heartbeat-ack - */ -export interface GatewayHeartbeatAck extends NonDispatchPayload { - op: GatewayOpcodes.HeartbeatAck; - d: never; -} -/** - * https://discord.com/developers/docs/topics/gateway#invalid-session - */ -export interface GatewayInvalidSession extends NonDispatchPayload { - op: GatewayOpcodes.InvalidSession; - d: GatewayInvalidSessionData; -} -/** - * https://discord.com/developers/docs/topics/gateway#invalid-session - */ -export declare type GatewayInvalidSessionData = boolean; -/** - * https://discord.com/developers/docs/topics/gateway#reconnect - */ -export interface GatewayReconnect extends NonDispatchPayload { - op: GatewayOpcodes.Reconnect; - d: never; -} -/** - * https://discord.com/developers/docs/topics/gateway#ready - */ -export declare type GatewayReadyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#ready - */ -export interface GatewayReadyDispatchData { - /** - * Gateway version - * - * See https://discord.com/developers/docs/topics/gateway#gateways-gateway-versions - */ - v: number; - /** - * Information about the user including email - * - * See https://discord.com/developers/docs/resources/user#user-object - */ - user: APIUser; - /** - * The guilds the user is in - * - * See https://discord.com/developers/docs/resources/guild#unavailable-guild-object - */ - guilds: APIUnavailableGuild[]; - /** - * Used for resuming connections - */ - session_id: string; - /** - * The shard information associated with this session, if sent when identifying - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - shard?: [shard_id: number, shard_count: number]; - /** - * Contains `id` and `flags` - * - * See https://discord.com/developers/docs/resources/application#application-object - */ - application: Pick; -} -/** - * https://discord.com/developers/docs/topics/gateway#resumed - */ -export declare type GatewayResumedDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#channel-create - * https://discord.com/developers/docs/topics/gateway#channel-update - * https://discord.com/developers/docs/topics/gateway#channel-delete - */ -export declare type GatewayChannelModifyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#channel-create - * https://discord.com/developers/docs/topics/gateway#channel-update - * https://discord.com/developers/docs/topics/gateway#channel-delete - */ -export declare type GatewayChannelModifyDispatchData = APIChannel; -/** - * https://discord.com/developers/docs/topics/gateway#channel-create - */ -export declare type GatewayChannelCreateDispatch = GatewayChannelModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#channel-create - */ -export declare type GatewayChannelCreateDispatchData = GatewayChannelModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#channel-update - */ -export declare type GatewayChannelUpdateDispatch = GatewayChannelModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#channel-update - */ -export declare type GatewayChannelUpdateDispatchData = GatewayChannelModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#channel-delete - */ -export declare type GatewayChannelDeleteDispatch = GatewayChannelModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#channel-delete - */ -export declare type GatewayChannelDeleteDispatchData = GatewayChannelModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#channel-pins-update - */ -export declare type GatewayChannelPinsUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#channel-pins-update - */ -export interface GatewayChannelPinsUpdateDispatchData { - /** - * The id of the guild - */ - guild_id?: Snowflake; - /** - * The id of the channel - */ - channel_id: Snowflake; - /** - * The time at which the most recent pinned message was pinned - */ - last_pin_timestamp?: string | null; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-create - */ -export declare type GatewayGuildModifyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-update - */ -export declare type GatewayGuildModifyDispatchData = APIGuild; -/** - * https://discord.com/developers/docs/topics/gateway#guild-create - */ -export declare type GatewayGuildCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-create - * https://discord.com/developers/docs/topics/gateway#guild-create-guild-create-extra-fields - */ -export interface GatewayGuildCreateDispatchData extends APIGuild { - /** - * When this guild was joined at - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - */ - joined_at: string; - /** - * `true` if this is considered a large guild - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - */ - large: boolean; - /** - * `true` if this guild is unavailable due to an outage - */ - unavailable?: boolean; - /** - * Total number of members in this guild - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - */ - member_count: number; - /** - * States of members currently in voice channels; lacks the `guild_id` key - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - * - * See https://discord.com/developers/docs/resources/voice#voice-state-object - */ - voice_states: Omit[]; - /** - * Users in the guild - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - * - * See https://discord.com/developers/docs/resources/guild#guild-member-object - */ - members: APIGuildMember[]; - /** - * Channels in the guild - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - * - * See https://discord.com/developers/docs/resources/channel#channel-object - */ - channels: APIChannel[]; - /** - * Threads in the guild - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - * - * See https://discord.com/developers/docs/resources/channel#channel-object - */ - threads: APIChannel[]; - /** - * Presences of the members in the guild, will only include non-offline members if the size is greater than `large_threshold` - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - * - * See https://discord.com/developers/docs/topics/gateway#presence-update - */ - presences: GatewayPresenceUpdate[]; - /** - * The stage instances in the guild - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - * - * See https://discord.com/developers/docs/resources/stage-instance#stage-instance-object-stage-instance-structure - */ - stage_instances: APIStageInstance[]; - /** - * The scheduled events in the guild - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - * - * https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object - */ - guild_scheduled_events: APIGuildScheduledEvent[]; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-update - */ -export declare type GatewayGuildUpdateDispatch = GatewayGuildModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-update - */ -export declare type GatewayGuildUpdateDispatchData = GatewayGuildModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#guild-delete - */ -export declare type GatewayGuildDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-delete - */ -export declare type GatewayGuildDeleteDispatchData = APIUnavailableGuild; -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-add - * https://discord.com/developers/docs/topics/gateway#guild-ban-remove - */ -export declare type GatewayGuildBanModifyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-add - * https://discord.com/developers/docs/topics/gateway#guild-ban-remove - */ -export interface GatewayGuildBanModifyDispatchData { - /** - * ID of the guild - */ - guild_id: Snowflake; - /** - * The banned user - * - * See https://discord.com/developers/docs/resources/user#user-object - */ - user: APIUser; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-add - */ -export declare type GatewayGuildBanAddDispatch = GatewayGuildBanModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-add - */ -export declare type GatewayGuildBanAddDispatchData = GatewayGuildBanModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-remove - */ -export declare type GatewayGuildBanRemoveDispatch = GatewayGuildBanModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-remove - */ -export declare type GatewayGuildBanRemoveDispatchData = GatewayGuildBanModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#guild-emojis-update - */ -export declare type GatewayGuildEmojisUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-emojis-update - */ -export interface GatewayGuildEmojisUpdateDispatchData { - /** - * ID of the guild - */ - guild_id: Snowflake; - /** - * Array of emojis - * - * See https://discord.com/developers/docs/resources/emoji#emoji-object - */ - emojis: APIEmoji[]; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-stickers-update - */ -export declare type GatewayGuildStickersUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-stickers-update - */ -export interface GatewayGuildStickersUpdateDispatchData { - /** - * ID of the guild - */ - guild_id: Snowflake; - /** - * Array of stickers - * - * See https://discord.com/developers/docs/resources/sticker#sticker-object - */ - stickers: APISticker[]; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-integrations-update - */ -export declare type GatewayGuildIntegrationsUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-integrations-update - */ -export interface GatewayGuildIntegrationsUpdateDispatchData { - /** - * ID of the guild whose integrations were updated - */ - guild_id: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-add - */ -export declare type GatewayGuildMemberAddDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-add - */ -export interface GatewayGuildMemberAddDispatchData extends APIGuildMember { - /** - * The id of the guild - */ - guild_id: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-remove - */ -export declare type GatewayGuildMemberRemoveDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-remove - */ -export interface GatewayGuildMemberRemoveDispatchData { - /** - * The id of the guild - */ - guild_id: Snowflake; - /** - * The user who was removed - * - * See https://discord.com/developers/docs/resources/user#user-object - */ - user: APIUser; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-update - */ -export declare type GatewayGuildMemberUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-update - */ -export declare type GatewayGuildMemberUpdateDispatchData = Omit & Partial> & Required> & Nullable> & { - /** - * The id of the guild - */ - guild_id: Snowflake; -}; -/** - * https://discord.com/developers/docs/topics/gateway#guild-members-chunk - */ -export declare type GatewayGuildMembersChunkDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-members-chunk - */ -export interface GatewayGuildMembersChunkDispatchData { - /** - * The id of the guild - */ - guild_id: Snowflake; - /** - * Set of guild members - * - * See https://discord.com/developers/docs/resources/guild#guild-member-object - */ - members: APIGuildMember[]; - /** - * The chunk index in the expected chunks for this response (`0 <= chunk_index < chunk_count`) - */ - chunk_index?: number; - /** - * The total number of expected chunks for this response - */ - chunk_count?: number; - /** - * If passing an invalid id to `REQUEST_GUILD_MEMBERS`, it will be returned here - */ - not_found?: unknown[]; - /** - * If passing true to `REQUEST_GUILD_MEMBERS`, presences of the returned members will be here - * - * See https://discord.com/developers/docs/topics/gateway#presence - */ - presences?: RawGatewayPresenceUpdate[]; - /** - * The nonce used in the Guild Members Request - * - * See https://discord.com/developers/docs/topics/gateway#request-guild-members - */ - nonce?: string; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-create - * https://discord.com/developers/docs/topics/gateway#guild-role-update - */ -export declare type GatewayGuildRoleModifyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-create - * https://discord.com/developers/docs/topics/gateway#guild-role-update - */ -export interface GatewayGuildRoleModifyDispatchData { - /** - * The id of the guild - */ - guild_id: Snowflake; - /** - * The role created or updated - * - * See https://discord.com/developers/docs/topics/permissions#role-object - */ - role: APIRole; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-create - */ -export declare type GatewayGuildRoleCreateDispatch = GatewayGuildRoleModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-create - */ -export declare type GatewayGuildRoleCreateDispatchData = GatewayGuildRoleModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-update - */ -export declare type GatewayGuildRoleUpdateDispatch = GatewayGuildRoleModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-update - */ -export declare type GatewayGuildRoleUpdateDispatchData = GatewayGuildRoleModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-delete - */ -export declare type GatewayGuildRoleDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-delete - */ -export interface GatewayGuildRoleDeleteDispatchData { - /** - * The id of the guild - */ - guild_id: Snowflake; - /** - * The id of the role - */ - role_id: Snowflake; -} -export declare type GatewayGuildScheduledEventCreateDispatch = DataPayload; -export declare type GatewayGuildScheduledEventCreateDispatchData = APIGuildScheduledEvent; -export declare type GatewayGuildScheduledEventUpdateDispatch = DataPayload; -export declare type GatewayGuildScheduledEventUpdateDispatchData = APIGuildScheduledEvent; -export declare type GatewayGuildScheduledEventDeleteDispatch = DataPayload; -export declare type GatewayGuildScheduledEventDeleteDispatchData = APIGuildScheduledEvent; -export declare type GatewayGuildScheduledEventUserAddDispatch = DataPayload; -export interface GatewayGuildScheduledEventUserAddDispatchData { - guild_scheduled_event_id: Snowflake; - user_id: Snowflake; - guild_id: Snowflake; -} -export declare type GatewayGuildScheduledEventUserRemoveDispatch = DataPayload; -export interface GatewayGuildScheduledEventUserRemoveDispatchData { - guild_scheduled_event_id: Snowflake; - user_id: Snowflake; - guild_id: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#integration-create - */ -export declare type GatewayIntegrationCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#integration-create - */ -export declare type GatewayIntegrationCreateDispatchData = APIGuildIntegration & { - guild_id: Snowflake; -}; -/** - * https://discord.com/developers/docs/topics/gateway#integration-update - */ -export declare type GatewayIntegrationUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#integration-update - */ -export declare type GatewayIntegrationUpdateDispatchData = APIGuildIntegration & { - guild_id: Snowflake; -}; -/** - * https://discord.com/developers/docs/topics/gateway#integration-update - */ -export declare type GatewayIntegrationDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#integration-delete - */ -export interface GatewayIntegrationDeleteDispatchData { - /** - * Integration id - */ - id: Snowflake; - /** - * ID of the guild - */ - guild_id: Snowflake; - /** - * ID of the bot/OAuth2 application for this Discord integration - */ - application_id?: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#interaction-create - */ -export declare type GatewayInteractionCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#interaction-create - */ -export declare type GatewayInteractionCreateDispatchData = APIInteraction; -/** - * https://discord.com/developers/docs/topics/gateway#invite-create - */ -export declare type GatewayInviteCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#invite-create - */ -export interface GatewayInviteCreateDispatchData { - /** - * The channel the invite is for - */ - channel_id: Snowflake; - /** - * The unique invite code - * - * See https://discord.com/developers/docs/resources/invite#invite-object - */ - code: string; - /** - * The time at which the invite was created - */ - created_at: number; - /** - * The guild of the invite - */ - guild_id?: Snowflake; - /** - * The user that created the invite - * - * See https://discord.com/developers/docs/resources/user#user-object - */ - inviter?: APIUser; - /** - * How long the invite is valid for (in seconds) - */ - max_age: number; - /** - * The maximum number of times the invite can be used - */ - max_uses: number; - /** - * The type of target for this voice channel invite - * - * See https://discord.com/developers/docs/resources/invite#invite-object-invite-target-types - */ - target_type?: InviteTargetType; - /** - * The user whose stream to display for this voice channel stream invite - * - * See https://discord.com/developers/docs/resources/user#user-object - */ - target_user?: APIUser; - /** - * The embedded application to open for this voice channel embedded application invite - */ - target_application?: Partial; - /** - * Whether or not the invite is temporary (invited users will be kicked on disconnect unless they're assigned a role) - */ - temporary: boolean; - /** - * How many times the invite has been used (always will be `0`) - */ - uses: 0; -} -/** - * https://discord.com/developers/docs/topics/gateway#invite-delete - */ -export declare type GatewayInviteDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#invite-delete - */ -export interface GatewayInviteDeleteDispatchData { - /** - * The channel of the invite - */ - channel_id: Snowflake; - /** - * The guild of the invite - */ - guild_id?: Snowflake; - /** - * The unique invite code - * - * See https://discord.com/developers/docs/resources/invite#invite-object - */ - code: string; -} -/** - * https://discord.com/developers/docs/topics/gateway#message-create - */ -export declare type GatewayMessageCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-create - */ -export declare type GatewayMessageCreateDispatchData = Omit & GatewayMessageEventExtraFields; -/** - * https://discord.com/developers/docs/topics/gateway#message-update - */ -export declare type GatewayMessageUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-update - */ -export declare type GatewayMessageUpdateDispatchData = Omit, 'mentions'> & GatewayMessageEventExtraFields & { - /** - * ID of the message - */ - id: Snowflake; - /** - * ID of the channel the message was sent in - */ - channel_id: Snowflake; -}; -export interface GatewayMessageEventExtraFields { - /** - * ID of the guild the message was sent in - */ - guild_id?: Snowflake; - /** - * Member properties for this message's author - * - * The member object exists in `MESSAGE_CREATE` and `MESSAGE_UPDATE` events - * from text-based guild channels - * - * See https://discord.com/developers/docs/resources/guild#guild-member-object - */ - member?: APIGuildMember; - /** - * Users specifically mentioned in the message - * - * The `member` field is only present in `MESSAGE_CREATE` and `MESSAGE_UPDATE` events - * from text-based guild channels - * - * See https://discord.com/developers/docs/resources/user#user-object - * See https://discord.com/developers/docs/resources/guild#guild-member-object - */ - mentions: (APIUser & { - member?: Omit; - })[]; -} -/** - * https://discord.com/developers/docs/topics/gateway#message-delete - */ -export declare type GatewayMessageDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-delete - */ -export interface GatewayMessageDeleteDispatchData { - /** - * The id of the message - */ - id: Snowflake; - /** - * The id of the channel - */ - channel_id: Snowflake; - /** - * The id of the guild - */ - guild_id?: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#message-delete-bulk - */ -export declare type GatewayMessageDeleteBulkDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-delete-bulk - */ -export interface GatewayMessageDeleteBulkDispatchData { - /** - * The ids of the messages - */ - ids: Snowflake[]; - /** - * The id of the channel - */ - channel_id: Snowflake; - /** - * The id of the guild - */ - guild_id?: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-add - */ -export declare type GatewayMessageReactionAddDispatch = ReactionData; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-add - */ -export declare type GatewayMessageReactionAddDispatchData = GatewayMessageReactionAddDispatch['d']; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove - */ -export declare type GatewayMessageReactionRemoveDispatch = ReactionData; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove - */ -export declare type GatewayMessageReactionRemoveDispatchData = GatewayMessageReactionRemoveDispatch['d']; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-all - */ -export declare type GatewayMessageReactionRemoveAllDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-all - */ -export declare type GatewayMessageReactionRemoveAllDispatchData = MessageReactionRemoveData; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-emoji - */ -export declare type GatewayMessageReactionRemoveEmojiDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-emoji - */ -export interface GatewayMessageReactionRemoveEmojiDispatchData extends MessageReactionRemoveData { - /** - * The emoji that was removed - */ - emoji: APIEmoji; -} -/** - * https://discord.com/developers/docs/topics/gateway#presence-update - */ -export declare type GatewayPresenceUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#presence-update - */ -export declare type GatewayPresenceUpdateDispatchData = RawGatewayPresenceUpdate; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-create - */ -export declare type GatewayStageInstanceCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-create - */ -export declare type GatewayStageInstanceCreateDispatchData = APIStageInstance; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-delete - */ -export declare type GatewayStageInstanceDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-delete - */ -export declare type GatewayStageInstanceDeleteDispatchData = APIStageInstance; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-update - */ -export declare type GatewayStageInstanceUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-update - */ -export declare type GatewayStageInstanceUpdateDispatchData = APIStageInstance; -/** - * https://discord.com/developers/docs/topics/gateway#thread-list-sync - */ -export declare type GatewayThreadListSyncDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#thread-list-sync - */ -export declare type GatewayThreadListSyncDispatchData = RawGatewayThreadListSync; -/** - * https://discord.com/developers/docs/topics/gateway#thread-members-update - */ -export declare type GatewayThreadMembersUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#thread-members-update - */ -export declare type GatewayThreadMembersUpdateDispatchData = RawGatewayThreadMembersUpdate; -/** - * https://discord.com/developers/docs/topics/gateway#thread-member-update - */ -export declare type GatewayThreadMemberUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#thread-member-update - */ -export declare type GatewayThreadMemberUpdateDispatchData = APIThreadMember & { - guild_id: Snowflake; -}; -/** - * https://discord.com/developers/docs/topics/gateway#thread-create - * https://discord.com/developers/docs/topics/gateway#thread-update - * https://discord.com/developers/docs/topics/gateway#thread-delete - */ -export declare type GatewayThreadModifyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#thread-create - */ -export declare type GatewayThreadCreateDispatch = GatewayChannelModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#thread-create - */ -export interface GatewayThreadCreateDispatchData extends APIThreadChannel { - /** - * Whether the thread is newly created or not. - */ - newly_created?: true; -} -/** - * https://discord.com/developers/docs/topics/gateway#thread-update - */ -export declare type GatewayThreadUpdateDispatch = GatewayChannelModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#thread-update - */ -export declare type GatewayThreadUpdateDispatchData = GatewayChannelModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#thread-delete - */ -export declare type GatewayThreadDeleteDispatch = GatewayChannelModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#thread-delete - */ -export declare type GatewayThreadDeleteDispatchData = GatewayChannelModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#typing-start - */ -export declare type GatewayTypingStartDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#typing-start - */ -export interface GatewayTypingStartDispatchData { - /** - * The id of the channel - */ - channel_id: Snowflake; - /** - * The id of the guild - */ - guild_id?: Snowflake; - /** - * The id of the user - */ - user_id: Snowflake; - /** - * Unix time (in seconds) of when the user started typing - */ - timestamp: number; - /** - * The member who started typing if this happened in a guild - * - * See https://discord.com/developers/docs/resources/guild#guild-member-object - */ - member?: APIGuildMember; -} -/** - * https://discord.com/developers/docs/topics/gateway#user-update - */ -export declare type GatewayUserUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#user-update - */ -export declare type GatewayUserUpdateDispatchData = APIUser; -/** - * https://discord.com/developers/docs/topics/gateway#voice-state-update - */ -export declare type GatewayVoiceStateUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#voice-state-update - */ -export declare type GatewayVoiceStateUpdateDispatchData = GatewayVoiceState; -/** - * https://discord.com/developers/docs/topics/gateway#voice-server-update - */ -export declare type GatewayVoiceServerUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#voice-server-update - */ -export interface GatewayVoiceServerUpdateDispatchData { - /** - * Voice connection token - */ - token: string; - /** - * The guild this voice server update is for - */ - guild_id: Snowflake; - /** - * The voice server host - * - * A `null` endpoint means that the voice server allocated has gone away and is trying to be reallocated. - * You should attempt to disconnect from the currently connected voice server, and not attempt to reconnect - * until a new voice server is allocated - */ - endpoint: string | null; -} -/** - * https://discord.com/developers/docs/topics/gateway#webhooks-update - */ -export declare type GatewayWebhooksUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#webhooks-update - */ -export interface GatewayWebhooksUpdateDispatchData { - /** - * The id of the guild - */ - guild_id: Snowflake; - /** - * The id of the channel - */ - channel_id: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#heartbeating - */ -export interface GatewayHeartbeat { - op: GatewayOpcodes.Heartbeat; - d: GatewayHeartbeatData; -} -/** - * https://discord.com/developers/docs/topics/gateway#heartbeating - */ -export declare type GatewayHeartbeatData = number | null; -/** - * https://discord.com/developers/docs/topics/gateway#identify - */ -export interface GatewayIdentify { - op: GatewayOpcodes.Identify; - d: GatewayIdentifyData; -} -/** - * https://discord.com/developers/docs/topics/gateway#identify - */ -export interface GatewayIdentifyData { - /** - * Authentication token - */ - token: string; - /** - * Connection properties - * - * See https://discord.com/developers/docs/topics/gateway#identify-identify-connection-properties - */ - properties: GatewayIdentifyProperties; - /** - * Whether this connection supports compression of packets - * - * @default false - */ - compress?: boolean; - /** - * Value between 50 and 250, total number of members where the gateway will stop sending - * offline members in the guild member list - * - * @default 50 - */ - large_threshold?: number; - /** - * Used for Guild Sharding - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - shard?: [shard_id: number, shard_count: number]; - /** - * Presence structure for initial presence information - * - * See https://discord.com/developers/docs/topics/gateway#update-presence - */ - presence?: GatewayPresenceUpdateData; - /** - * The Gateway Intents you wish to receive - * - * See https://discord.com/developers/docs/topics/gateway#gateway-intents - */ - intents: number; -} -/** - * https://discord.com/developers/docs/topics/gateway#identify-identify-connection-properties - */ -export interface GatewayIdentifyProperties { - /** - * Your operating system - */ - os: string; - /** - * Your library name - */ - browser: string; - /** - * Your library name - */ - device: string; -} -/** - * https://discord.com/developers/docs/topics/gateway#resume - */ -export interface GatewayResume { - op: GatewayOpcodes.Resume; - d: GatewayResumeData; -} -/** - * https://discord.com/developers/docs/topics/gateway#resume - */ -export interface GatewayResumeData { - /** - * Session token - */ - token: string; - /** - * Session id - */ - session_id: string; - /** - * Last sequence number received - */ - seq: number; -} -/** - * https://discord.com/developers/docs/topics/gateway#request-guild-members - */ -export interface GatewayRequestGuildMembers { - op: GatewayOpcodes.RequestGuildMembers; - d: GatewayRequestGuildMembersData; -} -/** - * https://discord.com/developers/docs/topics/gateway#request-guild-members - */ -export interface GatewayRequestGuildMembersData { - /** - * ID of the guild to get members for - */ - guild_id: Snowflake; - /** - * String that username starts with, or an empty string to return all members - */ - query?: string; - /** - * Maximum number of members to send matching the `query`; - * a limit of `0` can be used with an empty string `query` to return all members - */ - limit: number; - /** - * Used to specify if we want the presences of the matched members - */ - presences?: boolean; - /** - * Used to specify which users you wish to fetch - */ - user_ids?: Snowflake | Snowflake[]; - /** - * Nonce to identify the Guild Members Chunk response - * - * Nonce can only be up to 32 bytes. If you send an invalid nonce it will be ignored and the reply member_chunk(s) will not have a `nonce` set. - * - * See https://discord.com/developers/docs/topics/gateway#guild-members-chunk - */ - nonce?: string; -} -/** - * https://discord.com/developers/docs/topics/gateway#update-voice-state - */ -export interface GatewayVoiceStateUpdate { - op: GatewayOpcodes.VoiceStateUpdate; - d: GatewayVoiceStateUpdateData; -} -/** - * https://discord.com/developers/docs/topics/gateway#update-voice-state - */ -export interface GatewayVoiceStateUpdateData { - /** - * ID of the guild - */ - guild_id: Snowflake; - /** - * ID of the voice channel client wants to join (`null` if disconnecting) - */ - channel_id: Snowflake | null; - /** - * Is the client muted - */ - self_mute: boolean; - /** - * Is the client deafened - */ - self_deaf: boolean; -} -/** - * https://discord.com/developers/docs/topics/gateway#update-status - */ -export interface GatewayUpdatePresence { - op: GatewayOpcodes.PresenceUpdate; - d: GatewayPresenceUpdateData; -} -/** - * https://discord.com/developers/docs/topics/gateway#update-presence-gateway-presence-update-structure - */ -export interface GatewayPresenceUpdateData { - /** - * Unix time (in milliseconds) of when the client went idle, or `null` if the client is not idle - */ - since: number | null; - /** - * The user's activities - * - * See https://discord.com/developers/docs/topics/gateway#activity-object - */ - activities: GatewayActivityUpdateData[]; - /** - * The user's new status - * - * See https://discord.com/developers/docs/topics/gateway#update-presence-status-types - */ - status: PresenceUpdateStatus; - /** - * Whether or not the client is afk - */ - afk: boolean; -} -/** - * https://discord.com/developers/docs/topics/gateway#activity-object-activity-structure - */ -export declare type GatewayActivityUpdateData = Pick; -interface BasePayload { - /** - * Opcode for the payload - */ - op: GatewayOpcodes; - /** - * Event data - */ - d?: unknown; - /** - * Sequence number, used for resuming sessions and heartbeats - */ - s: number; - /** - * The event name for this payload - */ - t?: string; -} -declare type NonDispatchPayload = Omit & { - t: null; - s: null; -}; -interface DataPayload extends BasePayload { - op: GatewayOpcodes.Dispatch; - t: Event; - d: D; -} -declare type ReactionData = DataPayload>; -interface MessageReactionRemoveData { - /** - * The id of the channel - */ - channel_id: Snowflake; - /** - * The id of the message - */ - message_id: Snowflake; - /** - * The id of the guild - */ - guild_id?: Snowflake; -} -//# sourceMappingURL=v10.d.ts.map \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v10.d.ts.map b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v10.d.ts.map deleted file mode 100644 index a741060..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v10.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"v10.d.ts","sourceRoot":"","sources":["v10.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AACrE,OAAO,KAAK,EACX,cAAc,EACd,UAAU,EACV,QAAQ,EACR,QAAQ,EACR,mBAAmB,EACnB,cAAc,EACd,sBAAsB,EACtB,cAAc,EACd,UAAU,EACV,OAAO,EACP,gBAAgB,EAChB,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,mBAAmB,EACnB,OAAO,EACP,eAAe,EACf,qBAAqB,IAAI,wBAAwB,EACjD,qBAAqB,IAAI,wBAAwB,EACjD,0BAA0B,IAAI,6BAA6B,EAC3D,iBAAiB,EACjB,gBAAgB,EAChB,oBAAoB,EACpB,MAAM,uBAAuB,CAAC;AAC/B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAEnD,cAAc,UAAU,CAAC;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EAAE,SAAS,CAAC;IACnB;;OAEG;IACH,UAAU,EAAE,SAAS,CAAC;IACtB;;OAEG;IACH,UAAU,EAAE,SAAS,CAAC;IACtB;;OAEG;IACH,QAAQ,CAAC,EAAE,SAAS,CAAC;IACrB;;;;OAIG;IACH,MAAM,CAAC,EAAE,cAAc,CAAC;IACxB;;;;OAIG;IACH,KAAK,EAAE,QAAQ,CAAC;CAChB,EACD,CAAC,CACD,CACD,CAAC;AAEF,UAAU,yBAAyB;IAClC;;OAEG;IACH,UAAU,EAAE,SAAS,CAAC;IACtB;;OAEG;IACH,UAAU,EAAE,SAAS,CAAC;IACtB;;OAEG;IACH,QAAQ,CAAC,EAAE,SAAS,CAAC;CACrB"} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v10.js b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v10.js deleted file mode 100644 index 94aaefa..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v10.js +++ /dev/null @@ -1,243 +0,0 @@ -"use strict"; -/** - * Types extracted from https://discord.com/developers/docs/topics/gateway - */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GatewayDispatchEvents = exports.GatewayIntentBits = exports.GatewayCloseCodes = exports.GatewayOpcodes = exports.GatewayVersion = void 0; -__exportStar(require("./common"), exports); -exports.GatewayVersion = '10'; -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-opcodes - */ -var GatewayOpcodes; -(function (GatewayOpcodes) { - /** - * An event was dispatched - */ - GatewayOpcodes[GatewayOpcodes["Dispatch"] = 0] = "Dispatch"; - /** - * A bidirectional opcode to maintain an active gateway connection. - * Fired periodically by the client, or fired by the gateway to request an immediate heartbeat from the client. - */ - GatewayOpcodes[GatewayOpcodes["Heartbeat"] = 1] = "Heartbeat"; - /** - * Starts a new session during the initial handshake - */ - GatewayOpcodes[GatewayOpcodes["Identify"] = 2] = "Identify"; - /** - * Update the client's presence - */ - GatewayOpcodes[GatewayOpcodes["PresenceUpdate"] = 3] = "PresenceUpdate"; - /** - * Used to join/leave or move between voice channels - */ - GatewayOpcodes[GatewayOpcodes["VoiceStateUpdate"] = 4] = "VoiceStateUpdate"; - /** - * Resume a previous session that was disconnected - */ - GatewayOpcodes[GatewayOpcodes["Resume"] = 6] = "Resume"; - /** - * You should attempt to reconnect and resume immediately - */ - GatewayOpcodes[GatewayOpcodes["Reconnect"] = 7] = "Reconnect"; - /** - * Request information about offline guild members in a large guild - */ - GatewayOpcodes[GatewayOpcodes["RequestGuildMembers"] = 8] = "RequestGuildMembers"; - /** - * The session has been invalidated. You should reconnect and identify/resume accordingly - */ - GatewayOpcodes[GatewayOpcodes["InvalidSession"] = 9] = "InvalidSession"; - /** - * Sent immediately after connecting, contains the `heartbeat_interval` to use - */ - GatewayOpcodes[GatewayOpcodes["Hello"] = 10] = "Hello"; - /** - * Sent in response to receiving a heartbeat to acknowledge that it has been received - */ - GatewayOpcodes[GatewayOpcodes["HeartbeatAck"] = 11] = "HeartbeatAck"; -})(GatewayOpcodes = exports.GatewayOpcodes || (exports.GatewayOpcodes = {})); -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-close-event-codes - */ -var GatewayCloseCodes; -(function (GatewayCloseCodes) { - /** - * We're not sure what went wrong. Try reconnecting? - */ - GatewayCloseCodes[GatewayCloseCodes["UnknownError"] = 4000] = "UnknownError"; - /** - * You sent an invalid Gateway opcode or an invalid payload for an opcode. Don't do that! - * - * See https://discord.com/developers/docs/topics/gateway#payloads-and-opcodes - */ - GatewayCloseCodes[GatewayCloseCodes["UnknownOpcode"] = 4001] = "UnknownOpcode"; - /** - * You sent an invalid payload to us. Don't do that! - * - * See https://discord.com/developers/docs/topics/gateway#sending-payloads - */ - GatewayCloseCodes[GatewayCloseCodes["DecodeError"] = 4002] = "DecodeError"; - /** - * You sent us a payload prior to identifying - * - * See https://discord.com/developers/docs/topics/gateway#identify - */ - GatewayCloseCodes[GatewayCloseCodes["NotAuthenticated"] = 4003] = "NotAuthenticated"; - /** - * The account token sent with your identify payload is incorrect - * - * See https://discord.com/developers/docs/topics/gateway#identify - */ - GatewayCloseCodes[GatewayCloseCodes["AuthenticationFailed"] = 4004] = "AuthenticationFailed"; - /** - * You sent more than one identify payload. Don't do that! - */ - GatewayCloseCodes[GatewayCloseCodes["AlreadyAuthenticated"] = 4005] = "AlreadyAuthenticated"; - /** - * The sequence sent when resuming the session was invalid. Reconnect and start a new session - * - * See https://discord.com/developers/docs/topics/gateway#resume - */ - GatewayCloseCodes[GatewayCloseCodes["InvalidSeq"] = 4007] = "InvalidSeq"; - /** - * Woah nelly! You're sending payloads to us too quickly. Slow it down! You will be disconnected on receiving this - */ - GatewayCloseCodes[GatewayCloseCodes["RateLimited"] = 4008] = "RateLimited"; - /** - * Your session timed out. Reconnect and start a new one - */ - GatewayCloseCodes[GatewayCloseCodes["SessionTimedOut"] = 4009] = "SessionTimedOut"; - /** - * You sent us an invalid shard when identifying - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - GatewayCloseCodes[GatewayCloseCodes["InvalidShard"] = 4010] = "InvalidShard"; - /** - * The session would have handled too many guilds - you are required to shard your connection in order to connect - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - GatewayCloseCodes[GatewayCloseCodes["ShardingRequired"] = 4011] = "ShardingRequired"; - /** - * You sent an invalid version for the gateway - */ - GatewayCloseCodes[GatewayCloseCodes["InvalidAPIVersion"] = 4012] = "InvalidAPIVersion"; - /** - * You sent an invalid intent for a Gateway Intent. You may have incorrectly calculated the bitwise value - * - * See https://discord.com/developers/docs/topics/gateway#gateway-intents - */ - GatewayCloseCodes[GatewayCloseCodes["InvalidIntents"] = 4013] = "InvalidIntents"; - /** - * You sent a disallowed intent for a Gateway Intent. You may have tried to specify an intent that you have not - * enabled or are not whitelisted for - * - * See https://discord.com/developers/docs/topics/gateway#gateway-intents - * - * See https://discord.com/developers/docs/topics/gateway#privileged-intents - */ - GatewayCloseCodes[GatewayCloseCodes["DisallowedIntents"] = 4014] = "DisallowedIntents"; -})(GatewayCloseCodes = exports.GatewayCloseCodes || (exports.GatewayCloseCodes = {})); -/** - * https://discord.com/developers/docs/topics/gateway#list-of-intents - */ -var GatewayIntentBits; -(function (GatewayIntentBits) { - GatewayIntentBits[GatewayIntentBits["Guilds"] = 1] = "Guilds"; - GatewayIntentBits[GatewayIntentBits["GuildMembers"] = 2] = "GuildMembers"; - GatewayIntentBits[GatewayIntentBits["GuildBans"] = 4] = "GuildBans"; - GatewayIntentBits[GatewayIntentBits["GuildEmojisAndStickers"] = 8] = "GuildEmojisAndStickers"; - GatewayIntentBits[GatewayIntentBits["GuildIntegrations"] = 16] = "GuildIntegrations"; - GatewayIntentBits[GatewayIntentBits["GuildWebhooks"] = 32] = "GuildWebhooks"; - GatewayIntentBits[GatewayIntentBits["GuildInvites"] = 64] = "GuildInvites"; - GatewayIntentBits[GatewayIntentBits["GuildVoiceStates"] = 128] = "GuildVoiceStates"; - GatewayIntentBits[GatewayIntentBits["GuildPresences"] = 256] = "GuildPresences"; - GatewayIntentBits[GatewayIntentBits["GuildMessages"] = 512] = "GuildMessages"; - GatewayIntentBits[GatewayIntentBits["GuildMessageReactions"] = 1024] = "GuildMessageReactions"; - GatewayIntentBits[GatewayIntentBits["GuildMessageTyping"] = 2048] = "GuildMessageTyping"; - GatewayIntentBits[GatewayIntentBits["DirectMessages"] = 4096] = "DirectMessages"; - GatewayIntentBits[GatewayIntentBits["DirectMessageReactions"] = 8192] = "DirectMessageReactions"; - GatewayIntentBits[GatewayIntentBits["DirectMessageTyping"] = 16384] = "DirectMessageTyping"; - GatewayIntentBits[GatewayIntentBits["MessageContent"] = 32768] = "MessageContent"; - GatewayIntentBits[GatewayIntentBits["GuildScheduledEvents"] = 65536] = "GuildScheduledEvents"; -})(GatewayIntentBits = exports.GatewayIntentBits || (exports.GatewayIntentBits = {})); -/** - * https://discord.com/developers/docs/topics/gateway#commands-and-events-gateway-events - */ -var GatewayDispatchEvents; -(function (GatewayDispatchEvents) { - GatewayDispatchEvents["ApplicationCommandPermissionsUpdate"] = "APPLICATION_COMMAND_PERMISSIONS_UPDATE"; - GatewayDispatchEvents["ChannelCreate"] = "CHANNEL_CREATE"; - GatewayDispatchEvents["ChannelDelete"] = "CHANNEL_DELETE"; - GatewayDispatchEvents["ChannelPinsUpdate"] = "CHANNEL_PINS_UPDATE"; - GatewayDispatchEvents["ChannelUpdate"] = "CHANNEL_UPDATE"; - GatewayDispatchEvents["GuildBanAdd"] = "GUILD_BAN_ADD"; - GatewayDispatchEvents["GuildBanRemove"] = "GUILD_BAN_REMOVE"; - GatewayDispatchEvents["GuildCreate"] = "GUILD_CREATE"; - GatewayDispatchEvents["GuildDelete"] = "GUILD_DELETE"; - GatewayDispatchEvents["GuildEmojisUpdate"] = "GUILD_EMOJIS_UPDATE"; - GatewayDispatchEvents["GuildIntegrationsUpdate"] = "GUILD_INTEGRATIONS_UPDATE"; - GatewayDispatchEvents["GuildMemberAdd"] = "GUILD_MEMBER_ADD"; - GatewayDispatchEvents["GuildMemberRemove"] = "GUILD_MEMBER_REMOVE"; - GatewayDispatchEvents["GuildMembersChunk"] = "GUILD_MEMBERS_CHUNK"; - GatewayDispatchEvents["GuildMemberUpdate"] = "GUILD_MEMBER_UPDATE"; - GatewayDispatchEvents["GuildRoleCreate"] = "GUILD_ROLE_CREATE"; - GatewayDispatchEvents["GuildRoleDelete"] = "GUILD_ROLE_DELETE"; - GatewayDispatchEvents["GuildRoleUpdate"] = "GUILD_ROLE_UPDATE"; - GatewayDispatchEvents["GuildStickersUpdate"] = "GUILD_STICKERS_UPDATE"; - GatewayDispatchEvents["GuildUpdate"] = "GUILD_UPDATE"; - GatewayDispatchEvents["IntegrationCreate"] = "INTEGRATION_CREATE"; - GatewayDispatchEvents["IntegrationDelete"] = "INTEGRATION_DELETE"; - GatewayDispatchEvents["IntegrationUpdate"] = "INTEGRATION_UPDATE"; - GatewayDispatchEvents["InteractionCreate"] = "INTERACTION_CREATE"; - GatewayDispatchEvents["InviteCreate"] = "INVITE_CREATE"; - GatewayDispatchEvents["InviteDelete"] = "INVITE_DELETE"; - GatewayDispatchEvents["MessageCreate"] = "MESSAGE_CREATE"; - GatewayDispatchEvents["MessageDelete"] = "MESSAGE_DELETE"; - GatewayDispatchEvents["MessageDeleteBulk"] = "MESSAGE_DELETE_BULK"; - GatewayDispatchEvents["MessageReactionAdd"] = "MESSAGE_REACTION_ADD"; - GatewayDispatchEvents["MessageReactionRemove"] = "MESSAGE_REACTION_REMOVE"; - GatewayDispatchEvents["MessageReactionRemoveAll"] = "MESSAGE_REACTION_REMOVE_ALL"; - GatewayDispatchEvents["MessageReactionRemoveEmoji"] = "MESSAGE_REACTION_REMOVE_EMOJI"; - GatewayDispatchEvents["MessageUpdate"] = "MESSAGE_UPDATE"; - GatewayDispatchEvents["PresenceUpdate"] = "PRESENCE_UPDATE"; - GatewayDispatchEvents["StageInstanceCreate"] = "STAGE_INSTANCE_CREATE"; - GatewayDispatchEvents["StageInstanceDelete"] = "STAGE_INSTANCE_DELETE"; - GatewayDispatchEvents["StageInstanceUpdate"] = "STAGE_INSTANCE_UPDATE"; - GatewayDispatchEvents["Ready"] = "READY"; - GatewayDispatchEvents["Resumed"] = "RESUMED"; - GatewayDispatchEvents["ThreadCreate"] = "THREAD_CREATE"; - GatewayDispatchEvents["ThreadDelete"] = "THREAD_DELETE"; - GatewayDispatchEvents["ThreadListSync"] = "THREAD_LIST_SYNC"; - GatewayDispatchEvents["ThreadMembersUpdate"] = "THREAD_MEMBERS_UPDATE"; - GatewayDispatchEvents["ThreadMemberUpdate"] = "THREAD_MEMBER_UPDATE"; - GatewayDispatchEvents["ThreadUpdate"] = "THREAD_UPDATE"; - GatewayDispatchEvents["TypingStart"] = "TYPING_START"; - GatewayDispatchEvents["UserUpdate"] = "USER_UPDATE"; - GatewayDispatchEvents["VoiceServerUpdate"] = "VOICE_SERVER_UPDATE"; - GatewayDispatchEvents["VoiceStateUpdate"] = "VOICE_STATE_UPDATE"; - GatewayDispatchEvents["WebhooksUpdate"] = "WEBHOOKS_UPDATE"; - GatewayDispatchEvents["GuildScheduledEventCreate"] = "GUILD_SCHEDULED_EVENT_CREATE"; - GatewayDispatchEvents["GuildScheduledEventUpdate"] = "GUILD_SCHEDULED_EVENT_UPDATE"; - GatewayDispatchEvents["GuildScheduledEventDelete"] = "GUILD_SCHEDULED_EVENT_DELETE"; - GatewayDispatchEvents["GuildScheduledEventUserAdd"] = "GUILD_SCHEDULED_EVENT_USER_ADD"; - GatewayDispatchEvents["GuildScheduledEventUserRemove"] = "GUILD_SCHEDULED_EVENT_USER_REMOVE"; -})(GatewayDispatchEvents = exports.GatewayDispatchEvents || (exports.GatewayDispatchEvents = {})); -// #endregion Shared -//# sourceMappingURL=v10.js.map \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v10.js.map b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v10.js.map deleted file mode 100644 index 29ffa09..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v10.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"v10.js","sourceRoot":"","sources":["v10.ts"],"names":[],"mappings":";AAAA;;GAEG;;;;;;;;;;;;;;;;;AA+BH,2CAAyB;AAEZ,QAAA,cAAc,GAAG,IAAI,CAAC;AAEnC;;GAEG;AACH,IAAY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,oEAA2C,CAAA;IAC3C,uDAA8B,CAAA;IAC9B,qDAA4B,CAAA;IAC5B,mDAA0B,CAAA;IAC1B,kEAAyC,CAAA;IACzC,gEAAuC,CAAA;IACvC,2DAAkC,CAAA;IAClC,mFAA0D,CAAA;IAC1D,mFAA0D,CAAA;IAC1D,mFAA0D,CAAA;IAC1D,sFAA6D,CAAA;IAC7D,4FAAmE,CAAA;AACpE,CAAC,EAzDW,qBAAqB,GAArB,6BAAqB,KAArB,6BAAqB,QAyDhC;AAmjDD,oBAAoB"} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v10.mjs b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v10.mjs deleted file mode 100644 index 0ee554f..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v10.mjs +++ /dev/null @@ -1,8 +0,0 @@ -import mod from "./v10.js"; - -export default mod; -export const GatewayCloseCodes = mod.GatewayCloseCodes; -export const GatewayDispatchEvents = mod.GatewayDispatchEvents; -export const GatewayIntentBits = mod.GatewayIntentBits; -export const GatewayOpcodes = mod.GatewayOpcodes; -export const GatewayVersion = mod.GatewayVersion; diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v6.d.ts b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v6.d.ts deleted file mode 100644 index 13aa6ad..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v6.d.ts +++ /dev/null @@ -1,608 +0,0 @@ -/** - * Types extracted from https://discord.com/developers/docs/topics/gateway - */ -import type { APIChannel, APIEmoji, APIGuild, APIGuildMember, APIMessage, APIRole, APIUnavailableGuild, APIUser, GatewayActivity, GatewayPresenceUpdate as RawGatewayPresenceUpdate, GatewayVoiceState, InviteTargetUserType, PresenceUpdateStatus } from '../payloads/v6/index'; -export * from './common'; -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare const GatewayVersion = "6"; -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-opcodes - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare enum GatewayOPCodes { - Dispatch = 0, - Heartbeat = 1, - Identify = 2, - PresenceUpdate = 3, - VoiceStateUpdate = 4, - Resume = 6, - Reconnect = 7, - RequestGuildMembers = 8, - InvalidSession = 9, - Hello = 10, - HeartbeatAck = 11 -} -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-close-event-codes - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare enum GatewayCloseCodes { - UnknownError = 4000, - UnknownOpCode = 4001, - DecodeError = 4002, - NotAuthenticated = 4003, - AuthenticationFailed = 4004, - AlreadyAuthenticated = 4005, - InvalidSeq = 4007, - RateLimited = 4008, - SessionTimedOut = 4009, - InvalidShard = 4010, - ShardingRequired = 4011, - InvalidAPIVersion = 4012, - InvalidIntents = 4013, - DisallowedIntents = 4014 -} -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#voice-voice-opcodes - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare enum VoiceOPCodes { - Identify = 0, - SelectProtocol = 1, - Ready = 2, - Heartbeat = 3, - SessionDescription = 4, - Speaking = 5, - HeartbeatAck = 6, - Resume = 7, - Hello = 8, - Resumed = 9, - ClientDisconnect = 13 -} -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#voice-voice-close-event-codes - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare enum VoiceCloseCodes { - UnknownOpCode = 4001, - NotAuthenticated = 4003, - AuthenticationFailed = 4004, - AlreadyAuthenticated = 4005, - SessionNoLongerValid = 4006, - SessionTimeout = 4009, - ServerNotFound = 4011, - UnknownProtocol = 4012, - Disconnected = 4014, - VoiceServerCrashed = 4015, - UnknownEncryptionMode = 4016 -} -/** - * https://discord.com/developers/docs/topics/gateway#list-of-intents - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare enum GatewayIntentBits { - GUILDS = 1, - GUILD_MEMBERS = 2, - GUILD_BANS = 4, - GUILD_EMOJIS = 8, - GUILD_INTEGRATIONS = 16, - GUILD_WEBHOOKS = 32, - GUILD_INVITES = 64, - GUILD_VOICE_STATES = 128, - GUILD_PRESENCES = 256, - GUILD_MESSAGES = 512, - GUILD_MESSAGE_REACTIONS = 1024, - GUILD_MESSAGE_TYPING = 2048, - DIRECT_MESSAGES = 4096, - DIRECT_MESSAGE_REACTIONS = 8192, - DIRECT_MESSAGE_TYPING = 16384 -} -/** - * https://discord.com/developers/docs/topics/gateway#commands-and-events-gateway-events - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare enum GatewayDispatchEvents { - Ready = "READY", - Resumed = "RESUMED", - ChannelCreate = "CHANNEL_CREATE", - ChannelUpdate = "CHANNEL_UPDATE", - ChannelDelete = "CHANNEL_DELETE", - ChannelPinsUpdate = "CHANNEL_PINS_UPDATE", - GuildCreate = "GUILD_CREATE", - GuildUpdate = "GUILD_UPDATE", - GuildDelete = "GUILD_DELETE", - GuildBanAdd = "GUILD_BAN_ADD", - GuildBanRemove = "GUILD_BAN_REMOVE", - GuildEmojisUpdate = "GUILD_EMOJIS_UPDATE", - GuildIntegrationsUpdate = "GUILD_INTEGRATIONS_UPDATE", - GuildMemberAdd = "GUILD_MEMBER_ADD", - GuildMemberRemove = "GUILD_MEMBER_REMOVE", - GuildMemberUpdate = "GUILD_MEMBER_UPDATE", - GuildMembersChunk = "GUILD_MEMBERS_CHUNK", - GuildRoleCreate = "GUILD_ROLE_CREATE", - GuildRoleUpdate = "GUILD_ROLE_UPDATE", - GuildRoleDelete = "GUILD_ROLE_DELETE", - InviteCreate = "INVITE_CREATE", - InviteDelete = "INVITE_DELETE", - MessageCreate = "MESSAGE_CREATE", - MessageUpdate = "MESSAGE_UPDATE", - MessageDelete = "MESSAGE_DELETE", - MessageDeleteBulk = "MESSAGE_DELETE_BULK", - MessageReactionAdd = "MESSAGE_REACTION_ADD", - MessageReactionRemove = "MESSAGE_REACTION_REMOVE", - MessageReactionRemoveAll = "MESSAGE_REACTION_REMOVE_ALL", - MessageReactionRemoveEmoji = "MESSAGE_REACTION_REMOVE_EMOJI", - PresenceUpdate = "PRESENCE_UPDATE", - TypingStart = "TYPING_START", - UserUpdate = "USER_UPDATE", - VoiceStateUpdate = "VOICE_STATE_UPDATE", - VoiceServerUpdate = "VOICE_SERVER_UPDATE", - WebhooksUpdate = "WEBHOOKS_UPDATE" -} -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewaySendPayload = GatewayHeartbeat | GatewayIdentify | GatewayUpdatePresence | GatewayVoiceStateUpdate | GatewayResume | GatewayRequestGuildMembers; -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayReceivePayload = GatewayHello | GatewayHeartbeatRequest | GatewayHeartbeatAck | GatewayInvalidSession | GatewayReconnect | GatewayDispatchPayload; -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayDispatchPayload = GatewayReadyDispatch | GatewayResumedDispatch | GatewayChannelModifyDispatch | GatewayChannelPinsUpdateDispatch | GatewayGuildModifyDispatch | GatewayGuildDeleteDispatch | GatewayGuildBanModifyDispatch | GatewayGuildEmojisUpdateDispatch | GatewayGuildIntegrationsUpdateDispatch | GatewayGuildMemberAddDispatch | GatewayGuildMemberRemoveDispatch | GatewayGuildMemberUpdateDispatch | GatewayGuildMembersChunkDispatch | GatewayGuildRoleModifyDispatch | GatewayGuildRoleDeleteDispatch | GatewayInviteCreateDispatch | GatewayInviteDeleteDispatch | GatewayMessageCreateDispatch | GatewayMessageUpdateDispatch | GatewayMessageDeleteDispatch | GatewayMessageDeleteBulkDispatch | GatewayMessageReactionAddDispatch | GatewayMessageReactionRemoveDispatch | GatewayMessageReactionRemoveAllDispatch | GatewayMessageReactionRemoveEmojiDispatch | GatewayPresenceUpdateDispatch | GatewayTypingStartDispatch | GatewayUserUpdateDispatch | GatewayVoiceStateUpdateDispatch | GatewayVoiceServerUpdateDispatch | GatewayWebhooksUpdateDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#hello - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export interface GatewayHello extends NonDispatchPayload { - op: GatewayOPCodes.Hello; - d: { - heartbeat_interval: number; - }; -} -/** - * https://discord.com/developers/docs/topics/gateway#heartbeating - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export interface GatewayHeartbeatRequest extends NonDispatchPayload { - op: GatewayOPCodes.Heartbeat; - d: never; -} -/** - * https://discord.com/developers/docs/topics/gateway#heartbeating-example-gateway-heartbeat-ack - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export interface GatewayHeartbeatAck extends NonDispatchPayload { - op: GatewayOPCodes.HeartbeatAck; - d: never; -} -/** - * https://discord.com/developers/docs/topics/gateway#invalid-session - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export interface GatewayInvalidSession extends NonDispatchPayload { - op: GatewayOPCodes.InvalidSession; - d: boolean; -} -/** - * https://discord.com/developers/docs/topics/gateway#reconnect - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export interface GatewayReconnect extends NonDispatchPayload { - op: GatewayOPCodes.Reconnect; - d: never; -} -/** - * https://discord.com/developers/docs/topics/gateway#ready - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayReadyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#resumed - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayResumedDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#channel-create - * https://discord.com/developers/docs/topics/gateway#channel-update - * https://discord.com/developers/docs/topics/gateway#channel-delete - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayChannelModifyDispatch = DataPayload; -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayChannelCreateDispatch = GatewayChannelModifyDispatch; -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayChannelUpdateDispatch = GatewayChannelModifyDispatch; -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayChannelDeleteDispatch = GatewayChannelModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#channel-pins-update - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayChannelPinsUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-create - * https://discord.com/developers/docs/topics/gateway#guild-update - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayGuildModifyDispatch = DataPayload; -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayGuildCreateDispatch = GatewayGuildModifyDispatch; -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayGuildUpdateDispatch = GatewayGuildModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-delete - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayGuildDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-add - * https://discord.com/developers/docs/topics/gateway#guild-ban-remove - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayGuildBanModifyDispatch = DataPayload; -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayGuildBanAddDispatch = GatewayGuildBanModifyDispatch; -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayGuildBanRemoveDispatch = GatewayGuildBanModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-emojis-update - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayGuildEmojisUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-integrations-update - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayGuildIntegrationsUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-add - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayGuildMemberAddDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-remove - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayGuildMemberRemoveDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-update - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayGuildMemberUpdateDispatch = DataPayload & { - guild_id: string; -}>; -/** - * https://discord.com/developers/docs/topics/gateway#guild-members-chunk - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayGuildMembersChunkDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-create - * https://discord.com/developers/docs/topics/gateway#guild-role-update - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayGuildRoleModifyDispatch = DataPayload; -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayGuildRoleCreateDispatch = GatewayGuildRoleModifyDispatch; -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayGuildRoleUpdateDispatch = GatewayGuildRoleModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-delete - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayGuildRoleDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#invite-create - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayInviteCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#invite-delete - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayInviteDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-create - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayMessageCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-update - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayMessageUpdateDispatch = DataPayload>; -/** - * https://discord.com/developers/docs/topics/gateway#message-delete - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayMessageDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-delete-bulk - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayMessageDeleteBulkDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-add - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayMessageReactionAddDispatch = ReactionData; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayMessageReactionRemoveDispatch = ReactionData; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-all - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayMessageReactionRemoveAllDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-emoji - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayMessageReactionRemoveEmojiDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#presence-update - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayPresenceUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#typing-start - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayTypingStartDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#user-update - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayUserUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#voice-state-update - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayVoiceStateUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#voice-server-update - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayVoiceServerUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#webhooks-update - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export declare type GatewayWebhooksUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#heartbeating - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export interface GatewayHeartbeat { - op: GatewayOPCodes.Heartbeat; - d: number; -} -/** - * https://discord.com/developers/docs/topics/gateway#identify-identify-connection-properties - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export interface GatewayIdentifyProperties { - $os: string; - $browser: string; - $device: string; -} -/** - * https://discord.com/developers/docs/topics/gateway#identify - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export interface GatewayIdentify { - op: GatewayOPCodes.Identify; - d: { - token: string; - properties: GatewayIdentifyProperties; - compress?: boolean; - large_threshold?: number; - shard?: [shard_id: number, shard_count: number]; - presence?: RawGatewayPresenceUpdate; - guild_subscriptions?: boolean; - intents?: number; - }; -} -/** - * https://discord.com/developers/docs/topics/gateway#resume - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export interface GatewayResume { - op: GatewayOPCodes.Resume; - d: { - token: string; - session_id: string; - seq: number; - }; -} -/** - * https://discord.com/developers/docs/topics/gateway#request-guild-members - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export interface GatewayRequestGuildMembers { - op: GatewayOPCodes.RequestGuildMembers; - d: { - guild_id: string | string[]; - query?: string; - limit: number; - presences?: boolean; - user_ids?: string | string[]; - nonce?: string; - }; -} -/** - * https://discord.com/developers/docs/topics/gateway#update-voice-state - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export interface GatewayVoiceStateUpdate { - op: GatewayOPCodes.VoiceStateUpdate; - d: { - guild_id: string; - channel_id: string | null; - self_mute: boolean; - self_deaf: boolean; - }; -} -/** - * https://discord.com/developers/docs/topics/gateway#update-status - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export interface GatewayUpdatePresence { - op: GatewayOPCodes.PresenceUpdate; - d: GatewayPresenceUpdateData; -} -/** - * https://discord.com/developers/docs/topics/gateway#update-status-gateway-status-update-structure - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -export interface GatewayPresenceUpdateData { - since: number | null; - game: GatewayActivity | null; - status: PresenceUpdateStatus; - afk: boolean; -} -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -interface BasePayload { - op: GatewayOPCodes; - s: number; - d?: unknown; - t?: string; -} -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -declare type NonDispatchPayload = Omit; -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -interface DataPayload extends BasePayload { - op: GatewayOPCodes.Dispatch; - t: Event; - d: D; -} -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -declare type ReactionData = DataPayload>; -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -interface MessageReactionRemoveData { - channel_id: string; - message_id: string; - guild_id?: string; -} -//# sourceMappingURL=v6.d.ts.map \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v6.d.ts.map b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v6.d.ts.map deleted file mode 100644 index a7b9755..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v6.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"v6.d.ts","sourceRoot":"","sources":["v6.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EACX,UAAU,EACV,QAAQ,EACR,QAAQ,EACR,cAAc,EACd,UAAU,EACV,OAAO,EACP,mBAAmB,EACnB,OAAO,EACP,eAAe,EACf,qBAAqB,IAAI,wBAAwB,EACjD,iBAAiB,EACjB,oBAAoB,EACpB,oBAAoB,EACpB,MAAM,sBAAsB,CAAC;AAE9B,cAAc,UAAU,CAAC;AAEzB;;GAEG;AACH,eAAO,MAAM,cAAc,MAAM,CAAC;AAElC;;;GAGG;AACH,oBAAY,cAAc;IACzB,QAAQ,IAAA;IACR,SAAS,IAAA;IACT,QAAQ,IAAA;IACR,cAAc,IAAA;IACd,gBAAgB,IAAA;IAEhB,MAAM,IAAI;IACV,SAAS,IAAA;IACT,mBAAmB,IAAA;IACnB,cAAc,IAAA;IACd,KAAK,KAAA;IACL,YAAY,KAAA;CACZ;AAED;;;GAGG;AACH,oBAAY,iBAAiB;IAC5B,YAAY,OAAO;IACnB,aAAa,OAAA;IACb,WAAW,OAAA;IACX,gBAAgB,OAAA;IAChB,oBAAoB,OAAA;IACpB,oBAAoB,OAAA;IAEpB,UAAU,OAAO;IACjB,WAAW,OAAA;IACX,eAAe,OAAA;IACf,YAAY,OAAA;IACZ,gBAAgB,OAAA;IAChB,iBAAiB,OAAA;IACjB,cAAc,OAAA;IACd,iBAAiB,OAAA;CACjB;AAED;;;GAGG;AACH,oBAAY,YAAY;I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CAAC;IAC5B,CAAC,EAAE,KAAK,CAAC;IACT,CAAC,EAAE,CAAC,CAAC;CACL;AAED;;GAEG;AACH,aAAK,YAAY,CAAC,CAAC,SAAS,qBAAqB,EAAE,CAAC,SAAS,MAAM,GAAG,KAAK,IAAI,WAAW,CACzF,CAAC,EACD,IAAI,CACH;IACC,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,MAAM,CAAC,EAAE,cAAc,CAAC;IACxB,KAAK,EAAE,QAAQ,CAAC;CAChB,EACD,CAAC,CACD,CACD,CAAC;AAEF;;GAEG;AACH,UAAU,yBAAyB;IAClC,UAAU,EAAE,MAAM,CAAC;IACnB,UAAU,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB"} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v6.js b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v6.js deleted file mode 100644 index 764c33a..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v6.js +++ /dev/null @@ -1,167 +0,0 @@ -"use strict"; -/** - * Types extracted from https://discord.com/developers/docs/topics/gateway - */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GatewayDispatchEvents = exports.GatewayIntentBits = exports.VoiceCloseCodes = exports.VoiceOPCodes = exports.GatewayCloseCodes = exports.GatewayOPCodes = exports.GatewayVersion = void 0; -__exportStar(require("./common"), exports); -/** - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -exports.GatewayVersion = '6'; -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-opcodes - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -var GatewayOPCodes; -(function (GatewayOPCodes) { - GatewayOPCodes[GatewayOPCodes["Dispatch"] = 0] = "Dispatch"; - GatewayOPCodes[GatewayOPCodes["Heartbeat"] = 1] = "Heartbeat"; - GatewayOPCodes[GatewayOPCodes["Identify"] = 2] = "Identify"; - GatewayOPCodes[GatewayOPCodes["PresenceUpdate"] = 3] = "PresenceUpdate"; - GatewayOPCodes[GatewayOPCodes["VoiceStateUpdate"] = 4] = "VoiceStateUpdate"; - GatewayOPCodes[GatewayOPCodes["Resume"] = 6] = "Resume"; - GatewayOPCodes[GatewayOPCodes["Reconnect"] = 7] = "Reconnect"; - GatewayOPCodes[GatewayOPCodes["RequestGuildMembers"] = 8] = "RequestGuildMembers"; - GatewayOPCodes[GatewayOPCodes["InvalidSession"] = 9] = "InvalidSession"; - GatewayOPCodes[GatewayOPCodes["Hello"] = 10] = "Hello"; - GatewayOPCodes[GatewayOPCodes["HeartbeatAck"] = 11] = "HeartbeatAck"; -})(GatewayOPCodes = exports.GatewayOPCodes || (exports.GatewayOPCodes = {})); -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-close-event-codes - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -var GatewayCloseCodes; -(function (GatewayCloseCodes) { - GatewayCloseCodes[GatewayCloseCodes["UnknownError"] = 4000] = "UnknownError"; - GatewayCloseCodes[GatewayCloseCodes["UnknownOpCode"] = 4001] = "UnknownOpCode"; - GatewayCloseCodes[GatewayCloseCodes["DecodeError"] = 4002] = "DecodeError"; - GatewayCloseCodes[GatewayCloseCodes["NotAuthenticated"] = 4003] = "NotAuthenticated"; - GatewayCloseCodes[GatewayCloseCodes["AuthenticationFailed"] = 4004] = "AuthenticationFailed"; - GatewayCloseCodes[GatewayCloseCodes["AlreadyAuthenticated"] = 4005] = "AlreadyAuthenticated"; - GatewayCloseCodes[GatewayCloseCodes["InvalidSeq"] = 4007] = "InvalidSeq"; - GatewayCloseCodes[GatewayCloseCodes["RateLimited"] = 4008] = "RateLimited"; - GatewayCloseCodes[GatewayCloseCodes["SessionTimedOut"] = 4009] = "SessionTimedOut"; - GatewayCloseCodes[GatewayCloseCodes["InvalidShard"] = 4010] = "InvalidShard"; - GatewayCloseCodes[GatewayCloseCodes["ShardingRequired"] = 4011] = "ShardingRequired"; - GatewayCloseCodes[GatewayCloseCodes["InvalidAPIVersion"] = 4012] = "InvalidAPIVersion"; - GatewayCloseCodes[GatewayCloseCodes["InvalidIntents"] = 4013] = "InvalidIntents"; - GatewayCloseCodes[GatewayCloseCodes["DisallowedIntents"] = 4014] = "DisallowedIntents"; -})(GatewayCloseCodes = exports.GatewayCloseCodes || (exports.GatewayCloseCodes = {})); -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#voice-voice-opcodes - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -var VoiceOPCodes; -(function (VoiceOPCodes) { - VoiceOPCodes[VoiceOPCodes["Identify"] = 0] = "Identify"; - VoiceOPCodes[VoiceOPCodes["SelectProtocol"] = 1] = "SelectProtocol"; - VoiceOPCodes[VoiceOPCodes["Ready"] = 2] = "Ready"; - VoiceOPCodes[VoiceOPCodes["Heartbeat"] = 3] = "Heartbeat"; - VoiceOPCodes[VoiceOPCodes["SessionDescription"] = 4] = "SessionDescription"; - VoiceOPCodes[VoiceOPCodes["Speaking"] = 5] = "Speaking"; - VoiceOPCodes[VoiceOPCodes["HeartbeatAck"] = 6] = "HeartbeatAck"; - VoiceOPCodes[VoiceOPCodes["Resume"] = 7] = "Resume"; - VoiceOPCodes[VoiceOPCodes["Hello"] = 8] = "Hello"; - VoiceOPCodes[VoiceOPCodes["Resumed"] = 9] = "Resumed"; - VoiceOPCodes[VoiceOPCodes["ClientDisconnect"] = 13] = "ClientDisconnect"; -})(VoiceOPCodes = exports.VoiceOPCodes || (exports.VoiceOPCodes = {})); -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#voice-voice-close-event-codes - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -var VoiceCloseCodes; -(function (VoiceCloseCodes) { - VoiceCloseCodes[VoiceCloseCodes["UnknownOpCode"] = 4001] = "UnknownOpCode"; - VoiceCloseCodes[VoiceCloseCodes["NotAuthenticated"] = 4003] = "NotAuthenticated"; - VoiceCloseCodes[VoiceCloseCodes["AuthenticationFailed"] = 4004] = "AuthenticationFailed"; - VoiceCloseCodes[VoiceCloseCodes["AlreadyAuthenticated"] = 4005] = "AlreadyAuthenticated"; - VoiceCloseCodes[VoiceCloseCodes["SessionNoLongerValid"] = 4006] = "SessionNoLongerValid"; - VoiceCloseCodes[VoiceCloseCodes["SessionTimeout"] = 4009] = "SessionTimeout"; - VoiceCloseCodes[VoiceCloseCodes["ServerNotFound"] = 4011] = "ServerNotFound"; - VoiceCloseCodes[VoiceCloseCodes["UnknownProtocol"] = 4012] = "UnknownProtocol"; - VoiceCloseCodes[VoiceCloseCodes["Disconnected"] = 4014] = "Disconnected"; - VoiceCloseCodes[VoiceCloseCodes["VoiceServerCrashed"] = 4015] = "VoiceServerCrashed"; - VoiceCloseCodes[VoiceCloseCodes["UnknownEncryptionMode"] = 4016] = "UnknownEncryptionMode"; -})(VoiceCloseCodes = exports.VoiceCloseCodes || (exports.VoiceCloseCodes = {})); -/** - * https://discord.com/developers/docs/topics/gateway#list-of-intents - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -var GatewayIntentBits; -(function (GatewayIntentBits) { - GatewayIntentBits[GatewayIntentBits["GUILDS"] = 1] = "GUILDS"; - GatewayIntentBits[GatewayIntentBits["GUILD_MEMBERS"] = 2] = "GUILD_MEMBERS"; - GatewayIntentBits[GatewayIntentBits["GUILD_BANS"] = 4] = "GUILD_BANS"; - GatewayIntentBits[GatewayIntentBits["GUILD_EMOJIS"] = 8] = "GUILD_EMOJIS"; - GatewayIntentBits[GatewayIntentBits["GUILD_INTEGRATIONS"] = 16] = "GUILD_INTEGRATIONS"; - GatewayIntentBits[GatewayIntentBits["GUILD_WEBHOOKS"] = 32] = "GUILD_WEBHOOKS"; - GatewayIntentBits[GatewayIntentBits["GUILD_INVITES"] = 64] = "GUILD_INVITES"; - GatewayIntentBits[GatewayIntentBits["GUILD_VOICE_STATES"] = 128] = "GUILD_VOICE_STATES"; - GatewayIntentBits[GatewayIntentBits["GUILD_PRESENCES"] = 256] = "GUILD_PRESENCES"; - GatewayIntentBits[GatewayIntentBits["GUILD_MESSAGES"] = 512] = "GUILD_MESSAGES"; - GatewayIntentBits[GatewayIntentBits["GUILD_MESSAGE_REACTIONS"] = 1024] = "GUILD_MESSAGE_REACTIONS"; - GatewayIntentBits[GatewayIntentBits["GUILD_MESSAGE_TYPING"] = 2048] = "GUILD_MESSAGE_TYPING"; - GatewayIntentBits[GatewayIntentBits["DIRECT_MESSAGES"] = 4096] = "DIRECT_MESSAGES"; - GatewayIntentBits[GatewayIntentBits["DIRECT_MESSAGE_REACTIONS"] = 8192] = "DIRECT_MESSAGE_REACTIONS"; - GatewayIntentBits[GatewayIntentBits["DIRECT_MESSAGE_TYPING"] = 16384] = "DIRECT_MESSAGE_TYPING"; -})(GatewayIntentBits = exports.GatewayIntentBits || (exports.GatewayIntentBits = {})); -/** - * https://discord.com/developers/docs/topics/gateway#commands-and-events-gateway-events - * @deprecated Gateway v6 is deprecated and the types will not receive further updates, please update to v8. - */ -var GatewayDispatchEvents; -(function (GatewayDispatchEvents) { - GatewayDispatchEvents["Ready"] = "READY"; - GatewayDispatchEvents["Resumed"] = "RESUMED"; - GatewayDispatchEvents["ChannelCreate"] = "CHANNEL_CREATE"; - GatewayDispatchEvents["ChannelUpdate"] = "CHANNEL_UPDATE"; - GatewayDispatchEvents["ChannelDelete"] = "CHANNEL_DELETE"; - GatewayDispatchEvents["ChannelPinsUpdate"] = "CHANNEL_PINS_UPDATE"; - GatewayDispatchEvents["GuildCreate"] = "GUILD_CREATE"; - GatewayDispatchEvents["GuildUpdate"] = "GUILD_UPDATE"; - GatewayDispatchEvents["GuildDelete"] = "GUILD_DELETE"; - GatewayDispatchEvents["GuildBanAdd"] = "GUILD_BAN_ADD"; - GatewayDispatchEvents["GuildBanRemove"] = "GUILD_BAN_REMOVE"; - GatewayDispatchEvents["GuildEmojisUpdate"] = "GUILD_EMOJIS_UPDATE"; - GatewayDispatchEvents["GuildIntegrationsUpdate"] = "GUILD_INTEGRATIONS_UPDATE"; - GatewayDispatchEvents["GuildMemberAdd"] = "GUILD_MEMBER_ADD"; - GatewayDispatchEvents["GuildMemberRemove"] = "GUILD_MEMBER_REMOVE"; - GatewayDispatchEvents["GuildMemberUpdate"] = "GUILD_MEMBER_UPDATE"; - GatewayDispatchEvents["GuildMembersChunk"] = "GUILD_MEMBERS_CHUNK"; - GatewayDispatchEvents["GuildRoleCreate"] = "GUILD_ROLE_CREATE"; - GatewayDispatchEvents["GuildRoleUpdate"] = "GUILD_ROLE_UPDATE"; - GatewayDispatchEvents["GuildRoleDelete"] = "GUILD_ROLE_DELETE"; - GatewayDispatchEvents["InviteCreate"] = "INVITE_CREATE"; - GatewayDispatchEvents["InviteDelete"] = "INVITE_DELETE"; - GatewayDispatchEvents["MessageCreate"] = "MESSAGE_CREATE"; - GatewayDispatchEvents["MessageUpdate"] = "MESSAGE_UPDATE"; - GatewayDispatchEvents["MessageDelete"] = "MESSAGE_DELETE"; - GatewayDispatchEvents["MessageDeleteBulk"] = "MESSAGE_DELETE_BULK"; - GatewayDispatchEvents["MessageReactionAdd"] = "MESSAGE_REACTION_ADD"; - GatewayDispatchEvents["MessageReactionRemove"] = "MESSAGE_REACTION_REMOVE"; - GatewayDispatchEvents["MessageReactionRemoveAll"] = "MESSAGE_REACTION_REMOVE_ALL"; - GatewayDispatchEvents["MessageReactionRemoveEmoji"] = "MESSAGE_REACTION_REMOVE_EMOJI"; - GatewayDispatchEvents["PresenceUpdate"] = "PRESENCE_UPDATE"; - GatewayDispatchEvents["TypingStart"] = "TYPING_START"; - GatewayDispatchEvents["UserUpdate"] = "USER_UPDATE"; - GatewayDispatchEvents["VoiceStateUpdate"] = "VOICE_STATE_UPDATE"; - GatewayDispatchEvents["VoiceServerUpdate"] = "VOICE_SERVER_UPDATE"; - GatewayDispatchEvents["WebhooksUpdate"] = "WEBHOOKS_UPDATE"; -})(GatewayDispatchEvents = exports.GatewayDispatchEvents || (exports.GatewayDispatchEvents = {})); -// #endregion Shared -//# sourceMappingURL=v6.js.map \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v6.js.map b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v6.js.map deleted file mode 100644 index 71f63a7..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v6.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"v6.js","sourceRoot":"","sources":["v6.ts"],"names":[],"mappings":";AAAA;;GAEG;;;;;;;;;;;;;;;;;AAkBH,2CAAyB;AAEzB;;GAEG;AACU,QAAA,cAAc,GAAG,GAAG,CAAC;AAElC;;;GAGG;AACH,IAAY,cAaX;AAbD,WAAY,cAAc;IACzB,2DAAQ,CAAA;IACR,6DAAS,CAAA;IACT,2DAAQ,CAAA;IACR,uEAAc,CAAA;IACd,2EAAgB,CAAA;IAEhB,uDAAU,CAAA;IACV,6DAAS,CAAA;IACT,iFAAmB,CAAA;IACnB,uEAAc,CAAA;IACd,sDAAK,CAAA;IACL,oEAAY,CAAA;AACb,CAAC,EAbW,cAAc,GAAd,sBAAc,KAAd,sBAAc,QAazB;AAED;;;GAGG;AACH,IA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,uFAA2B,CAAA;IAC3B,iFAAwB,CAAA;IACxB,+EAAuB,CAAA;IACvB,kGAAiC,CAAA;IACjC,4FAA8B,CAAA;IAC9B,kFAAyB,CAAA;IACzB,oGAAkC,CAAA;IAClC,+FAA+B,CAAA;AAChC,CAAC,EAhBW,iBAAiB,GAAjB,yBAAiB,KAAjB,yBAAiB,QAgB5B;AAED;;;GAGG;AACH,IAAY,qBAqCX;AArCD,WAAY,qBAAqB;IAChC,wCAAe,CAAA;IACf,4CAAmB,CAAA;IACnB,yDAAgC,CAAA;IAChC,yDAAgC,CAAA;IAChC,yDAAgC,CAAA;IAChC,kEAAyC,CAAA;IACzC,qDAA4B,CAAA;IAC5B,qDAA4B,CAAA;IAC5B,qDAA4B,CAAA;IAC5B,sDAA6B,CAAA;IAC7B,4DAAmC,CAAA;IACnC,kEAAyC,CAAA;IACzC,8EAAqD,CAAA;IACrD,4DAAmC,CAAA;IACnC,kEAAyC,CAAA;IACzC,kEAAyC,CAAA;IACzC,kEAAyC,CAAA;IACzC,8DAAqC,CAAA;IACrC,8DAAqC,CAAA;IACrC,8DAAqC,CAAA;IACrC,uDAA8B,CAAA;IAC9B,uDAA8B,CAAA;IAC9B,yDAAgC,CAAA;IAChC,yDAAgC,CAAA;IAChC,yDAAgC,CAAA;IAChC,kEAAyC,CAAA;IACzC,oEAA2C,CAAA;IAC3C,0EAAiD,CAAA;IACjD,iFAAwD,CAAA;IACxD,qFAA4D,CAAA;IAC5D,2DAAkC,CAAA;IAClC,qDAA4B,CAAA;IAC5B,mDAA0B,CAAA;IAC1B,gEAAuC,CAAA;IACvC,kEAAyC,CAAA;IACzC,2DAAkC,CAAA;AACnC,CAAC,EArCW,qBAAqB,GAArB,6BAAqB,KAArB,6BAAqB,QAqChC;AAuoBD,oBAAoB"} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v6.mjs b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v6.mjs deleted file mode 100644 index 848edfc..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v6.mjs +++ /dev/null @@ -1,10 +0,0 @@ -import mod from "./v6.js"; - -export default mod; -export const GatewayCloseCodes = mod.GatewayCloseCodes; -export const GatewayDispatchEvents = mod.GatewayDispatchEvents; -export const GatewayIntentBits = mod.GatewayIntentBits; -export const GatewayOPCodes = mod.GatewayOPCodes; -export const GatewayVersion = mod.GatewayVersion; -export const VoiceCloseCodes = mod.VoiceCloseCodes; -export const VoiceOPCodes = mod.VoiceOPCodes; diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v8.d.ts b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v8.d.ts deleted file mode 100644 index 24608ea..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v8.d.ts +++ /dev/null @@ -1,1455 +0,0 @@ -/** - * Types extracted from https://discord.com/developers/docs/topics/gateway - */ -import type { Snowflake } from '../globals'; -import type { APIApplication, APIChannel, APIEmoji, APIGuild, APIGuildIntegration, APIGuildMember, APIGuildScheduledEvent, APIInteraction, APIMessage, APIRole, APIStageInstance, APISticker, APIUnavailableGuild, APIUser, GatewayActivity, GatewayPresenceUpdate as RawGatewayPresenceUpdate, GatewayVoiceState, InviteTargetType, PresenceUpdateStatus } from '../payloads/v8/index'; -import type { Nullable } from '../utils/internals'; -export * from './common'; -/** - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare const GatewayVersion = "8"; -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-opcodes - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare enum GatewayOpcodes { - /** - * An event was dispatched - */ - Dispatch = 0, - /** - * A bidirectional opcode to maintain an active gateway connection. - * Fired periodically by the client, or fired by the gateway to request an immediate heartbeat from the client. - */ - Heartbeat = 1, - /** - * Starts a new session during the initial handshake - */ - Identify = 2, - /** - * Update the client's presence - */ - PresenceUpdate = 3, - /** - * Used to join/leave or move between voice channels - */ - VoiceStateUpdate = 4, - /** - * Resume a previous session that was disconnected - */ - Resume = 6, - /** - * You should attempt to reconnect and resume immediately - */ - Reconnect = 7, - /** - * Request information about offline guild members in a large guild - */ - RequestGuildMembers = 8, - /** - * The session has been invalidated. You should reconnect and identify/resume accordingly - */ - InvalidSession = 9, - /** - * Sent immediately after connecting, contains the `heartbeat_interval` to use - */ - Hello = 10, - /** - * Sent in response to receiving a heartbeat to acknowledge that it has been received - */ - HeartbeatAck = 11 -} -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-close-event-codes - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare enum GatewayCloseCodes { - /** - * We're not sure what went wrong. Try reconnecting? - */ - UnknownError = 4000, - /** - * You sent an invalid Gateway opcode or an invalid payload for an opcode. Don't do that! - * - * See https://discord.com/developers/docs/topics/gateway#payloads-and-opcodes - */ - UnknownOpcode = 4001, - /** - * You sent an invalid payload to us. Don't do that! - * - * See https://discord.com/developers/docs/topics/gateway#sending-payloads - */ - DecodeError = 4002, - /** - * You sent us a payload prior to identifying - * - * See https://discord.com/developers/docs/topics/gateway#identify - */ - NotAuthenticated = 4003, - /** - * The account token sent with your identify payload is incorrect - * - * See https://discord.com/developers/docs/topics/gateway#identify - */ - AuthenticationFailed = 4004, - /** - * You sent more than one identify payload. Don't do that! - */ - AlreadyAuthenticated = 4005, - /** - * The sequence sent when resuming the session was invalid. Reconnect and start a new session - * - * See https://discord.com/developers/docs/topics/gateway#resume - */ - InvalidSeq = 4007, - /** - * Woah nelly! You're sending payloads to us too quickly. Slow it down! You will be disconnected on receiving this - */ - RateLimited = 4008, - /** - * Your session timed out. Reconnect and start a new one - */ - SessionTimedOut = 4009, - /** - * You sent us an invalid shard when identifying - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - InvalidShard = 4010, - /** - * The session would have handled too many guilds - you are required to shard your connection in order to connect - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - ShardingRequired = 4011, - /** - * You sent an invalid version for the gateway - */ - InvalidAPIVersion = 4012, - /** - * You sent an invalid intent for a Gateway Intent. You may have incorrectly calculated the bitwise value - * - * See https://discord.com/developers/docs/topics/gateway#gateway-intents - */ - InvalidIntents = 4013, - /** - * You sent a disallowed intent for a Gateway Intent. You may have tried to specify an intent that you have not - * enabled or are not whitelisted for - * - * See https://discord.com/developers/docs/topics/gateway#gateway-intents - * - * See https://discord.com/developers/docs/topics/gateway#privileged-intents - */ - DisallowedIntents = 4014 -} -/** - * https://discord.com/developers/docs/topics/gateway#list-of-intents - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare enum GatewayIntentBits { - Guilds = 1, - GuildMembers = 2, - GuildBans = 4, - GuildEmojisAndStickers = 8, - GuildIntegrations = 16, - GuildWebhooks = 32, - GuildInvites = 64, - GuildVoiceStates = 128, - GuildPresences = 256, - GuildMessages = 512, - GuildMessageReactions = 1024, - GuildMessageTyping = 2048, - DirectMessages = 4096, - DirectMessageReactions = 8192, - DirectMessageTyping = 16384, - GuildScheduledEvents = 65536 -} -/** - * https://discord.com/developers/docs/topics/gateway#commands-and-events-gateway-events - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare enum GatewayDispatchEvents { - ChannelCreate = "CHANNEL_CREATE", - ChannelDelete = "CHANNEL_DELETE", - ChannelPinsUpdate = "CHANNEL_PINS_UPDATE", - ChannelUpdate = "CHANNEL_UPDATE", - GuildBanAdd = "GUILD_BAN_ADD", - GuildBanRemove = "GUILD_BAN_REMOVE", - GuildCreate = "GUILD_CREATE", - GuildDelete = "GUILD_DELETE", - GuildEmojisUpdate = "GUILD_EMOJIS_UPDATE", - GuildIntegrationsUpdate = "GUILD_INTEGRATIONS_UPDATE", - GuildMemberAdd = "GUILD_MEMBER_ADD", - GuildMemberRemove = "GUILD_MEMBER_REMOVE", - GuildMembersChunk = "GUILD_MEMBERS_CHUNK", - GuildMemberUpdate = "GUILD_MEMBER_UPDATE", - GuildRoleCreate = "GUILD_ROLE_CREATE", - GuildRoleDelete = "GUILD_ROLE_DELETE", - GuildRoleUpdate = "GUILD_ROLE_UPDATE", - GuildStickersUpdate = "GUILD_STICKERS_UPDATE", - GuildUpdate = "GUILD_UPDATE", - IntegrationCreate = "INTEGRATION_CREATE", - IntegrationDelete = "INTEGRATION_DELETE", - IntegrationUpdate = "INTEGRATION_UPDATE", - InteractionCreate = "INTERACTION_CREATE", - InviteCreate = "INVITE_CREATE", - InviteDelete = "INVITE_DELETE", - MessageCreate = "MESSAGE_CREATE", - MessageDelete = "MESSAGE_DELETE", - MessageDeleteBulk = "MESSAGE_DELETE_BULK", - MessageReactionAdd = "MESSAGE_REACTION_ADD", - MessageReactionRemove = "MESSAGE_REACTION_REMOVE", - MessageReactionRemoveAll = "MESSAGE_REACTION_REMOVE_ALL", - MessageReactionRemoveEmoji = "MESSAGE_REACTION_REMOVE_EMOJI", - MessageUpdate = "MESSAGE_UPDATE", - PresenceUpdate = "PRESENCE_UPDATE", - StageInstanceCreate = "STAGE_INSTANCE_CREATE", - StageInstanceDelete = "STAGE_INSTANCE_DELETE", - StageInstanceUpdate = "STAGE_INSTANCE_UPDATE", - Ready = "READY", - Resumed = "RESUMED", - TypingStart = "TYPING_START", - UserUpdate = "USER_UPDATE", - VoiceServerUpdate = "VOICE_SERVER_UPDATE", - VoiceStateUpdate = "VOICE_STATE_UPDATE", - WebhooksUpdate = "WEBHOOKS_UPDATE", - GuildScheduledEventCreate = "GUILD_SCHEDULED_EVENT_CREATE", - GuildScheduledEventUpdate = "GUILD_SCHEDULED_EVENT_UPDATE", - GuildScheduledEventDelete = "GUILD_SCHEDULED_EVENT_DELETE", - GuildScheduledEventUserAdd = "GUILD_SCHEDULED_EVENT_USER_ADD", - GuildScheduledEventUserRemove = "GUILD_SCHEDULED_EVENT_USER_REMOVE" -} -/** - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewaySendPayload = GatewayHeartbeat | GatewayIdentify | GatewayUpdatePresence | GatewayVoiceStateUpdate | GatewayResume | GatewayRequestGuildMembers; -/** - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayReceivePayload = GatewayHello | GatewayHeartbeatRequest | GatewayHeartbeatAck | GatewayInvalidSession | GatewayReconnect | GatewayDispatchPayload; -/** - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayDispatchPayload = GatewayChannelModifyDispatch | GatewayChannelPinsUpdateDispatch | GatewayGuildBanModifyDispatch | GatewayGuildDeleteDispatch | GatewayGuildEmojisUpdateDispatch | GatewayGuildIntegrationsUpdateDispatch | GatewayGuildMemberAddDispatch | GatewayGuildMemberRemoveDispatch | GatewayGuildMembersChunkDispatch | GatewayGuildMemberUpdateDispatch | GatewayGuildModifyDispatch | GatewayGuildRoleDeleteDispatch | GatewayGuildRoleModifyDispatch | GatewayGuildScheduledEventCreateDispatch | GatewayGuildScheduledEventUpdateDispatch | GatewayGuildScheduledEventDeleteDispatch | GatewayGuildScheduledEventUserAddDispatch | GatewayGuildScheduledEventUserRemoveDispatch | GatewayGuildStickersUpdateDispatch | GatewayIntegrationCreateDispatch | GatewayIntegrationDeleteDispatch | GatewayIntegrationUpdateDispatch | GatewayInteractionCreateDispatch | GatewayInviteCreateDispatch | GatewayInviteDeleteDispatch | GatewayMessageCreateDispatch | GatewayMessageDeleteBulkDispatch | GatewayMessageDeleteDispatch | GatewayMessageReactionAddDispatch | GatewayMessageReactionRemoveAllDispatch | GatewayMessageReactionRemoveDispatch | GatewayMessageReactionRemoveEmojiDispatch | GatewayMessageUpdateDispatch | GatewayPresenceUpdateDispatch | GatewayStageInstanceCreateDispatch | GatewayStageInstanceDeleteDispatch | GatewayStageInstanceUpdateDispatch | GatewayReadyDispatch | GatewayResumedDispatch | GatewayTypingStartDispatch | GatewayUserUpdateDispatch | GatewayVoiceServerUpdateDispatch | GatewayVoiceStateUpdateDispatch | GatewayWebhooksUpdateDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#hello - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayHello extends NonDispatchPayload { - op: GatewayOpcodes.Hello; - d: GatewayHelloData; -} -/** - * https://discord.com/developers/docs/topics/gateway#hello - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayHelloData { - /** - * The interval (in milliseconds) the client should heartbeat with - */ - heartbeat_interval: number; -} -/** - * https://discord.com/developers/docs/topics/gateway#heartbeating - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayHeartbeatRequest extends NonDispatchPayload { - op: GatewayOpcodes.Heartbeat; - d: never; -} -/** - * https://discord.com/developers/docs/topics/gateway#heartbeating-example-gateway-heartbeat-ack - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayHeartbeatAck extends NonDispatchPayload { - op: GatewayOpcodes.HeartbeatAck; - d: never; -} -/** - * https://discord.com/developers/docs/topics/gateway#invalid-session - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayInvalidSession extends NonDispatchPayload { - op: GatewayOpcodes.InvalidSession; - d: GatewayInvalidSessionData; -} -/** - * https://discord.com/developers/docs/topics/gateway#invalid-session - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayInvalidSessionData = boolean; -/** - * https://discord.com/developers/docs/topics/gateway#reconnect - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayReconnect extends NonDispatchPayload { - op: GatewayOpcodes.Reconnect; - d: never; -} -/** - * https://discord.com/developers/docs/topics/gateway#ready - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayReadyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#ready - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayReadyDispatchData { - /** - * Gateway version - * - * See https://discord.com/developers/docs/topics/gateway#gateways-gateway-versions - */ - v: number; - /** - * Information about the user including email - * - * See https://discord.com/developers/docs/resources/user#user-object - */ - user: APIUser; - /** - * The guilds the user is in - * - * See https://discord.com/developers/docs/resources/guild#unavailable-guild-object - */ - guilds: APIUnavailableGuild[]; - /** - * Used for resuming connections - */ - session_id: string; - /** - * The shard information associated with this session, if sent when identifying - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - shard?: [shard_id: number, shard_count: number]; - /** - * Contains `id` and `flags` - * - * See https://discord.com/developers/docs/resources/application#application-object - */ - application: Pick; -} -/** - * https://discord.com/developers/docs/topics/gateway#resumed - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayResumedDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#channel-create - * https://discord.com/developers/docs/topics/gateway#channel-update - * https://discord.com/developers/docs/topics/gateway#channel-delete - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayChannelModifyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#channel-create - * https://discord.com/developers/docs/topics/gateway#channel-update - * https://discord.com/developers/docs/topics/gateway#channel-delete - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayChannelModifyDispatchData = APIChannel; -/** - * https://discord.com/developers/docs/topics/gateway#channel-create - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayChannelCreateDispatch = GatewayChannelModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#channel-create - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayChannelCreateDispatchData = GatewayChannelModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#channel-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayChannelUpdateDispatch = GatewayChannelModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#channel-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayChannelUpdateDispatchData = GatewayChannelModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#channel-delete - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayChannelDeleteDispatch = GatewayChannelModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#channel-delete - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayChannelDeleteDispatchData = GatewayChannelModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#channel-pins-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayChannelPinsUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#channel-pins-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayChannelPinsUpdateDispatchData { - /** - * The id of the guild - */ - guild_id?: Snowflake; - /** - * The id of the channel - */ - channel_id: Snowflake; - /** - * The time at which the most recent pinned message was pinned - */ - last_pin_timestamp?: string | null; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-create - * https://discord.com/developers/docs/topics/gateway#guild-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildModifyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-create - * https://discord.com/developers/docs/topics/gateway#guild-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildModifyDispatchData = APIGuild; -/** - * https://discord.com/developers/docs/topics/gateway#guild-create - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildCreateDispatch = GatewayGuildModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-create - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildCreateDispatchData = GatewayGuildModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#guild-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildUpdateDispatch = GatewayGuildModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildUpdateDispatchData = GatewayGuildModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#guild-delete - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-delete - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildDeleteDispatchData = APIUnavailableGuild; -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-add - * https://discord.com/developers/docs/topics/gateway#guild-ban-remove - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildBanModifyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-add - * https://discord.com/developers/docs/topics/gateway#guild-ban-remove - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayGuildBanModifyDispatchData { - /** - * ID of the guild - */ - guild_id: Snowflake; - /** - * The banned user - * - * See https://discord.com/developers/docs/resources/user#user-object - */ - user: APIUser; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-add - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildBanAddDispatch = GatewayGuildBanModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-add - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildBanAddDispatchData = GatewayGuildBanModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-remove - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildBanRemoveDispatch = GatewayGuildBanModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-remove - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildBanRemoveDispatchData = GatewayGuildBanModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#guild-emojis-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildEmojisUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-emojis-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayGuildEmojisUpdateDispatchData { - /** - * ID of the guild - */ - guild_id: Snowflake; - /** - * Array of emojis - * - * See https://discord.com/developers/docs/resources/emoji#emoji-object - */ - emojis: APIEmoji[]; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-stickers-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildStickersUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-stickers-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayGuildStickersUpdateDispatchData { - /** - * ID of the guild - */ - guild_id: Snowflake; - /** - * Array of stickers - * - * See https://discord.com/developers/docs/resources/sticker#sticker-object - */ - stickers: APISticker[]; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-integrations-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildIntegrationsUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-integrations-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayGuildIntegrationsUpdateDispatchData { - /** - * ID of the guild whose integrations were updated - */ - guild_id: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-add - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildMemberAddDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-add - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayGuildMemberAddDispatchData extends APIGuildMember { - /** - * The id of the guild - */ - guild_id: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-remove - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildMemberRemoveDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-remove - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayGuildMemberRemoveDispatchData { - /** - * The id of the guild - */ - guild_id: Snowflake; - /** - * The user who was removed - * - * See https://discord.com/developers/docs/resources/user#user-object - */ - user: APIUser; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildMemberUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildMemberUpdateDispatchData = Omit & Partial> & Required> & Nullable> & { - /** - * The id of the guild - */ - guild_id: Snowflake; -}; -/** - * https://discord.com/developers/docs/topics/gateway#guild-members-chunk - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildMembersChunkDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-members-chunk - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayGuildMembersChunkDispatchData { - /** - * The id of the guild - */ - guild_id: Snowflake; - /** - * Set of guild members - * - * See https://discord.com/developers/docs/resources/guild#guild-member-object - */ - members: APIGuildMember[]; - /** - * The chunk index in the expected chunks for this response (`0 <= chunk_index < chunk_count`) - */ - chunk_index?: number; - /** - * The total number of expected chunks for this response - */ - chunk_count?: number; - /** - * If passing an invalid id to `REQUEST_GUILD_MEMBERS`, it will be returned here - */ - not_found?: unknown[]; - /** - * If passing true to `REQUEST_GUILD_MEMBERS`, presences of the returned members will be here - * - * See https://discord.com/developers/docs/topics/gateway#presence - */ - presences?: RawGatewayPresenceUpdate[]; - /** - * The nonce used in the Guild Members Request - * - * See https://discord.com/developers/docs/topics/gateway#request-guild-members - */ - nonce?: string; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-create - * https://discord.com/developers/docs/topics/gateway#guild-role-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildRoleModifyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-create - * https://discord.com/developers/docs/topics/gateway#guild-role-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayGuildRoleModifyDispatchData { - /** - * The id of the guild - */ - guild_id: Snowflake; - /** - * The role created or updated - * - * See https://discord.com/developers/docs/topics/permissions#role-object - */ - role: APIRole; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-create - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildRoleCreateDispatch = GatewayGuildRoleModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-create - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildRoleCreateDispatchData = GatewayGuildRoleModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildRoleUpdateDispatch = GatewayGuildRoleModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildRoleUpdateDispatchData = GatewayGuildRoleModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-delete - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildRoleDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-delete - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayGuildRoleDeleteDispatchData { - /** - * The id of the guild - */ - guild_id: Snowflake; - /** - * The id of the role - */ - role_id: Snowflake; -} -/** - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildScheduledEventCreateDispatch = DataPayload; -/** - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildScheduledEventCreateDispatchData = APIGuildScheduledEvent; -/** - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildScheduledEventUpdateDispatch = DataPayload; -/** - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildScheduledEventUpdateDispatchData = APIGuildScheduledEvent; -/** - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildScheduledEventDeleteDispatch = DataPayload; -/** - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildScheduledEventDeleteDispatchData = APIGuildScheduledEvent; -/** - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildScheduledEventUserAddDispatch = DataPayload; -/** - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayGuildScheduledEventUserAddDispatchData { - guild_scheduled_event_id: Snowflake; - user_id: Snowflake; - guild_id: Snowflake; -} -/** - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayGuildScheduledEventUserRemoveDispatch = DataPayload; -/** - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayGuildScheduledEventUserRemoveDispatchData { - guild_scheduled_event_id: Snowflake; - user_id: Snowflake; - guild_id: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#integration-create - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayIntegrationCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#integration-create - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayIntegrationCreateDispatchData = APIGuildIntegration & { - guild_id: Snowflake; -}; -/** - * https://discord.com/developers/docs/topics/gateway#integration-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayIntegrationUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#integration-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayIntegrationUpdateDispatchData = APIGuildIntegration & { - guild_id: Snowflake; -}; -/** - * https://discord.com/developers/docs/topics/gateway#integration-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayIntegrationDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#integration-delete - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayIntegrationDeleteDispatchData { - /** - * Integration id - */ - id: Snowflake; - /** - * ID of the guild - */ - guild_id: Snowflake; - /** - * ID of the bot/OAuth2 application for this Discord integration - */ - application_id?: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#interaction-create - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayInteractionCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#interaction-create - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayInteractionCreateDispatchData = APIInteraction; -/** - * https://discord.com/developers/docs/topics/gateway#invite-create - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayInviteCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#invite-create - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayInviteCreateDispatchData { - /** - * The channel the invite is for - */ - channel_id: Snowflake; - /** - * The unique invite code - * - * See https://discord.com/developers/docs/resources/invite#invite-object - */ - code: string; - /** - * The time at which the invite was created - */ - created_at: number; - /** - * The guild of the invite - */ - guild_id?: Snowflake; - /** - * The user that created the invite - * - * See https://discord.com/developers/docs/resources/user#user-object - */ - inviter?: APIUser; - /** - * How long the invite is valid for (in seconds) - */ - max_age: number; - /** - * The maximum number of times the invite can be used - */ - max_uses: number; - /** - * The type of target for this voice channel invite - * - * See https://discord.com/developers/docs/resources/invite#invite-object-invite-target-types - */ - target_type?: InviteTargetType; - /** - * The user whose stream to display for this voice channel stream invite - * - * See https://discord.com/developers/docs/resources/user#user-object - */ - target_user?: APIUser; - /** - * The embedded application to open for this voice channel embedded application invite - */ - target_application?: Partial; - /** - * Whether or not the invite is temporary (invited users will be kicked on disconnect unless they're assigned a role) - */ - temporary: boolean; - /** - * How many times the invite has been used (always will be `0`) - */ - uses: 0; -} -/** - * https://discord.com/developers/docs/topics/gateway#invite-delete - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayInviteDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#invite-delete - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayInviteDeleteDispatchData { - /** - * The channel of the invite - */ - channel_id: Snowflake; - /** - * The guild of the invite - */ - guild_id?: Snowflake; - /** - * The unique invite code - * - * See https://discord.com/developers/docs/resources/invite#invite-object - */ - code: string; -} -/** - * https://discord.com/developers/docs/topics/gateway#message-create - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayMessageCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-create - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayMessageCreateDispatchData = APIMessage; -/** - * https://discord.com/developers/docs/topics/gateway#message-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayMessageUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayMessageUpdateDispatchData = { - id: Snowflake; - channel_id: Snowflake; -} & Partial; -/** - * https://discord.com/developers/docs/topics/gateway#message-delete - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayMessageDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-delete - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayMessageDeleteDispatchData { - /** - * The id of the message - */ - id: Snowflake; - /** - * The id of the channel - */ - channel_id: Snowflake; - /** - * The id of the guild - */ - guild_id?: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#message-delete-bulk - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayMessageDeleteBulkDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-delete-bulk - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayMessageDeleteBulkDispatchData { - /** - * The ids of the messages - */ - ids: Snowflake[]; - /** - * The id of the channel - */ - channel_id: Snowflake; - /** - * The id of the guild - */ - guild_id?: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-add - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayMessageReactionAddDispatch = ReactionData; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-add - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayMessageReactionAddDispatchData = GatewayMessageReactionAddDispatch['d']; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayMessageReactionRemoveDispatch = ReactionData; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayMessageReactionRemoveDispatchData = GatewayMessageReactionRemoveDispatch['d']; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-all - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayMessageReactionRemoveAllDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-all - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayMessageReactionRemoveAllDispatchData = MessageReactionRemoveData; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-emoji - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayMessageReactionRemoveEmojiDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-emoji - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayMessageReactionRemoveEmojiDispatchData extends MessageReactionRemoveData { - /** - * The emoji that was removed - */ - emoji: APIEmoji; -} -/** - * https://discord.com/developers/docs/topics/gateway#presence-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayPresenceUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#presence-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayPresenceUpdateDispatchData = RawGatewayPresenceUpdate; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-create - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayStageInstanceCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-create - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayStageInstanceCreateDispatchData = APIStageInstance; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-delete - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayStageInstanceDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-delete - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayStageInstanceDeleteDispatchData = APIStageInstance; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayStageInstanceUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayStageInstanceUpdateDispatchData = APIStageInstance; -/** - * https://discord.com/developers/docs/topics/gateway#typing-start - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayTypingStartDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#typing-start - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayTypingStartDispatchData { - /** - * The id of the channel - */ - channel_id: Snowflake; - /** - * The id of the guild - */ - guild_id?: Snowflake; - /** - * The id of the user - */ - user_id: Snowflake; - /** - * Unix time (in seconds) of when the user started typing - */ - timestamp: number; - /** - * The member who started typing if this happened in a guild - * - * See https://discord.com/developers/docs/resources/guild#guild-member-object - */ - member?: APIGuildMember; -} -/** - * https://discord.com/developers/docs/topics/gateway#user-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayUserUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#user-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayUserUpdateDispatchData = APIUser; -/** - * https://discord.com/developers/docs/topics/gateway#voice-state-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayVoiceStateUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#voice-state-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayVoiceStateUpdateDispatchData = GatewayVoiceState; -/** - * https://discord.com/developers/docs/topics/gateway#voice-server-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayVoiceServerUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#voice-server-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayVoiceServerUpdateDispatchData { - /** - * Voice connection token - */ - token: string; - /** - * The guild this voice server update is for - */ - guild_id: Snowflake; - /** - * The voice server host - * - * A `null` endpoint means that the voice server allocated has gone away and is trying to be reallocated. - * You should attempt to disconnect from the currently connected voice server, and not attempt to reconnect - * until a new voice server is allocated - */ - endpoint: string | null; -} -/** - * https://discord.com/developers/docs/topics/gateway#webhooks-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayWebhooksUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#webhooks-update - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayWebhooksUpdateDispatchData { - /** - * The id of the guild - */ - guild_id: Snowflake; - /** - * The id of the channel - */ - channel_id: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#heartbeating - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayHeartbeat { - op: GatewayOpcodes.Heartbeat; - d: GatewayHeartbeatData; -} -/** - * https://discord.com/developers/docs/topics/gateway#heartbeating - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayHeartbeatData = number | null; -/** - * https://discord.com/developers/docs/topics/gateway#identify - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayIdentify { - op: GatewayOpcodes.Identify; - d: GatewayIdentifyData; -} -/** - * https://discord.com/developers/docs/topics/gateway#identify - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayIdentifyData { - /** - * Authentication token - */ - token: string; - /** - * Connection properties - * - * See https://discord.com/developers/docs/topics/gateway#identify-identify-connection-properties - */ - properties: GatewayIdentifyProperties; - /** - * Whether this connection supports compression of packets - * - * @default false - */ - compress?: boolean; - /** - * Value between 50 and 250, total number of members where the gateway will stop sending - * offline members in the guild member list - * - * @default 50 - */ - large_threshold?: number; - /** - * Used for Guild Sharding - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - shard?: [shard_id: number, shard_count: number]; - /** - * Presence structure for initial presence information - * - * See https://discord.com/developers/docs/topics/gateway#update-presence - */ - presence?: GatewayPresenceUpdateData; - /** - * The Gateway Intents you wish to receive - * - * See https://discord.com/developers/docs/topics/gateway#gateway-intents - */ - intents: number; -} -/** - * https://discord.com/developers/docs/topics/gateway#identify-identify-connection-properties - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayIdentifyProperties { - /** - * Your operating system - */ - $os: string; - /** - * Your library name - */ - $browser: string; - /** - * Your library name - */ - $device: string; -} -/** - * https://discord.com/developers/docs/topics/gateway#resume - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayResume { - op: GatewayOpcodes.Resume; - d: GatewayResumeData; -} -/** - * https://discord.com/developers/docs/topics/gateway#resume - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayResumeData { - /** - * Session token - */ - token: string; - /** - * Session id - */ - session_id: string; - /** - * Last sequence number received - */ - seq: number; -} -/** - * https://discord.com/developers/docs/topics/gateway#request-guild-members - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayRequestGuildMembers { - op: GatewayOpcodes.RequestGuildMembers; - d: GatewayRequestGuildMembersData; -} -/** - * https://discord.com/developers/docs/topics/gateway#request-guild-members - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayRequestGuildMembersData { - /** - * ID of the guild to get members for - */ - guild_id: Snowflake; - /** - * String that username starts with, or an empty string to return all members - */ - query?: string; - /** - * Maximum number of members to send matching the `query`; - * a limit of `0` can be used with an empty string `query` to return all members - */ - limit: number; - /** - * Used to specify if we want the presences of the matched members - */ - presences?: boolean; - /** - * Used to specify which users you wish to fetch - */ - user_ids?: Snowflake | Snowflake[]; - /** - * Nonce to identify the Guild Members Chunk response - * - * Nonce can only be up to 32 bytes. If you send an invalid nonce it will be ignored and the reply member_chunk(s) will not have a `nonce` set. - * - * See https://discord.com/developers/docs/topics/gateway#guild-members-chunk - */ - nonce?: string; -} -/** - * https://discord.com/developers/docs/topics/gateway#update-voice-state - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayVoiceStateUpdate { - op: GatewayOpcodes.VoiceStateUpdate; - d: GatewayVoiceStateUpdateData; -} -/** - * https://discord.com/developers/docs/topics/gateway#update-voice-state - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayVoiceStateUpdateData { - /** - * ID of the guild - */ - guild_id: Snowflake; - /** - * ID of the voice channel client wants to join (`null` if disconnecting) - */ - channel_id: Snowflake | null; - /** - * Is the client muted - */ - self_mute: boolean; - /** - * Is the client deafened - */ - self_deaf: boolean; -} -/** - * https://discord.com/developers/docs/topics/gateway#update-presence - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayUpdatePresence { - op: GatewayOpcodes.PresenceUpdate; - d: GatewayPresenceUpdateData; -} -/** - * https://discord.com/developers/docs/topics/gateway#update-presence-gateway-presence-update-structure - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export interface GatewayPresenceUpdateData { - /** - * Unix time (in milliseconds) of when the client went idle, or `null` if the client is not idle - */ - since: number | null; - /** - * The user's activities - * - * See https://discord.com/developers/docs/topics/gateway#activity-object - */ - activities: GatewayActivityUpdateData[]; - /** - * The user's new status - * - * See https://discord.com/developers/docs/topics/gateway#update-presence-status-types - */ - status: PresenceUpdateStatus; - /** - * Whether or not the client is afk - */ - afk: boolean; -} -/** - * https://discord.com/developers/docs/topics/gateway#activity-object-activity-structure - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -export declare type GatewayActivityUpdateData = Pick; -interface BasePayload { - /** - * Opcode for the payload - */ - op: GatewayOpcodes; - /** - * Event data - */ - d?: unknown; - /** - * Sequence number, used for resuming sessions and heartbeats - */ - s: number; - /** - * The event name for this payload - */ - t?: string; -} -declare type NonDispatchPayload = Omit & { - t: null; - s: null; -}; -interface DataPayload extends BasePayload { - op: GatewayOpcodes.Dispatch; - t: Event; - d: D; -} -declare type ReactionData = DataPayload>; -/** - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -interface MessageReactionRemoveData { - /** - * The id of the channel - */ - channel_id: Snowflake; - /** - * The id of the message - */ - message_id: Snowflake; - /** - * The id of the guild - */ - guild_id?: Snowflake; -} -//# sourceMappingURL=v8.d.ts.map \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v8.d.ts.map b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v8.d.ts.map deleted file mode 100644 index 0ded498..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v8.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"v8.d.ts","sourceRoot":"","sources":["v8.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,KAAK,EACX,cAAc,EACd,UAAU,EACV,QAAQ,EACR,QAAQ,EACR,mBAAmB,EACnB,cAAc,EACd,sBAAsB,EACtB,cAAc,EACd,UAAU,EACV,OAAO,EACP,gBAAgB,EAChB,UAAU,EACV,mBAAmB,EACnB,OAAO,EACP,eAAe,EACf,qBAAqB,IAAI,wBAAwB,EACjD,iBAAiB,EACjB,gBAAgB,EAChB,oBAAoB,EACpB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,oBAAoB,CAAC;AAEnD,cAAc,UAAU,CAAC;AAEzB;;GAEG;AACH,eAAO,MAAM,cAAc,MAAM,CAAC;AAElC;;;GAGG;AACH,oBAAY,cAAc;IACzB;;OAEG;IACH,QAAQ,IAAA;IACR;;;OAGG;IACH,SAAS,IAAA;IACT;;OAEG;IACH,QAAQ,IAAA;IACR;;OAEG;IACH,cAAc,IAAA;IACd;;OAEG;IACH,gBAAgB,IAAA;IAChB;;OAEG;IACH,MAAM,IAAI;IACV;;OAEG;IACH,SAAS,IAAA;IACT;;OAEG;IACH,mBAAmB,IAAA;IACnB;;OAEG;IACH,cAAc,IAAA;IACd;;OAEG;IACH,KAAK,KAAA;IACL;;OAEG;IACH,YAAY,KAAA;CACZ;AAED;;;GAGG;AACH,oBAAY,iBAAiB;IAC5B;;OAEG;IACH,YAAY,OAAO;IACnB;;;;OAIG;IACH,aAAa,OAAA;IACb;;;;OAIG;IACH,WAAW,OAAA;IACX;;;;OAIG;IACH,gBAAgB,OAAA;IAChB;;;;OAIG;IACH,oBAAoB,OAAA;IACpB;;OAEG;IACH,oBAAoB,OAAA;IACpB;;;;OAIG;IACH,UAAU,OAAO;IACjB;;O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IACH,KAAK,EAAE,QAAQ,CAAC;CAChB,EACD,CAAC,CACD,CACD,CAAC;AAEF;;GAEG;AACH,UAAU,yBAAyB;IAClC;;OAEG;IACH,UAAU,EAAE,SAAS,CAAC;IACtB;;OAEG;IACH,UAAU,EAAE,SAAS,CAAC;IACtB;;OAEG;IACH,QAAQ,CAAC,EAAE,SAAS,CAAC;CACrB"} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v8.js b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v8.js deleted file mode 100644 index f07761b..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v8.js +++ /dev/null @@ -1,242 +0,0 @@ -"use strict"; -/** - * Types extracted from https://discord.com/developers/docs/topics/gateway - */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GatewayDispatchEvents = exports.GatewayIntentBits = exports.GatewayCloseCodes = exports.GatewayOpcodes = exports.GatewayVersion = void 0; -__exportStar(require("./common"), exports); -/** - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -exports.GatewayVersion = '8'; -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-opcodes - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -var GatewayOpcodes; -(function (GatewayOpcodes) { - /** - * An event was dispatched - */ - GatewayOpcodes[GatewayOpcodes["Dispatch"] = 0] = "Dispatch"; - /** - * A bidirectional opcode to maintain an active gateway connection. - * Fired periodically by the client, or fired by the gateway to request an immediate heartbeat from the client. - */ - GatewayOpcodes[GatewayOpcodes["Heartbeat"] = 1] = "Heartbeat"; - /** - * Starts a new session during the initial handshake - */ - GatewayOpcodes[GatewayOpcodes["Identify"] = 2] = "Identify"; - /** - * Update the client's presence - */ - GatewayOpcodes[GatewayOpcodes["PresenceUpdate"] = 3] = "PresenceUpdate"; - /** - * Used to join/leave or move between voice channels - */ - GatewayOpcodes[GatewayOpcodes["VoiceStateUpdate"] = 4] = "VoiceStateUpdate"; - /** - * Resume a previous session that was disconnected - */ - GatewayOpcodes[GatewayOpcodes["Resume"] = 6] = "Resume"; - /** - * You should attempt to reconnect and resume immediately - */ - GatewayOpcodes[GatewayOpcodes["Reconnect"] = 7] = "Reconnect"; - /** - * Request information about offline guild members in a large guild - */ - GatewayOpcodes[GatewayOpcodes["RequestGuildMembers"] = 8] = "RequestGuildMembers"; - /** - * The session has been invalidated. You should reconnect and identify/resume accordingly - */ - GatewayOpcodes[GatewayOpcodes["InvalidSession"] = 9] = "InvalidSession"; - /** - * Sent immediately after connecting, contains the `heartbeat_interval` to use - */ - GatewayOpcodes[GatewayOpcodes["Hello"] = 10] = "Hello"; - /** - * Sent in response to receiving a heartbeat to acknowledge that it has been received - */ - GatewayOpcodes[GatewayOpcodes["HeartbeatAck"] = 11] = "HeartbeatAck"; -})(GatewayOpcodes = exports.GatewayOpcodes || (exports.GatewayOpcodes = {})); -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-close-event-codes - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -var GatewayCloseCodes; -(function (GatewayCloseCodes) { - /** - * We're not sure what went wrong. Try reconnecting? - */ - GatewayCloseCodes[GatewayCloseCodes["UnknownError"] = 4000] = "UnknownError"; - /** - * You sent an invalid Gateway opcode or an invalid payload for an opcode. Don't do that! - * - * See https://discord.com/developers/docs/topics/gateway#payloads-and-opcodes - */ - GatewayCloseCodes[GatewayCloseCodes["UnknownOpcode"] = 4001] = "UnknownOpcode"; - /** - * You sent an invalid payload to us. Don't do that! - * - * See https://discord.com/developers/docs/topics/gateway#sending-payloads - */ - GatewayCloseCodes[GatewayCloseCodes["DecodeError"] = 4002] = "DecodeError"; - /** - * You sent us a payload prior to identifying - * - * See https://discord.com/developers/docs/topics/gateway#identify - */ - GatewayCloseCodes[GatewayCloseCodes["NotAuthenticated"] = 4003] = "NotAuthenticated"; - /** - * The account token sent with your identify payload is incorrect - * - * See https://discord.com/developers/docs/topics/gateway#identify - */ - GatewayCloseCodes[GatewayCloseCodes["AuthenticationFailed"] = 4004] = "AuthenticationFailed"; - /** - * You sent more than one identify payload. Don't do that! - */ - GatewayCloseCodes[GatewayCloseCodes["AlreadyAuthenticated"] = 4005] = "AlreadyAuthenticated"; - /** - * The sequence sent when resuming the session was invalid. Reconnect and start a new session - * - * See https://discord.com/developers/docs/topics/gateway#resume - */ - GatewayCloseCodes[GatewayCloseCodes["InvalidSeq"] = 4007] = "InvalidSeq"; - /** - * Woah nelly! You're sending payloads to us too quickly. Slow it down! You will be disconnected on receiving this - */ - GatewayCloseCodes[GatewayCloseCodes["RateLimited"] = 4008] = "RateLimited"; - /** - * Your session timed out. Reconnect and start a new one - */ - GatewayCloseCodes[GatewayCloseCodes["SessionTimedOut"] = 4009] = "SessionTimedOut"; - /** - * You sent us an invalid shard when identifying - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - GatewayCloseCodes[GatewayCloseCodes["InvalidShard"] = 4010] = "InvalidShard"; - /** - * The session would have handled too many guilds - you are required to shard your connection in order to connect - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - GatewayCloseCodes[GatewayCloseCodes["ShardingRequired"] = 4011] = "ShardingRequired"; - /** - * You sent an invalid version for the gateway - */ - GatewayCloseCodes[GatewayCloseCodes["InvalidAPIVersion"] = 4012] = "InvalidAPIVersion"; - /** - * You sent an invalid intent for a Gateway Intent. You may have incorrectly calculated the bitwise value - * - * See https://discord.com/developers/docs/topics/gateway#gateway-intents - */ - GatewayCloseCodes[GatewayCloseCodes["InvalidIntents"] = 4013] = "InvalidIntents"; - /** - * You sent a disallowed intent for a Gateway Intent. You may have tried to specify an intent that you have not - * enabled or are not whitelisted for - * - * See https://discord.com/developers/docs/topics/gateway#gateway-intents - * - * See https://discord.com/developers/docs/topics/gateway#privileged-intents - */ - GatewayCloseCodes[GatewayCloseCodes["DisallowedIntents"] = 4014] = "DisallowedIntents"; -})(GatewayCloseCodes = exports.GatewayCloseCodes || (exports.GatewayCloseCodes = {})); -/** - * https://discord.com/developers/docs/topics/gateway#list-of-intents - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -var GatewayIntentBits; -(function (GatewayIntentBits) { - GatewayIntentBits[GatewayIntentBits["Guilds"] = 1] = "Guilds"; - GatewayIntentBits[GatewayIntentBits["GuildMembers"] = 2] = "GuildMembers"; - GatewayIntentBits[GatewayIntentBits["GuildBans"] = 4] = "GuildBans"; - GatewayIntentBits[GatewayIntentBits["GuildEmojisAndStickers"] = 8] = "GuildEmojisAndStickers"; - GatewayIntentBits[GatewayIntentBits["GuildIntegrations"] = 16] = "GuildIntegrations"; - GatewayIntentBits[GatewayIntentBits["GuildWebhooks"] = 32] = "GuildWebhooks"; - GatewayIntentBits[GatewayIntentBits["GuildInvites"] = 64] = "GuildInvites"; - GatewayIntentBits[GatewayIntentBits["GuildVoiceStates"] = 128] = "GuildVoiceStates"; - GatewayIntentBits[GatewayIntentBits["GuildPresences"] = 256] = "GuildPresences"; - GatewayIntentBits[GatewayIntentBits["GuildMessages"] = 512] = "GuildMessages"; - GatewayIntentBits[GatewayIntentBits["GuildMessageReactions"] = 1024] = "GuildMessageReactions"; - GatewayIntentBits[GatewayIntentBits["GuildMessageTyping"] = 2048] = "GuildMessageTyping"; - GatewayIntentBits[GatewayIntentBits["DirectMessages"] = 4096] = "DirectMessages"; - GatewayIntentBits[GatewayIntentBits["DirectMessageReactions"] = 8192] = "DirectMessageReactions"; - GatewayIntentBits[GatewayIntentBits["DirectMessageTyping"] = 16384] = "DirectMessageTyping"; - GatewayIntentBits[GatewayIntentBits["GuildScheduledEvents"] = 65536] = "GuildScheduledEvents"; -})(GatewayIntentBits = exports.GatewayIntentBits || (exports.GatewayIntentBits = {})); -/** - * https://discord.com/developers/docs/topics/gateway#commands-and-events-gateway-events - * @deprecated API and gateway v8 are deprecated and the types will not receive further updates, please update to v10. - */ -var GatewayDispatchEvents; -(function (GatewayDispatchEvents) { - GatewayDispatchEvents["ChannelCreate"] = "CHANNEL_CREATE"; - GatewayDispatchEvents["ChannelDelete"] = "CHANNEL_DELETE"; - GatewayDispatchEvents["ChannelPinsUpdate"] = "CHANNEL_PINS_UPDATE"; - GatewayDispatchEvents["ChannelUpdate"] = "CHANNEL_UPDATE"; - GatewayDispatchEvents["GuildBanAdd"] = "GUILD_BAN_ADD"; - GatewayDispatchEvents["GuildBanRemove"] = "GUILD_BAN_REMOVE"; - GatewayDispatchEvents["GuildCreate"] = "GUILD_CREATE"; - GatewayDispatchEvents["GuildDelete"] = "GUILD_DELETE"; - GatewayDispatchEvents["GuildEmojisUpdate"] = "GUILD_EMOJIS_UPDATE"; - GatewayDispatchEvents["GuildIntegrationsUpdate"] = "GUILD_INTEGRATIONS_UPDATE"; - GatewayDispatchEvents["GuildMemberAdd"] = "GUILD_MEMBER_ADD"; - GatewayDispatchEvents["GuildMemberRemove"] = "GUILD_MEMBER_REMOVE"; - GatewayDispatchEvents["GuildMembersChunk"] = "GUILD_MEMBERS_CHUNK"; - GatewayDispatchEvents["GuildMemberUpdate"] = "GUILD_MEMBER_UPDATE"; - GatewayDispatchEvents["GuildRoleCreate"] = "GUILD_ROLE_CREATE"; - GatewayDispatchEvents["GuildRoleDelete"] = "GUILD_ROLE_DELETE"; - GatewayDispatchEvents["GuildRoleUpdate"] = "GUILD_ROLE_UPDATE"; - GatewayDispatchEvents["GuildStickersUpdate"] = "GUILD_STICKERS_UPDATE"; - GatewayDispatchEvents["GuildUpdate"] = "GUILD_UPDATE"; - GatewayDispatchEvents["IntegrationCreate"] = "INTEGRATION_CREATE"; - GatewayDispatchEvents["IntegrationDelete"] = "INTEGRATION_DELETE"; - GatewayDispatchEvents["IntegrationUpdate"] = "INTEGRATION_UPDATE"; - GatewayDispatchEvents["InteractionCreate"] = "INTERACTION_CREATE"; - GatewayDispatchEvents["InviteCreate"] = "INVITE_CREATE"; - GatewayDispatchEvents["InviteDelete"] = "INVITE_DELETE"; - GatewayDispatchEvents["MessageCreate"] = "MESSAGE_CREATE"; - GatewayDispatchEvents["MessageDelete"] = "MESSAGE_DELETE"; - GatewayDispatchEvents["MessageDeleteBulk"] = "MESSAGE_DELETE_BULK"; - GatewayDispatchEvents["MessageReactionAdd"] = "MESSAGE_REACTION_ADD"; - GatewayDispatchEvents["MessageReactionRemove"] = "MESSAGE_REACTION_REMOVE"; - GatewayDispatchEvents["MessageReactionRemoveAll"] = "MESSAGE_REACTION_REMOVE_ALL"; - GatewayDispatchEvents["MessageReactionRemoveEmoji"] = "MESSAGE_REACTION_REMOVE_EMOJI"; - GatewayDispatchEvents["MessageUpdate"] = "MESSAGE_UPDATE"; - GatewayDispatchEvents["PresenceUpdate"] = "PRESENCE_UPDATE"; - GatewayDispatchEvents["StageInstanceCreate"] = "STAGE_INSTANCE_CREATE"; - GatewayDispatchEvents["StageInstanceDelete"] = "STAGE_INSTANCE_DELETE"; - GatewayDispatchEvents["StageInstanceUpdate"] = "STAGE_INSTANCE_UPDATE"; - GatewayDispatchEvents["Ready"] = "READY"; - GatewayDispatchEvents["Resumed"] = "RESUMED"; - GatewayDispatchEvents["TypingStart"] = "TYPING_START"; - GatewayDispatchEvents["UserUpdate"] = "USER_UPDATE"; - GatewayDispatchEvents["VoiceServerUpdate"] = "VOICE_SERVER_UPDATE"; - GatewayDispatchEvents["VoiceStateUpdate"] = "VOICE_STATE_UPDATE"; - GatewayDispatchEvents["WebhooksUpdate"] = "WEBHOOKS_UPDATE"; - GatewayDispatchEvents["GuildScheduledEventCreate"] = "GUILD_SCHEDULED_EVENT_CREATE"; - GatewayDispatchEvents["GuildScheduledEventUpdate"] = "GUILD_SCHEDULED_EVENT_UPDATE"; - GatewayDispatchEvents["GuildScheduledEventDelete"] = "GUILD_SCHEDULED_EVENT_DELETE"; - GatewayDispatchEvents["GuildScheduledEventUserAdd"] = "GUILD_SCHEDULED_EVENT_USER_ADD"; - GatewayDispatchEvents["GuildScheduledEventUserRemove"] = "GUILD_SCHEDULED_EVENT_USER_REMOVE"; -})(GatewayDispatchEvents = exports.GatewayDispatchEvents || (exports.GatewayDispatchEvents = {})); -// #endregion Shared -//# sourceMappingURL=v8.js.map \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v8.js.map b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v8.js.map deleted file mode 100644 index ada6a2d..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v8.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"v8.js","sourceRoot":"","sources":["v8.ts"],"names":[],"mappings":";AAAA;;GAEG;;;;;;;;;;;;;;;;;AA0BH,2CAAyB;AAEzB;;GAEG;AACU,QAAA,cAAc,GAAG,GAAG,CAAC;AAElC;;;GAGG;AACH,IAAY,cA8CX;AA9CD,WAAY,cAAc;IACzB;;OAEG;IACH,2DAAQ,CAAA;IACR;;;OAGG;IACH,6DAAS,CAAA;IACT;;OAEG;IACH,2DAAQ,CAAA;IACR;;OAEG;IACH,uEAAc,CAAA;IACd;;OAEG;IACH,2EAAgB,CAAA;IAChB;;OAEG;IACH,uDAAU,CAAA;IACV;;OAEG;IACH,6DAAS,CAAA;IACT;;OAEG;IACH,iFAAmB,CAAA;IACnB;;OAEG;IACH,uEAAc,CAAA;IACd;;OAEG;IACH,sDAAK,CAAA;IACL;;OAEG;IACH,oEAAY,CAAA;AACb,CAAC,E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,sDAA6B,CAAA;IAC7B,4DAAmC,CAAA;IACnC,qDAA4B,CAAA;IAC5B,qDAA4B,CAAA;IAC5B,kEAAyC,CAAA;IACzC,8EAAqD,CAAA;IACrD,4DAAmC,CAAA;IACnC,kEAAyC,CAAA;IACzC,kEAAyC,CAAA;IACzC,kEAAyC,CAAA;IACzC,8DAAqC,CAAA;IACrC,8DAAqC,CAAA;IACrC,8DAAqC,CAAA;IACrC,sEAA6C,CAAA;IAC7C,qDAA4B,CAAA;IAC5B,iEAAwC,CAAA;IACxC,iEAAwC,CAAA;IACxC,iEAAwC,CAAA;IACxC,iEAAwC,CAAA;IACxC,uDAA8B,CAAA;IAC9B,uDAA8B,CAAA;IAC9B,yDAAgC,CAAA;IAChC,yDAAgC,CAAA;IAChC,kEAAyC,CAAA;IACzC,oEAA2C,CAAA;IAC3C,0EAAiD,CAAA;IACjD,iFAAwD,CAAA;IACxD,qFAA4D,CAAA;IAC5D,yDAAgC,CAAA;IAChC,2DAAkC,CAAA;IAClC,sEAA6C,CAAA;IAC7C,sEAA6C,CAAA;IAC7C,sEAA6C,CAAA;IAC7C,wCAAe,CAAA;IACf,4CAAmB,CAAA;IACnB,qDAA4B,CAAA;IAC5B,mDAA0B,CAAA;IAC1B,kEAAyC,CAAA;IACzC,gEAAuC,CAAA;IACvC,2DAAkC,CAAA;IAClC,mFAA0D,CAAA;IAC1D,mFAA0D,CAAA;IAC1D,mFAA0D,CAAA;IAC1D,sFAA6D,CAAA;IAC7D,4FAAmE,CAAA;AACpE,CAAC,EAlDW,qBAAqB,GAArB,6BAAqB,KAArB,6BAAqB,QAkDhC;AA4gDD,oBAAoB"} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v8.mjs b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v8.mjs deleted file mode 100644 index c5cfed1..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v8.mjs +++ /dev/null @@ -1,8 +0,0 @@ -import mod from "./v8.js"; - -export default mod; -export const GatewayCloseCodes = mod.GatewayCloseCodes; -export const GatewayDispatchEvents = mod.GatewayDispatchEvents; -export const GatewayIntentBits = mod.GatewayIntentBits; -export const GatewayOpcodes = mod.GatewayOpcodes; -export const GatewayVersion = mod.GatewayVersion; diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v9.d.ts b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v9.d.ts deleted file mode 100644 index 385d7f1..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v9.d.ts +++ /dev/null @@ -1,1470 +0,0 @@ -/** - * Types extracted from https://discord.com/developers/docs/topics/gateway - */ -import type { Snowflake } from '../globals'; -import type { GatewayPresenceUpdate } from '../payloads/v9/gateway'; -import type { APIApplication, APIChannel, APIEmoji, APIGuild, APIGuildIntegration, APIGuildMember, APIGuildScheduledEvent, APIInteraction, APIMessage, APIRole, APIStageInstance, APISticker, APIThreadChannel, APIThreadMember, APIUnavailableGuild, APIUser, GatewayActivity, GatewayPresenceUpdate as RawGatewayPresenceUpdate, GatewayThreadListSync as RawGatewayThreadListSync, GatewayThreadMembersUpdate as RawGatewayThreadMembersUpdate, GatewayVoiceState, InviteTargetType, PresenceUpdateStatus } from '../payloads/v9/index'; -import type { Nullable } from '../utils/internals'; -export * from './common'; -export declare const GatewayVersion = "9"; -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-opcodes - */ -export declare enum GatewayOpcodes { - /** - * An event was dispatched - */ - Dispatch = 0, - /** - * A bidirectional opcode to maintain an active gateway connection. - * Fired periodically by the client, or fired by the gateway to request an immediate heartbeat from the client. - */ - Heartbeat = 1, - /** - * Starts a new session during the initial handshake - */ - Identify = 2, - /** - * Update the client's presence - */ - PresenceUpdate = 3, - /** - * Used to join/leave or move between voice channels - */ - VoiceStateUpdate = 4, - /** - * Resume a previous session that was disconnected - */ - Resume = 6, - /** - * You should attempt to reconnect and resume immediately - */ - Reconnect = 7, - /** - * Request information about offline guild members in a large guild - */ - RequestGuildMembers = 8, - /** - * The session has been invalidated. You should reconnect and identify/resume accordingly - */ - InvalidSession = 9, - /** - * Sent immediately after connecting, contains the `heartbeat_interval` to use - */ - Hello = 10, - /** - * Sent in response to receiving a heartbeat to acknowledge that it has been received - */ - HeartbeatAck = 11 -} -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-close-event-codes - */ -export declare enum GatewayCloseCodes { - /** - * We're not sure what went wrong. Try reconnecting? - */ - UnknownError = 4000, - /** - * You sent an invalid Gateway opcode or an invalid payload for an opcode. Don't do that! - * - * See https://discord.com/developers/docs/topics/gateway#payloads-and-opcodes - */ - UnknownOpcode = 4001, - /** - * You sent an invalid payload to us. Don't do that! - * - * See https://discord.com/developers/docs/topics/gateway#sending-payloads - */ - DecodeError = 4002, - /** - * You sent us a payload prior to identifying - * - * See https://discord.com/developers/docs/topics/gateway#identify - */ - NotAuthenticated = 4003, - /** - * The account token sent with your identify payload is incorrect - * - * See https://discord.com/developers/docs/topics/gateway#identify - */ - AuthenticationFailed = 4004, - /** - * You sent more than one identify payload. Don't do that! - */ - AlreadyAuthenticated = 4005, - /** - * The sequence sent when resuming the session was invalid. Reconnect and start a new session - * - * See https://discord.com/developers/docs/topics/gateway#resume - */ - InvalidSeq = 4007, - /** - * Woah nelly! You're sending payloads to us too quickly. Slow it down! You will be disconnected on receiving this - */ - RateLimited = 4008, - /** - * Your session timed out. Reconnect and start a new one - */ - SessionTimedOut = 4009, - /** - * You sent us an invalid shard when identifying - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - InvalidShard = 4010, - /** - * The session would have handled too many guilds - you are required to shard your connection in order to connect - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - ShardingRequired = 4011, - /** - * You sent an invalid version for the gateway - */ - InvalidAPIVersion = 4012, - /** - * You sent an invalid intent for a Gateway Intent. You may have incorrectly calculated the bitwise value - * - * See https://discord.com/developers/docs/topics/gateway#gateway-intents - */ - InvalidIntents = 4013, - /** - * You sent a disallowed intent for a Gateway Intent. You may have tried to specify an intent that you have not - * enabled or are not whitelisted for - * - * See https://discord.com/developers/docs/topics/gateway#gateway-intents - * - * See https://discord.com/developers/docs/topics/gateway#privileged-intents - */ - DisallowedIntents = 4014 -} -/** - * https://discord.com/developers/docs/topics/gateway#list-of-intents - */ -export declare enum GatewayIntentBits { - Guilds = 1, - GuildMembers = 2, - GuildBans = 4, - GuildEmojisAndStickers = 8, - GuildIntegrations = 16, - GuildWebhooks = 32, - GuildInvites = 64, - GuildVoiceStates = 128, - GuildPresences = 256, - GuildMessages = 512, - GuildMessageReactions = 1024, - GuildMessageTyping = 2048, - DirectMessages = 4096, - DirectMessageReactions = 8192, - DirectMessageTyping = 16384, - GuildScheduledEvents = 65536 -} -/** - * https://discord.com/developers/docs/topics/gateway#commands-and-events-gateway-events - */ -export declare enum GatewayDispatchEvents { - ApplicationCommandPermissionsUpdate = "APPLICATION_COMMAND_PERMISSIONS_UPDATE", - ChannelCreate = "CHANNEL_CREATE", - ChannelDelete = "CHANNEL_DELETE", - ChannelPinsUpdate = "CHANNEL_PINS_UPDATE", - ChannelUpdate = "CHANNEL_UPDATE", - GuildBanAdd = "GUILD_BAN_ADD", - GuildBanRemove = "GUILD_BAN_REMOVE", - GuildCreate = "GUILD_CREATE", - GuildDelete = "GUILD_DELETE", - GuildEmojisUpdate = "GUILD_EMOJIS_UPDATE", - GuildIntegrationsUpdate = "GUILD_INTEGRATIONS_UPDATE", - GuildMemberAdd = "GUILD_MEMBER_ADD", - GuildMemberRemove = "GUILD_MEMBER_REMOVE", - GuildMembersChunk = "GUILD_MEMBERS_CHUNK", - GuildMemberUpdate = "GUILD_MEMBER_UPDATE", - GuildRoleCreate = "GUILD_ROLE_CREATE", - GuildRoleDelete = "GUILD_ROLE_DELETE", - GuildRoleUpdate = "GUILD_ROLE_UPDATE", - GuildStickersUpdate = "GUILD_STICKERS_UPDATE", - GuildUpdate = "GUILD_UPDATE", - IntegrationCreate = "INTEGRATION_CREATE", - IntegrationDelete = "INTEGRATION_DELETE", - IntegrationUpdate = "INTEGRATION_UPDATE", - InteractionCreate = "INTERACTION_CREATE", - InviteCreate = "INVITE_CREATE", - InviteDelete = "INVITE_DELETE", - MessageCreate = "MESSAGE_CREATE", - MessageDelete = "MESSAGE_DELETE", - MessageDeleteBulk = "MESSAGE_DELETE_BULK", - MessageReactionAdd = "MESSAGE_REACTION_ADD", - MessageReactionRemove = "MESSAGE_REACTION_REMOVE", - MessageReactionRemoveAll = "MESSAGE_REACTION_REMOVE_ALL", - MessageReactionRemoveEmoji = "MESSAGE_REACTION_REMOVE_EMOJI", - MessageUpdate = "MESSAGE_UPDATE", - PresenceUpdate = "PRESENCE_UPDATE", - StageInstanceCreate = "STAGE_INSTANCE_CREATE", - StageInstanceDelete = "STAGE_INSTANCE_DELETE", - StageInstanceUpdate = "STAGE_INSTANCE_UPDATE", - Ready = "READY", - Resumed = "RESUMED", - ThreadCreate = "THREAD_CREATE", - ThreadDelete = "THREAD_DELETE", - ThreadListSync = "THREAD_LIST_SYNC", - ThreadMembersUpdate = "THREAD_MEMBERS_UPDATE", - ThreadMemberUpdate = "THREAD_MEMBER_UPDATE", - ThreadUpdate = "THREAD_UPDATE", - TypingStart = "TYPING_START", - UserUpdate = "USER_UPDATE", - VoiceServerUpdate = "VOICE_SERVER_UPDATE", - VoiceStateUpdate = "VOICE_STATE_UPDATE", - WebhooksUpdate = "WEBHOOKS_UPDATE", - GuildScheduledEventCreate = "GUILD_SCHEDULED_EVENT_CREATE", - GuildScheduledEventUpdate = "GUILD_SCHEDULED_EVENT_UPDATE", - GuildScheduledEventDelete = "GUILD_SCHEDULED_EVENT_DELETE", - GuildScheduledEventUserAdd = "GUILD_SCHEDULED_EVENT_USER_ADD", - GuildScheduledEventUserRemove = "GUILD_SCHEDULED_EVENT_USER_REMOVE" -} -export declare type GatewaySendPayload = GatewayHeartbeat | GatewayIdentify | GatewayUpdatePresence | GatewayVoiceStateUpdate | GatewayResume | GatewayRequestGuildMembers; -export declare type GatewayReceivePayload = GatewayHello | GatewayHeartbeatRequest | GatewayHeartbeatAck | GatewayInvalidSession | GatewayReconnect | GatewayDispatchPayload; -export declare type GatewayDispatchPayload = GatewayChannelModifyDispatch | GatewayChannelPinsUpdateDispatch | GatewayGuildBanModifyDispatch | GatewayGuildCreateDispatch | GatewayGuildDeleteDispatch | GatewayGuildEmojisUpdateDispatch | GatewayGuildIntegrationsUpdateDispatch | GatewayGuildMemberAddDispatch | GatewayGuildMemberRemoveDispatch | GatewayGuildMembersChunkDispatch | GatewayGuildMemberUpdateDispatch | GatewayGuildModifyDispatch | GatewayGuildRoleDeleteDispatch | GatewayGuildRoleModifyDispatch | GatewayGuildScheduledEventCreateDispatch | GatewayGuildScheduledEventUpdateDispatch | GatewayGuildScheduledEventDeleteDispatch | GatewayGuildScheduledEventUserAddDispatch | GatewayGuildScheduledEventUserRemoveDispatch | GatewayGuildStickersUpdateDispatch | GatewayIntegrationCreateDispatch | GatewayIntegrationDeleteDispatch | GatewayIntegrationUpdateDispatch | GatewayInteractionCreateDispatch | GatewayInviteCreateDispatch | GatewayInviteDeleteDispatch | GatewayMessageCreateDispatch | GatewayMessageDeleteBulkDispatch | GatewayMessageDeleteDispatch | GatewayMessageReactionAddDispatch | GatewayMessageReactionRemoveAllDispatch | GatewayMessageReactionRemoveDispatch | GatewayMessageReactionRemoveEmojiDispatch | GatewayMessageUpdateDispatch | GatewayPresenceUpdateDispatch | GatewayStageInstanceCreateDispatch | GatewayStageInstanceDeleteDispatch | GatewayStageInstanceUpdateDispatch | GatewayReadyDispatch | GatewayResumedDispatch | GatewayThreadListSyncDispatch | GatewayThreadMembersUpdateDispatch | GatewayThreadMemberUpdateDispatch | GatewayThreadModifyDispatch | GatewayTypingStartDispatch | GatewayUserUpdateDispatch | GatewayVoiceServerUpdateDispatch | GatewayVoiceStateUpdateDispatch | GatewayWebhooksUpdateDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#hello - */ -export interface GatewayHello extends NonDispatchPayload { - op: GatewayOpcodes.Hello; - d: GatewayHelloData; -} -/** - * https://discord.com/developers/docs/topics/gateway#hello - */ -export interface GatewayHelloData { - /** - * The interval (in milliseconds) the client should heartbeat with - */ - heartbeat_interval: number; -} -/** - * https://discord.com/developers/docs/topics/gateway#heartbeating - */ -export interface GatewayHeartbeatRequest extends NonDispatchPayload { - op: GatewayOpcodes.Heartbeat; - d: never; -} -/** - * https://discord.com/developers/docs/topics/gateway#heartbeating-example-gateway-heartbeat-ack - */ -export interface GatewayHeartbeatAck extends NonDispatchPayload { - op: GatewayOpcodes.HeartbeatAck; - d: never; -} -/** - * https://discord.com/developers/docs/topics/gateway#invalid-session - */ -export interface GatewayInvalidSession extends NonDispatchPayload { - op: GatewayOpcodes.InvalidSession; - d: GatewayInvalidSessionData; -} -/** - * https://discord.com/developers/docs/topics/gateway#invalid-session - */ -export declare type GatewayInvalidSessionData = boolean; -/** - * https://discord.com/developers/docs/topics/gateway#reconnect - */ -export interface GatewayReconnect extends NonDispatchPayload { - op: GatewayOpcodes.Reconnect; - d: never; -} -/** - * https://discord.com/developers/docs/topics/gateway#ready - */ -export declare type GatewayReadyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#ready - */ -export interface GatewayReadyDispatchData { - /** - * Gateway version - * - * See https://discord.com/developers/docs/topics/gateway#gateways-gateway-versions - */ - v: number; - /** - * Information about the user including email - * - * See https://discord.com/developers/docs/resources/user#user-object - */ - user: APIUser; - /** - * The guilds the user is in - * - * See https://discord.com/developers/docs/resources/guild#unavailable-guild-object - */ - guilds: APIUnavailableGuild[]; - /** - * Used for resuming connections - */ - session_id: string; - /** - * The shard information associated with this session, if sent when identifying - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - shard?: [shard_id: number, shard_count: number]; - /** - * Contains `id` and `flags` - * - * See https://discord.com/developers/docs/resources/application#application-object - */ - application: Pick; -} -/** - * https://discord.com/developers/docs/topics/gateway#resumed - */ -export declare type GatewayResumedDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#channel-create - * https://discord.com/developers/docs/topics/gateway#channel-update - * https://discord.com/developers/docs/topics/gateway#channel-delete - */ -export declare type GatewayChannelModifyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#channel-create - * https://discord.com/developers/docs/topics/gateway#channel-update - * https://discord.com/developers/docs/topics/gateway#channel-delete - */ -export declare type GatewayChannelModifyDispatchData = APIChannel; -/** - * https://discord.com/developers/docs/topics/gateway#channel-create - */ -export declare type GatewayChannelCreateDispatch = GatewayChannelModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#channel-create - */ -export declare type GatewayChannelCreateDispatchData = GatewayChannelModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#channel-update - */ -export declare type GatewayChannelUpdateDispatch = GatewayChannelModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#channel-update - */ -export declare type GatewayChannelUpdateDispatchData = GatewayChannelModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#channel-delete - */ -export declare type GatewayChannelDeleteDispatch = GatewayChannelModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#channel-delete - */ -export declare type GatewayChannelDeleteDispatchData = GatewayChannelModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#channel-pins-update - */ -export declare type GatewayChannelPinsUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#channel-pins-update - */ -export interface GatewayChannelPinsUpdateDispatchData { - /** - * The id of the guild - */ - guild_id?: Snowflake; - /** - * The id of the channel - */ - channel_id: Snowflake; - /** - * The time at which the most recent pinned message was pinned - */ - last_pin_timestamp?: string | null; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-update - */ -export declare type GatewayGuildModifyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-update - */ -export declare type GatewayGuildModifyDispatchData = APIGuild; -/** - * https://discord.com/developers/docs/topics/gateway#guild-create - */ -export declare type GatewayGuildCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-create - * https://discord.com/developers/docs/topics/gateway#guild-create-guild-create-extra-fields - */ -export interface GatewayGuildCreateDispatchData extends APIGuild { - /** - * When this guild was joined at - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - */ - joined_at: string; - /** - * `true` if this is considered a large guild - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - */ - large: boolean; - /** - * `true` if this guild is unavailable due to an outage - */ - unavailable?: boolean; - /** - * Total number of members in this guild - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - */ - member_count: number; - /** - * States of members currently in voice channels; lacks the `guild_id` key - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - * - * See https://discord.com/developers/docs/resources/voice#voice-state-object - */ - voice_states: Omit[]; - /** - * Users in the guild - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - * - * See https://discord.com/developers/docs/resources/guild#guild-member-object - */ - members: APIGuildMember[]; - /** - * Channels in the guild - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - * - * See https://discord.com/developers/docs/resources/channel#channel-object - */ - channels: APIChannel[]; - /** - * Threads in the guild - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - * - * See https://discord.com/developers/docs/resources/channel#channel-object - */ - threads: APIChannel[]; - /** - * Presences of the members in the guild, will only include non-offline members if the size is greater than `large_threshold` - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - * - * See https://discord.com/developers/docs/topics/gateway#presence-update - */ - presences: GatewayPresenceUpdate[]; - /** - * The stage instances in the guild - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - * - * See https://discord.com/developers/docs/resources/stage-instance#stage-instance-object-stage-instance-structure - */ - stage_instances: APIStageInstance[]; - /** - * The scheduled events in the guild - * - * **This field is only sent within the [GUILD_CREATE](https://discord.com/developers/docs/topics/gateway#guild-create) event** - * - * https://discord.com/developers/docs/resources/guild-scheduled-event#guild-scheduled-event-object - */ - guild_scheduled_events: APIGuildScheduledEvent[]; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-update - */ -export declare type GatewayGuildUpdateDispatch = GatewayGuildModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-update - */ -export declare type GatewayGuildUpdateDispatchData = GatewayGuildModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#guild-delete - */ -export declare type GatewayGuildDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-delete - */ -export declare type GatewayGuildDeleteDispatchData = APIUnavailableGuild; -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-add - * https://discord.com/developers/docs/topics/gateway#guild-ban-remove - */ -export declare type GatewayGuildBanModifyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-add - * https://discord.com/developers/docs/topics/gateway#guild-ban-remove - */ -export interface GatewayGuildBanModifyDispatchData { - /** - * ID of the guild - */ - guild_id: Snowflake; - /** - * The banned user - * - * See https://discord.com/developers/docs/resources/user#user-object - */ - user: APIUser; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-add - */ -export declare type GatewayGuildBanAddDispatch = GatewayGuildBanModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-add - */ -export declare type GatewayGuildBanAddDispatchData = GatewayGuildBanModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-remove - */ -export declare type GatewayGuildBanRemoveDispatch = GatewayGuildBanModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-ban-remove - */ -export declare type GatewayGuildBanRemoveDispatchData = GatewayGuildBanModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#guild-emojis-update - */ -export declare type GatewayGuildEmojisUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-emojis-update - */ -export interface GatewayGuildEmojisUpdateDispatchData { - /** - * ID of the guild - */ - guild_id: Snowflake; - /** - * Array of emojis - * - * See https://discord.com/developers/docs/resources/emoji#emoji-object - */ - emojis: APIEmoji[]; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-stickers-update - */ -export declare type GatewayGuildStickersUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-stickers-update - */ -export interface GatewayGuildStickersUpdateDispatchData { - /** - * ID of the guild - */ - guild_id: Snowflake; - /** - * Array of stickers - * - * See https://discord.com/developers/docs/resources/sticker#sticker-object - */ - stickers: APISticker[]; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-integrations-update - */ -export declare type GatewayGuildIntegrationsUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-integrations-update - */ -export interface GatewayGuildIntegrationsUpdateDispatchData { - /** - * ID of the guild whose integrations were updated - */ - guild_id: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-add - */ -export declare type GatewayGuildMemberAddDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-add - */ -export interface GatewayGuildMemberAddDispatchData extends APIGuildMember { - /** - * The id of the guild - */ - guild_id: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-remove - */ -export declare type GatewayGuildMemberRemoveDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-remove - */ -export interface GatewayGuildMemberRemoveDispatchData { - /** - * The id of the guild - */ - guild_id: Snowflake; - /** - * The user who was removed - * - * See https://discord.com/developers/docs/resources/user#user-object - */ - user: APIUser; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-update - */ -export declare type GatewayGuildMemberUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-member-update - */ -export declare type GatewayGuildMemberUpdateDispatchData = Omit & Partial> & Required> & Nullable> & { - /** - * The id of the guild - */ - guild_id: Snowflake; -}; -/** - * https://discord.com/developers/docs/topics/gateway#guild-members-chunk - */ -export declare type GatewayGuildMembersChunkDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-members-chunk - */ -export interface GatewayGuildMembersChunkDispatchData { - /** - * The id of the guild - */ - guild_id: Snowflake; - /** - * Set of guild members - * - * See https://discord.com/developers/docs/resources/guild#guild-member-object - */ - members: APIGuildMember[]; - /** - * The chunk index in the expected chunks for this response (`0 <= chunk_index < chunk_count`) - */ - chunk_index?: number; - /** - * The total number of expected chunks for this response - */ - chunk_count?: number; - /** - * If passing an invalid id to `REQUEST_GUILD_MEMBERS`, it will be returned here - */ - not_found?: unknown[]; - /** - * If passing true to `REQUEST_GUILD_MEMBERS`, presences of the returned members will be here - * - * See https://discord.com/developers/docs/topics/gateway#presence - */ - presences?: RawGatewayPresenceUpdate[]; - /** - * The nonce used in the Guild Members Request - * - * See https://discord.com/developers/docs/topics/gateway#request-guild-members - */ - nonce?: string; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-create - * https://discord.com/developers/docs/topics/gateway#guild-role-update - */ -export declare type GatewayGuildRoleModifyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-create - * https://discord.com/developers/docs/topics/gateway#guild-role-update - */ -export interface GatewayGuildRoleModifyDispatchData { - /** - * The id of the guild - */ - guild_id: Snowflake; - /** - * The role created or updated - * - * See https://discord.com/developers/docs/topics/permissions#role-object - */ - role: APIRole; -} -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-create - */ -export declare type GatewayGuildRoleCreateDispatch = GatewayGuildRoleModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-create - */ -export declare type GatewayGuildRoleCreateDispatchData = GatewayGuildRoleModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-update - */ -export declare type GatewayGuildRoleUpdateDispatch = GatewayGuildRoleModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-update - */ -export declare type GatewayGuildRoleUpdateDispatchData = GatewayGuildRoleModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-delete - */ -export declare type GatewayGuildRoleDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#guild-role-delete - */ -export interface GatewayGuildRoleDeleteDispatchData { - /** - * The id of the guild - */ - guild_id: Snowflake; - /** - * The id of the role - */ - role_id: Snowflake; -} -export declare type GatewayGuildScheduledEventCreateDispatch = DataPayload; -export declare type GatewayGuildScheduledEventCreateDispatchData = APIGuildScheduledEvent; -export declare type GatewayGuildScheduledEventUpdateDispatch = DataPayload; -export declare type GatewayGuildScheduledEventUpdateDispatchData = APIGuildScheduledEvent; -export declare type GatewayGuildScheduledEventDeleteDispatch = DataPayload; -export declare type GatewayGuildScheduledEventDeleteDispatchData = APIGuildScheduledEvent; -export declare type GatewayGuildScheduledEventUserAddDispatch = DataPayload; -export interface GatewayGuildScheduledEventUserAddDispatchData { - guild_scheduled_event_id: Snowflake; - user_id: Snowflake; - guild_id: Snowflake; -} -export declare type GatewayGuildScheduledEventUserRemoveDispatch = DataPayload; -export interface GatewayGuildScheduledEventUserRemoveDispatchData { - guild_scheduled_event_id: Snowflake; - user_id: Snowflake; - guild_id: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#integration-create - */ -export declare type GatewayIntegrationCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#integration-create - */ -export declare type GatewayIntegrationCreateDispatchData = APIGuildIntegration & { - guild_id: Snowflake; -}; -/** - * https://discord.com/developers/docs/topics/gateway#integration-update - */ -export declare type GatewayIntegrationUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#integration-update - */ -export declare type GatewayIntegrationUpdateDispatchData = APIGuildIntegration & { - guild_id: Snowflake; -}; -/** - * https://discord.com/developers/docs/topics/gateway#integration-update - */ -export declare type GatewayIntegrationDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#integration-delete - */ -export interface GatewayIntegrationDeleteDispatchData { - /** - * Integration id - */ - id: Snowflake; - /** - * ID of the guild - */ - guild_id: Snowflake; - /** - * ID of the bot/OAuth2 application for this Discord integration - */ - application_id?: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#interaction-create - */ -export declare type GatewayInteractionCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#interaction-create - */ -export declare type GatewayInteractionCreateDispatchData = APIInteraction; -/** - * https://discord.com/developers/docs/topics/gateway#invite-create - */ -export declare type GatewayInviteCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#invite-create - */ -export interface GatewayInviteCreateDispatchData { - /** - * The channel the invite is for - */ - channel_id: Snowflake; - /** - * The unique invite code - * - * See https://discord.com/developers/docs/resources/invite#invite-object - */ - code: string; - /** - * The time at which the invite was created - */ - created_at: number; - /** - * The guild of the invite - */ - guild_id?: Snowflake; - /** - * The user that created the invite - * - * See https://discord.com/developers/docs/resources/user#user-object - */ - inviter?: APIUser; - /** - * How long the invite is valid for (in seconds) - */ - max_age: number; - /** - * The maximum number of times the invite can be used - */ - max_uses: number; - /** - * The type of target for this voice channel invite - * - * See https://discord.com/developers/docs/resources/invite#invite-object-invite-target-types - */ - target_type?: InviteTargetType; - /** - * The user whose stream to display for this voice channel stream invite - * - * See https://discord.com/developers/docs/resources/user#user-object - */ - target_user?: APIUser; - /** - * The embedded application to open for this voice channel embedded application invite - */ - target_application?: Partial; - /** - * Whether or not the invite is temporary (invited users will be kicked on disconnect unless they're assigned a role) - */ - temporary: boolean; - /** - * How many times the invite has been used (always will be `0`) - */ - uses: 0; -} -/** - * https://discord.com/developers/docs/topics/gateway#invite-delete - */ -export declare type GatewayInviteDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#invite-delete - */ -export interface GatewayInviteDeleteDispatchData { - /** - * The channel of the invite - */ - channel_id: Snowflake; - /** - * The guild of the invite - */ - guild_id?: Snowflake; - /** - * The unique invite code - * - * See https://discord.com/developers/docs/resources/invite#invite-object - */ - code: string; -} -/** - * https://discord.com/developers/docs/topics/gateway#message-create - */ -export declare type GatewayMessageCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-create - */ -export declare type GatewayMessageCreateDispatchData = Omit & GatewayMessageEventExtraFields; -/** - * https://discord.com/developers/docs/topics/gateway#message-update - */ -export declare type GatewayMessageUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-update - */ -export declare type GatewayMessageUpdateDispatchData = Omit, 'mentions'> & GatewayMessageEventExtraFields & { - /** - * ID of the message - */ - id: Snowflake; - /** - * ID of the channel the message was sent in - */ - channel_id: Snowflake; -}; -export interface GatewayMessageEventExtraFields { - /** - * ID of the guild the message was sent in - */ - guild_id?: Snowflake; - /** - * Member properties for this message's author - * - * The member object exists in `MESSAGE_CREATE` and `MESSAGE_UPDATE` events - * from text-based guild channels - * - * See https://discord.com/developers/docs/resources/guild#guild-member-object - */ - member?: APIGuildMember; - /** - * Users specifically mentioned in the message - * - * The `member` field is only present in `MESSAGE_CREATE` and `MESSAGE_UPDATE` events - * from text-based guild channels - * - * See https://discord.com/developers/docs/resources/user#user-object - * See https://discord.com/developers/docs/resources/guild#guild-member-object - */ - mentions: (APIUser & { - member?: Omit; - })[]; -} -/** - * https://discord.com/developers/docs/topics/gateway#message-delete - */ -export declare type GatewayMessageDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-delete - */ -export interface GatewayMessageDeleteDispatchData { - /** - * The id of the message - */ - id: Snowflake; - /** - * The id of the channel - */ - channel_id: Snowflake; - /** - * The id of the guild - */ - guild_id?: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#message-delete-bulk - */ -export declare type GatewayMessageDeleteBulkDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-delete-bulk - */ -export interface GatewayMessageDeleteBulkDispatchData { - /** - * The ids of the messages - */ - ids: Snowflake[]; - /** - * The id of the channel - */ - channel_id: Snowflake; - /** - * The id of the guild - */ - guild_id?: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-add - */ -export declare type GatewayMessageReactionAddDispatch = ReactionData; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-add - */ -export declare type GatewayMessageReactionAddDispatchData = GatewayMessageReactionAddDispatch['d']; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove - */ -export declare type GatewayMessageReactionRemoveDispatch = ReactionData; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove - */ -export declare type GatewayMessageReactionRemoveDispatchData = GatewayMessageReactionRemoveDispatch['d']; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-all - */ -export declare type GatewayMessageReactionRemoveAllDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-all - */ -export declare type GatewayMessageReactionRemoveAllDispatchData = MessageReactionRemoveData; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-emoji - */ -export declare type GatewayMessageReactionRemoveEmojiDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#message-reaction-remove-emoji - */ -export interface GatewayMessageReactionRemoveEmojiDispatchData extends MessageReactionRemoveData { - /** - * The emoji that was removed - */ - emoji: APIEmoji; -} -/** - * https://discord.com/developers/docs/topics/gateway#presence-update - */ -export declare type GatewayPresenceUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#presence-update - */ -export declare type GatewayPresenceUpdateDispatchData = RawGatewayPresenceUpdate; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-create - */ -export declare type GatewayStageInstanceCreateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-create - */ -export declare type GatewayStageInstanceCreateDispatchData = APIStageInstance; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-delete - */ -export declare type GatewayStageInstanceDeleteDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-delete - */ -export declare type GatewayStageInstanceDeleteDispatchData = APIStageInstance; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-update - */ -export declare type GatewayStageInstanceUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#stage-instance-update - */ -export declare type GatewayStageInstanceUpdateDispatchData = APIStageInstance; -/** - * https://discord.com/developers/docs/topics/gateway#thread-list-sync - */ -export declare type GatewayThreadListSyncDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#thread-list-sync - */ -export declare type GatewayThreadListSyncDispatchData = RawGatewayThreadListSync; -/** - * https://discord.com/developers/docs/topics/gateway#thread-members-update - */ -export declare type GatewayThreadMembersUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#thread-members-update - */ -export declare type GatewayThreadMembersUpdateDispatchData = RawGatewayThreadMembersUpdate; -/** - * https://discord.com/developers/docs/topics/gateway#thread-member-update - */ -export declare type GatewayThreadMemberUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#thread-member-update - */ -export declare type GatewayThreadMemberUpdateDispatchData = APIThreadMember & { - guild_id: Snowflake; -}; -/** - * https://discord.com/developers/docs/topics/gateway#thread-create - * https://discord.com/developers/docs/topics/gateway#thread-update - * https://discord.com/developers/docs/topics/gateway#thread-delete - */ -export declare type GatewayThreadModifyDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#thread-create - */ -export declare type GatewayThreadCreateDispatch = GatewayChannelModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#thread-create - */ -export interface GatewayThreadCreateDispatchData extends APIThreadChannel { - /** - * Whether the thread is newly created or not. - */ - newly_created?: true; -} -/** - * https://discord.com/developers/docs/topics/gateway#thread-update - */ -export declare type GatewayThreadUpdateDispatch = GatewayChannelModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#thread-update - */ -export declare type GatewayThreadUpdateDispatchData = GatewayChannelModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#thread-delete - */ -export declare type GatewayThreadDeleteDispatch = GatewayChannelModifyDispatch; -/** - * https://discord.com/developers/docs/topics/gateway#thread-delete - */ -export declare type GatewayThreadDeleteDispatchData = GatewayChannelModifyDispatchData; -/** - * https://discord.com/developers/docs/topics/gateway#typing-start - */ -export declare type GatewayTypingStartDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#typing-start - */ -export interface GatewayTypingStartDispatchData { - /** - * The id of the channel - */ - channel_id: Snowflake; - /** - * The id of the guild - */ - guild_id?: Snowflake; - /** - * The id of the user - */ - user_id: Snowflake; - /** - * Unix time (in seconds) of when the user started typing - */ - timestamp: number; - /** - * The member who started typing if this happened in a guild - * - * See https://discord.com/developers/docs/resources/guild#guild-member-object - */ - member?: APIGuildMember; -} -/** - * https://discord.com/developers/docs/topics/gateway#user-update - */ -export declare type GatewayUserUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#user-update - */ -export declare type GatewayUserUpdateDispatchData = APIUser; -/** - * https://discord.com/developers/docs/topics/gateway#voice-state-update - */ -export declare type GatewayVoiceStateUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#voice-state-update - */ -export declare type GatewayVoiceStateUpdateDispatchData = GatewayVoiceState; -/** - * https://discord.com/developers/docs/topics/gateway#voice-server-update - */ -export declare type GatewayVoiceServerUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#voice-server-update - */ -export interface GatewayVoiceServerUpdateDispatchData { - /** - * Voice connection token - */ - token: string; - /** - * The guild this voice server update is for - */ - guild_id: Snowflake; - /** - * The voice server host - * - * A `null` endpoint means that the voice server allocated has gone away and is trying to be reallocated. - * You should attempt to disconnect from the currently connected voice server, and not attempt to reconnect - * until a new voice server is allocated - */ - endpoint: string | null; -} -/** - * https://discord.com/developers/docs/topics/gateway#webhooks-update - */ -export declare type GatewayWebhooksUpdateDispatch = DataPayload; -/** - * https://discord.com/developers/docs/topics/gateway#webhooks-update - */ -export interface GatewayWebhooksUpdateDispatchData { - /** - * The id of the guild - */ - guild_id: Snowflake; - /** - * The id of the channel - */ - channel_id: Snowflake; -} -/** - * https://discord.com/developers/docs/topics/gateway#heartbeating - */ -export interface GatewayHeartbeat { - op: GatewayOpcodes.Heartbeat; - d: GatewayHeartbeatData; -} -/** - * https://discord.com/developers/docs/topics/gateway#heartbeating - */ -export declare type GatewayHeartbeatData = number | null; -/** - * https://discord.com/developers/docs/topics/gateway#identify - */ -export interface GatewayIdentify { - op: GatewayOpcodes.Identify; - d: GatewayIdentifyData; -} -/** - * https://discord.com/developers/docs/topics/gateway#identify - */ -export interface GatewayIdentifyData { - /** - * Authentication token - */ - token: string; - /** - * Connection properties - * - * See https://discord.com/developers/docs/topics/gateway#identify-identify-connection-properties - */ - properties: GatewayIdentifyProperties; - /** - * Whether this connection supports compression of packets - * - * @default false - */ - compress?: boolean; - /** - * Value between 50 and 250, total number of members where the gateway will stop sending - * offline members in the guild member list - * - * @default 50 - */ - large_threshold?: number; - /** - * Used for Guild Sharding - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - shard?: [shard_id: number, shard_count: number]; - /** - * Presence structure for initial presence information - * - * See https://discord.com/developers/docs/topics/gateway#update-presence - */ - presence?: GatewayPresenceUpdateData; - /** - * The Gateway Intents you wish to receive - * - * See https://discord.com/developers/docs/topics/gateway#gateway-intents - */ - intents: number; -} -/** - * https://discord.com/developers/docs/topics/gateway#identify-identify-connection-properties - */ -export interface GatewayIdentifyProperties { - /** - * Your operating system - */ - os: string; - /** - * Your library name - */ - browser: string; - /** - * Your library name - */ - device: string; -} -/** - * https://discord.com/developers/docs/topics/gateway#resume - */ -export interface GatewayResume { - op: GatewayOpcodes.Resume; - d: GatewayResumeData; -} -/** - * https://discord.com/developers/docs/topics/gateway#resume - */ -export interface GatewayResumeData { - /** - * Session token - */ - token: string; - /** - * Session id - */ - session_id: string; - /** - * Last sequence number received - */ - seq: number; -} -/** - * https://discord.com/developers/docs/topics/gateway#request-guild-members - */ -export interface GatewayRequestGuildMembers { - op: GatewayOpcodes.RequestGuildMembers; - d: GatewayRequestGuildMembersData; -} -/** - * https://discord.com/developers/docs/topics/gateway#request-guild-members - */ -export interface GatewayRequestGuildMembersData { - /** - * ID of the guild to get members for - */ - guild_id: Snowflake; - /** - * String that username starts with, or an empty string to return all members - */ - query?: string; - /** - * Maximum number of members to send matching the `query`; - * a limit of `0` can be used with an empty string `query` to return all members - */ - limit: number; - /** - * Used to specify if we want the presences of the matched members - */ - presences?: boolean; - /** - * Used to specify which users you wish to fetch - */ - user_ids?: Snowflake | Snowflake[]; - /** - * Nonce to identify the Guild Members Chunk response - * - * Nonce can only be up to 32 bytes. If you send an invalid nonce it will be ignored and the reply member_chunk(s) will not have a `nonce` set. - * - * See https://discord.com/developers/docs/topics/gateway#guild-members-chunk - */ - nonce?: string; -} -/** - * https://discord.com/developers/docs/topics/gateway#update-voice-state - */ -export interface GatewayVoiceStateUpdate { - op: GatewayOpcodes.VoiceStateUpdate; - d: GatewayVoiceStateUpdateData; -} -/** - * https://discord.com/developers/docs/topics/gateway#update-voice-state - */ -export interface GatewayVoiceStateUpdateData { - /** - * ID of the guild - */ - guild_id: Snowflake; - /** - * ID of the voice channel client wants to join (`null` if disconnecting) - */ - channel_id: Snowflake | null; - /** - * Is the client muted - */ - self_mute: boolean; - /** - * Is the client deafened - */ - self_deaf: boolean; -} -/** - * https://discord.com/developers/docs/topics/gateway#update-status - */ -export interface GatewayUpdatePresence { - op: GatewayOpcodes.PresenceUpdate; - d: GatewayPresenceUpdateData; -} -/** - * https://discord.com/developers/docs/topics/gateway#update-presence-gateway-presence-update-structure - */ -export interface GatewayPresenceUpdateData { - /** - * Unix time (in milliseconds) of when the client went idle, or `null` if the client is not idle - */ - since: number | null; - /** - * The user's activities - * - * See https://discord.com/developers/docs/topics/gateway#activity-object - */ - activities: GatewayActivityUpdateData[]; - /** - * The user's new status - * - * See https://discord.com/developers/docs/topics/gateway#update-presence-status-types - */ - status: PresenceUpdateStatus; - /** - * Whether or not the client is afk - */ - afk: boolean; -} -/** - * https://discord.com/developers/docs/topics/gateway#activity-object-activity-structure - */ -export declare type GatewayActivityUpdateData = Pick; -interface BasePayload { - /** - * Opcode for the payload - */ - op: GatewayOpcodes; - /** - * Event data - */ - d?: unknown; - /** - * Sequence number, used for resuming sessions and heartbeats - */ - s: number; - /** - * The event name for this payload - */ - t?: string; -} -declare type NonDispatchPayload = Omit & { - t: null; - s: null; -}; -interface DataPayload extends BasePayload { - op: GatewayOpcodes.Dispatch; - t: Event; - d: D; -} -declare type ReactionData = DataPayload>; -interface MessageReactionRemoveData { - /** - * The id of the channel - */ - channel_id: Snowflake; - /** - * The id of the message - */ - message_id: Snowflake; - /** - * The id of the guild - */ - guild_id?: Snowflake; -} -//# sourceMappingURL=v9.d.ts.map \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v9.d.ts.map b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v9.d.ts.map deleted file mode 100644 index 990831d..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v9.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"v9.d.ts","sourceRoot":"","sources":["v9.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,YAAY,CAAC;AAC5C,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,wBAAwB,CAAC;AACpE,OAAO,KAAK,EACX,cAAc,EACd,UAAU,EACV,QAAQ,EACR,QAAQ,EACR,mBAAmB,EACnB,cAAc,EACd,sBAAsB,EACtB,cAAc,EACd,UAAU,EACV,OAAO,EACP,gBAAgB,EAChB,UAAU,EACV,gBAAgB,EAChB,eAAe,EACf,mBAAmB,E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AAE,EAAE,cAAc,CAAC,QAAQ,CAAC;IAC5B,CAAC,EAAE,KAAK,CAAC;IACT,CAAC,EAAE,CAAC,CAAC;CACL;AAED,aAAK,YAAY,CAAC,CAAC,SAAS,qBAAqB,EAAE,CAAC,SAAS,MAAM,GAAG,KAAK,IAAI,WAAW,CACzF,CAAC,EACD,IAAI,CACH;IACC;;OAEG;IACH,OAAO,EAAE,SAAS,CAAC;IACnB;;OAEG;IACH,UAAU,EAAE,SAAS,CAAC;IACtB;;OAEG;IACH,UAAU,EAAE,SAAS,CAAC;IACtB;;OAEG;IACH,QAAQ,CAAC,EAAE,SAAS,CAAC;IACrB;;;;OAIG;IACH,MAAM,CAAC,EAAE,cAAc,CAAC;IACxB;;;;OAIG;IACH,KAAK,EAAE,QAAQ,CAAC;CAChB,EACD,CAAC,CACD,CACD,CAAC;AAEF,UAAU,yBAAyB;IAClC;;OAEG;IACH,UAAU,EAAE,SAAS,CAAC;IACtB;;OAEG;IACH,UAAU,EAAE,SAAS,CAAC;IACtB;;OAEG;IACH,QAAQ,CAAC,EAAE,SAAS,CAAC;CACrB"} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v9.js b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v9.js deleted file mode 100644 index d4b53f5..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v9.js +++ /dev/null @@ -1,242 +0,0 @@ -"use strict"; -/** - * Types extracted from https://discord.com/developers/docs/topics/gateway - */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __exportStar = (this && this.__exportStar) || function(m, exports) { - for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); -}; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.GatewayDispatchEvents = exports.GatewayIntentBits = exports.GatewayCloseCodes = exports.GatewayOpcodes = exports.GatewayVersion = void 0; -__exportStar(require("./common"), exports); -exports.GatewayVersion = '9'; -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-opcodes - */ -var GatewayOpcodes; -(function (GatewayOpcodes) { - /** - * An event was dispatched - */ - GatewayOpcodes[GatewayOpcodes["Dispatch"] = 0] = "Dispatch"; - /** - * A bidirectional opcode to maintain an active gateway connection. - * Fired periodically by the client, or fired by the gateway to request an immediate heartbeat from the client. - */ - GatewayOpcodes[GatewayOpcodes["Heartbeat"] = 1] = "Heartbeat"; - /** - * Starts a new session during the initial handshake - */ - GatewayOpcodes[GatewayOpcodes["Identify"] = 2] = "Identify"; - /** - * Update the client's presence - */ - GatewayOpcodes[GatewayOpcodes["PresenceUpdate"] = 3] = "PresenceUpdate"; - /** - * Used to join/leave or move between voice channels - */ - GatewayOpcodes[GatewayOpcodes["VoiceStateUpdate"] = 4] = "VoiceStateUpdate"; - /** - * Resume a previous session that was disconnected - */ - GatewayOpcodes[GatewayOpcodes["Resume"] = 6] = "Resume"; - /** - * You should attempt to reconnect and resume immediately - */ - GatewayOpcodes[GatewayOpcodes["Reconnect"] = 7] = "Reconnect"; - /** - * Request information about offline guild members in a large guild - */ - GatewayOpcodes[GatewayOpcodes["RequestGuildMembers"] = 8] = "RequestGuildMembers"; - /** - * The session has been invalidated. You should reconnect and identify/resume accordingly - */ - GatewayOpcodes[GatewayOpcodes["InvalidSession"] = 9] = "InvalidSession"; - /** - * Sent immediately after connecting, contains the `heartbeat_interval` to use - */ - GatewayOpcodes[GatewayOpcodes["Hello"] = 10] = "Hello"; - /** - * Sent in response to receiving a heartbeat to acknowledge that it has been received - */ - GatewayOpcodes[GatewayOpcodes["HeartbeatAck"] = 11] = "HeartbeatAck"; -})(GatewayOpcodes = exports.GatewayOpcodes || (exports.GatewayOpcodes = {})); -/** - * https://discord.com/developers/docs/topics/opcodes-and-status-codes#gateway-gateway-close-event-codes - */ -var GatewayCloseCodes; -(function (GatewayCloseCodes) { - /** - * We're not sure what went wrong. Try reconnecting? - */ - GatewayCloseCodes[GatewayCloseCodes["UnknownError"] = 4000] = "UnknownError"; - /** - * You sent an invalid Gateway opcode or an invalid payload for an opcode. Don't do that! - * - * See https://discord.com/developers/docs/topics/gateway#payloads-and-opcodes - */ - GatewayCloseCodes[GatewayCloseCodes["UnknownOpcode"] = 4001] = "UnknownOpcode"; - /** - * You sent an invalid payload to us. Don't do that! - * - * See https://discord.com/developers/docs/topics/gateway#sending-payloads - */ - GatewayCloseCodes[GatewayCloseCodes["DecodeError"] = 4002] = "DecodeError"; - /** - * You sent us a payload prior to identifying - * - * See https://discord.com/developers/docs/topics/gateway#identify - */ - GatewayCloseCodes[GatewayCloseCodes["NotAuthenticated"] = 4003] = "NotAuthenticated"; - /** - * The account token sent with your identify payload is incorrect - * - * See https://discord.com/developers/docs/topics/gateway#identify - */ - GatewayCloseCodes[GatewayCloseCodes["AuthenticationFailed"] = 4004] = "AuthenticationFailed"; - /** - * You sent more than one identify payload. Don't do that! - */ - GatewayCloseCodes[GatewayCloseCodes["AlreadyAuthenticated"] = 4005] = "AlreadyAuthenticated"; - /** - * The sequence sent when resuming the session was invalid. Reconnect and start a new session - * - * See https://discord.com/developers/docs/topics/gateway#resume - */ - GatewayCloseCodes[GatewayCloseCodes["InvalidSeq"] = 4007] = "InvalidSeq"; - /** - * Woah nelly! You're sending payloads to us too quickly. Slow it down! You will be disconnected on receiving this - */ - GatewayCloseCodes[GatewayCloseCodes["RateLimited"] = 4008] = "RateLimited"; - /** - * Your session timed out. Reconnect and start a new one - */ - GatewayCloseCodes[GatewayCloseCodes["SessionTimedOut"] = 4009] = "SessionTimedOut"; - /** - * You sent us an invalid shard when identifying - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - GatewayCloseCodes[GatewayCloseCodes["InvalidShard"] = 4010] = "InvalidShard"; - /** - * The session would have handled too many guilds - you are required to shard your connection in order to connect - * - * See https://discord.com/developers/docs/topics/gateway#sharding - */ - GatewayCloseCodes[GatewayCloseCodes["ShardingRequired"] = 4011] = "ShardingRequired"; - /** - * You sent an invalid version for the gateway - */ - GatewayCloseCodes[GatewayCloseCodes["InvalidAPIVersion"] = 4012] = "InvalidAPIVersion"; - /** - * You sent an invalid intent for a Gateway Intent. You may have incorrectly calculated the bitwise value - * - * See https://discord.com/developers/docs/topics/gateway#gateway-intents - */ - GatewayCloseCodes[GatewayCloseCodes["InvalidIntents"] = 4013] = "InvalidIntents"; - /** - * You sent a disallowed intent for a Gateway Intent. You may have tried to specify an intent that you have not - * enabled or are not whitelisted for - * - * See https://discord.com/developers/docs/topics/gateway#gateway-intents - * - * See https://discord.com/developers/docs/topics/gateway#privileged-intents - */ - GatewayCloseCodes[GatewayCloseCodes["DisallowedIntents"] = 4014] = "DisallowedIntents"; -})(GatewayCloseCodes = exports.GatewayCloseCodes || (exports.GatewayCloseCodes = {})); -/** - * https://discord.com/developers/docs/topics/gateway#list-of-intents - */ -var GatewayIntentBits; -(function (GatewayIntentBits) { - GatewayIntentBits[GatewayIntentBits["Guilds"] = 1] = "Guilds"; - GatewayIntentBits[GatewayIntentBits["GuildMembers"] = 2] = "GuildMembers"; - GatewayIntentBits[GatewayIntentBits["GuildBans"] = 4] = "GuildBans"; - GatewayIntentBits[GatewayIntentBits["GuildEmojisAndStickers"] = 8] = "GuildEmojisAndStickers"; - GatewayIntentBits[GatewayIntentBits["GuildIntegrations"] = 16] = "GuildIntegrations"; - GatewayIntentBits[GatewayIntentBits["GuildWebhooks"] = 32] = "GuildWebhooks"; - GatewayIntentBits[GatewayIntentBits["GuildInvites"] = 64] = "GuildInvites"; - GatewayIntentBits[GatewayIntentBits["GuildVoiceStates"] = 128] = "GuildVoiceStates"; - GatewayIntentBits[GatewayIntentBits["GuildPresences"] = 256] = "GuildPresences"; - GatewayIntentBits[GatewayIntentBits["GuildMessages"] = 512] = "GuildMessages"; - GatewayIntentBits[GatewayIntentBits["GuildMessageReactions"] = 1024] = "GuildMessageReactions"; - GatewayIntentBits[GatewayIntentBits["GuildMessageTyping"] = 2048] = "GuildMessageTyping"; - GatewayIntentBits[GatewayIntentBits["DirectMessages"] = 4096] = "DirectMessages"; - GatewayIntentBits[GatewayIntentBits["DirectMessageReactions"] = 8192] = "DirectMessageReactions"; - GatewayIntentBits[GatewayIntentBits["DirectMessageTyping"] = 16384] = "DirectMessageTyping"; - GatewayIntentBits[GatewayIntentBits["GuildScheduledEvents"] = 65536] = "GuildScheduledEvents"; -})(GatewayIntentBits = exports.GatewayIntentBits || (exports.GatewayIntentBits = {})); -/** - * https://discord.com/developers/docs/topics/gateway#commands-and-events-gateway-events - */ -var GatewayDispatchEvents; -(function (GatewayDispatchEvents) { - GatewayDispatchEvents["ApplicationCommandPermissionsUpdate"] = "APPLICATION_COMMAND_PERMISSIONS_UPDATE"; - GatewayDispatchEvents["ChannelCreate"] = "CHANNEL_CREATE"; - GatewayDispatchEvents["ChannelDelete"] = "CHANNEL_DELETE"; - GatewayDispatchEvents["ChannelPinsUpdate"] = "CHANNEL_PINS_UPDATE"; - GatewayDispatchEvents["ChannelUpdate"] = "CHANNEL_UPDATE"; - GatewayDispatchEvents["GuildBanAdd"] = "GUILD_BAN_ADD"; - GatewayDispatchEvents["GuildBanRemove"] = "GUILD_BAN_REMOVE"; - GatewayDispatchEvents["GuildCreate"] = "GUILD_CREATE"; - GatewayDispatchEvents["GuildDelete"] = "GUILD_DELETE"; - GatewayDispatchEvents["GuildEmojisUpdate"] = "GUILD_EMOJIS_UPDATE"; - GatewayDispatchEvents["GuildIntegrationsUpdate"] = "GUILD_INTEGRATIONS_UPDATE"; - GatewayDispatchEvents["GuildMemberAdd"] = "GUILD_MEMBER_ADD"; - GatewayDispatchEvents["GuildMemberRemove"] = "GUILD_MEMBER_REMOVE"; - GatewayDispatchEvents["GuildMembersChunk"] = "GUILD_MEMBERS_CHUNK"; - GatewayDispatchEvents["GuildMemberUpdate"] = "GUILD_MEMBER_UPDATE"; - GatewayDispatchEvents["GuildRoleCreate"] = "GUILD_ROLE_CREATE"; - GatewayDispatchEvents["GuildRoleDelete"] = "GUILD_ROLE_DELETE"; - GatewayDispatchEvents["GuildRoleUpdate"] = "GUILD_ROLE_UPDATE"; - GatewayDispatchEvents["GuildStickersUpdate"] = "GUILD_STICKERS_UPDATE"; - GatewayDispatchEvents["GuildUpdate"] = "GUILD_UPDATE"; - GatewayDispatchEvents["IntegrationCreate"] = "INTEGRATION_CREATE"; - GatewayDispatchEvents["IntegrationDelete"] = "INTEGRATION_DELETE"; - GatewayDispatchEvents["IntegrationUpdate"] = "INTEGRATION_UPDATE"; - GatewayDispatchEvents["InteractionCreate"] = "INTERACTION_CREATE"; - GatewayDispatchEvents["InviteCreate"] = "INVITE_CREATE"; - GatewayDispatchEvents["InviteDelete"] = "INVITE_DELETE"; - GatewayDispatchEvents["MessageCreate"] = "MESSAGE_CREATE"; - GatewayDispatchEvents["MessageDelete"] = "MESSAGE_DELETE"; - GatewayDispatchEvents["MessageDeleteBulk"] = "MESSAGE_DELETE_BULK"; - GatewayDispatchEvents["MessageReactionAdd"] = "MESSAGE_REACTION_ADD"; - GatewayDispatchEvents["MessageReactionRemove"] = "MESSAGE_REACTION_REMOVE"; - GatewayDispatchEvents["MessageReactionRemoveAll"] = "MESSAGE_REACTION_REMOVE_ALL"; - GatewayDispatchEvents["MessageReactionRemoveEmoji"] = "MESSAGE_REACTION_REMOVE_EMOJI"; - GatewayDispatchEvents["MessageUpdate"] = "MESSAGE_UPDATE"; - GatewayDispatchEvents["PresenceUpdate"] = "PRESENCE_UPDATE"; - GatewayDispatchEvents["StageInstanceCreate"] = "STAGE_INSTANCE_CREATE"; - GatewayDispatchEvents["StageInstanceDelete"] = "STAGE_INSTANCE_DELETE"; - GatewayDispatchEvents["StageInstanceUpdate"] = "STAGE_INSTANCE_UPDATE"; - GatewayDispatchEvents["Ready"] = "READY"; - GatewayDispatchEvents["Resumed"] = "RESUMED"; - GatewayDispatchEvents["ThreadCreate"] = "THREAD_CREATE"; - GatewayDispatchEvents["ThreadDelete"] = "THREAD_DELETE"; - GatewayDispatchEvents["ThreadListSync"] = "THREAD_LIST_SYNC"; - GatewayDispatchEvents["ThreadMembersUpdate"] = "THREAD_MEMBERS_UPDATE"; - GatewayDispatchEvents["ThreadMemberUpdate"] = "THREAD_MEMBER_UPDATE"; - GatewayDispatchEvents["ThreadUpdate"] = "THREAD_UPDATE"; - GatewayDispatchEvents["TypingStart"] = "TYPING_START"; - GatewayDispatchEvents["UserUpdate"] = "USER_UPDATE"; - GatewayDispatchEvents["VoiceServerUpdate"] = "VOICE_SERVER_UPDATE"; - GatewayDispatchEvents["VoiceStateUpdate"] = "VOICE_STATE_UPDATE"; - GatewayDispatchEvents["WebhooksUpdate"] = "WEBHOOKS_UPDATE"; - GatewayDispatchEvents["GuildScheduledEventCreate"] = "GUILD_SCHEDULED_EVENT_CREATE"; - GatewayDispatchEvents["GuildScheduledEventUpdate"] = "GUILD_SCHEDULED_EVENT_UPDATE"; - GatewayDispatchEvents["GuildScheduledEventDelete"] = "GUILD_SCHEDULED_EVENT_DELETE"; - GatewayDispatchEvents["GuildScheduledEventUserAdd"] = "GUILD_SCHEDULED_EVENT_USER_ADD"; - GatewayDispatchEvents["GuildScheduledEventUserRemove"] = "GUILD_SCHEDULED_EVENT_USER_REMOVE"; -})(GatewayDispatchEvents = exports.GatewayDispatchEvents || (exports.GatewayDispatchEvents = {})); -// #endregion Shared -//# sourceMappingURL=v9.js.map \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v9.js.map b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v9.js.map deleted file mode 100644 index 411535b..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v9.js.map +++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C,sEAA6C,CAAA;IAC7C,sEAA6C,CAAA;IAC7C,wCAAe,CAAA;IACf,4CAAmB,CAAA;IACnB,uDAA8B,CAAA;IAC9B,uDAA8B,CAAA;IAC9B,4DAAmC,CAAA;IACnC,sEAA6C,CAAA;IAC7C,oEAA2C,CAAA;IAC3C,uDAA8B,CAAA;IAC9B,qDAA4B,CAAA;IAC5B,mDAA0B,CAAA;IAC1B,kEAAyC,CAAA;IACzC,gEAAuC,CAAA;IACvC,2DAAkC,CAAA;IAClC,mFAA0D,CAAA;IAC1D,mFAA0D,CAAA;IAC1D,mFAA0D,CAAA;IAC1D,sFAA6D,CAAA;IAC7D,4FAAmE,CAAA;AACpE,CAAC,EAzDW,qBAAqB,GAArB,6BAAqB,KAArB,6BAAqB,QAyDhC;AAmjDD,oBAAoB"} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v9.mjs b/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v9.mjs deleted file mode 100644 index 27b1baf..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/gateway/v9.mjs +++ /dev/null @@ -1,8 +0,0 @@ -import mod from "./v9.js"; - -export default mod; -export const GatewayCloseCodes = mod.GatewayCloseCodes; -export const GatewayDispatchEvents = mod.GatewayDispatchEvents; -export const GatewayIntentBits = mod.GatewayIntentBits; -export const GatewayOpcodes = mod.GatewayOpcodes; -export const GatewayVersion = mod.GatewayVersion; diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/globals.d.ts b/node_modules/@discordjs/voice/node_modules/discord-api-types/globals.d.ts deleted file mode 100644 index 5658aae..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/globals.d.ts +++ /dev/null @@ -1,83 +0,0 @@ -/** - * https://discord.com/developers/docs/reference#snowflakes - */ -export declare type Snowflake = string; -/** - * https://discord.com/developers/docs/topics/permissions - * @internal - */ -export declare type Permissions = string; -/** - * https://discord.com/developers/docs/reference#message-formatting-formats - */ -export declare const FormattingPatterns: { - /** - * Regular expression for matching a user mention, strictly without a nickname - * - * The `id` group property is present on the `exec` result of this expression - */ - readonly User: RegExp; - /** - * Regular expression for matching a user mention, strictly with a nickname - * - * The `id` group property is present on the `exec` result of this expression - * @deprecated Passing `!` in user mentions is no longer necessary / supported, and future message contents won't have it - */ - readonly UserWithNickname: RegExp; - /** - * Regular expression for matching a user mention, with or without a nickname - * - * The `id` group property is present on the `exec` result of this expression - * @deprecated Passing `!` in user mentions is no longer necessary / supported, and future message contents won't have it - */ - readonly UserWithOptionalNickname: RegExp; - /** - * Regular expression for matching a channel mention - * - * The `id` group property is present on the `exec` result of this expression - */ - readonly Channel: RegExp; - /** - * Regular expression for matching a role mention - * - * The `id` group property is present on the `exec` result of this expression - */ - readonly Role: RegExp; - /** - * Regular expression for matching a custom emoji, either static or animated - * - * The `animated`, `name` and `id` group properties are present on the `exec` result of this expression - */ - readonly Emoji: RegExp; - /** - * Regular expression for matching strictly an animated custom emoji - * - * The `animated`, `name` and `id` group properties are present on the `exec` result of this expression - */ - readonly AnimatedEmoji: RegExp; - /** - * Regular expression for matching strictly a static custom emoji - * - * The `name` and `id` group properties are present on the `exec` result of this expression - */ - readonly StaticEmoji: RegExp; - /** - * Regular expression for matching a timestamp, either default or custom styled - * - * The `timestamp` and `style` group properties are present on the `exec` result of this expression - */ - readonly Timestamp: RegExp; - /** - * Regular expression for matching strictly default styled timestamps - * - * The `timestamp` group property is present on the `exec` result of this expression - */ - readonly DefaultStyledTimestamp: RegExp; - /** - * Regular expression for matching strictly custom styled timestamps - * - * The `timestamp` and `style` group properties are present on the `exec` result of this expression - */ - readonly StyledTimestamp: RegExp; -}; -//# sourceMappingURL=globals.d.ts.map \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/globals.d.ts.map b/node_modules/@discordjs/voice/node_modules/discord-api-types/globals.d.ts.map deleted file mode 100644 index 3ace4f5..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/globals.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"globals.d.ts","sourceRoot":"","sources":["globals.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,oBAAY,SAAS,GAAG,MAAM,CAAC;AAE/B;;;GAGG;AACH,oBAAY,WAAW,GAAG,MAAM,CAAC;AAEjC;;GAEG;AACH,eAAO,MAAM,kBAAkB;IAC9B;;;;OAIG;;IAEH;;;;;OAKG;;IAEH;;;;;OAKG;;IAEH;;;;OAIG;;IAEH;;;;OAIG;;IAEH;;;;OAIG;;IAEH;;;;OAIG;;IAEH;;;;OAIG;;IAEH;;;;OAIG;;IAEH;;;;OAIG;;IAEH;;;;OAIG;;CAEM,CAAC"} \ No newline at end of file diff --git a/node_modules/@discordjs/voice/node_modules/discord-api-types/globals.js b/node_modules/@discordjs/voice/node_modules/discord-api-types/globals.js deleted file mode 100644 index 2b53b68..0000000 --- a/node_modules/@discordjs/voice/node_modules/discord-api-types/globals.js +++ /dev/null @@ -1,82 +0,0 @@ -"use strict"; -Object.defineProperty(exports, "__esModule", { value: true }); -exports.FormattingPatterns = void 0; -/** - * https://discord.com/developers/docs/reference#message-formatting-formats - */ -exports.FormattingPatterns = { - /** - * Regular expression for matching a user mention, strictly without a nickname - * - * The `id` group property is present on the `exec` result of this expression - */ - User: /<@(?\d{17,20})>/, - /** - * Regular expression for matching a user mention, strictly with a nickname - * - * The `id` group property is present on the `exec` result of this expression - * @deprecated Passing `!` in user mentions is no longer necessary / supported, and future message contents won't have it - */ - UserWithNickname: /<@!(?\d{17,20})>/, - /** - * Regular expression for matching a user mention, with or without a nickname - * - * The `id` group property is present on the `exec` result of this expression - * @deprecated Passing `!` in user mentions is no longer necessary / supported, and future message contents won't have it - */ - UserWithOptionalNickname: /<@!?(?\d{17,20})>/, - /** - * Regular expression for matching a channel mention - * - * The `id` group property is present on the `exec` result of this expression - */ - Channel: /<#(?\d{17,20})>/, - /** - * Regular expression for matching a role mention - * - * The `id` group property is present on the `exec` result of this expression - */ - Role: /<@&(?\d{17,20})>/, - /** - * Regular expression for matching a custom emoji, either static or animated - * - * The `animated`, `name` and `id` group properties are present on the `exec` result of this expression - */ - Emoji: /<(?a)?:(?\w{2,32}):(?\d{17,20})>/, - /** - * Regular expression for matching strictly an animated custom emoji - * - * The `animated`, `name` and `id` group properties are present on the `exec` result of this expression - */ - AnimatedEmoji: /<(?a):(?\w{2,32}):(?\d{17,20})>/, - /** - * Regular expression for matching strictly a static custom emoji - * - * The `name` and `id` group properties are present on the `exec` result of this expression - */ - StaticEmoji: /<:(?\w{2,32}):(?\d{17,20})>/, - /** - * Regular expression for matching a timestamp, either default or custom styled - * - * The `timestamp` and `style` group properties are present on the `exec` result of this expression - */ - Timestamp: /-?\d{1,13})(:(? - - -
-
-

Himalaya

- on Github - by Chris Andrejewski -
-
-
-
- - -
-
- -
-
-
-
- - -
-
-

-          
-
-
-
- - - - - diff --git a/node_modules/himalaya/gulpfile.babel.js b/node_modules/himalaya/gulpfile.babel.js deleted file mode 100644 index 0b8098b..0000000 --- a/node_modules/himalaya/gulpfile.babel.js +++ /dev/null @@ -1,52 +0,0 @@ -import 'babel-polyfill' -import 'source-map-support/register' - -import del from 'del' -import gulp from 'gulp' -import babel from 'gulp-babel' -import sourcemaps from 'gulp-sourcemaps' -import babelify from 'babelify' -import source from 'vinyl-source-stream' -import browserify from 'browserify' -import buffer from 'vinyl-buffer' - -gulp.task('default', ['build']) - -gulp.task('build', ['cleanLib', 'buildSrc', 'buildDist']) - -gulp.task('cleanLib', () => { - return del(['lib'], {force: true}) -}) - -gulp.task('cleanDist', () => { - return del(['dist'], {force: true}) -}) - -gulp.task('buildSrc', ['cleanLib'], () => { - return gulp - .src(['src/**/*.js']) - .pipe(sourcemaps.init()) - .pipe(babel()) - .pipe(sourcemaps.write('./')) - .pipe(gulp.dest('lib')) -}) - -gulp.task('buildDist', ['cleanDist'], () => { - const options = { - entries: ['index.js'], - debug: false, - basedir: 'src', - standalone: 'himalaya' - } - return browserify(options) - .transform(babelify) - .bundle() - .pipe(source('himalaya.js')) - .pipe(buffer()) - .pipe(sourcemaps.init({ - // loads map from browserify file - loadMaps: true - })) - .pipe(sourcemaps.write('./')) - .pipe(gulp.dest('docs/dist')) -}) diff --git a/node_modules/himalaya/lib/compat.js b/node_modules/himalaya/lib/compat.js deleted file mode 100644 index 144b9af..0000000 --- a/node_modules/himalaya/lib/compat.js +++ /dev/null @@ -1,52 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.startsWith = startsWith; -exports.endsWith = endsWith; -exports.stringIncludes = stringIncludes; -exports.isRealNaN = isRealNaN; -exports.arrayIncludes = arrayIncludes; -/* - We don't want to include babel-polyfill in our project. - - Library authors should be using babel-runtime for non-global polyfilling - - Adding babel-polyfill/-runtime increases bundle size significantly - - We will include our polyfill instance methods as regular functions. -*/ - -function startsWith(str, searchString, position) { - return str.substr(position || 0, searchString.length) === searchString; -} - -function endsWith(str, searchString, position) { - var index = (position || str.length) - searchString.length; - var lastIndex = str.lastIndexOf(searchString, index); - return lastIndex !== -1 && lastIndex === index; -} - -function stringIncludes(str, searchString, position) { - return str.indexOf(searchString, position || 0) !== -1; -} - -function isRealNaN(x) { - return typeof x === 'number' && isNaN(x); -} - -function arrayIncludes(array, searchElement, position) { - var len = array.length; - if (len === 0) return false; - - var lookupIndex = position | 0; - var isNaNElement = isRealNaN(searchElement); - var searchIndex = lookupIndex >= 0 ? lookupIndex : len + lookupIndex; - while (searchIndex < len) { - var element = array[searchIndex++]; - if (element === searchElement) return true; - if (isNaNElement && isRealNaN(element)) return true; - } - - return false; -} -//# sourceMappingURL=compat.js.map diff --git a/node_modules/himalaya/lib/compat.js.map b/node_modules/himalaya/lib/compat.js.map deleted file mode 100644 index 0f177f8..0000000 --- a/node_modules/himalaya/lib/compat.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["compat.js"],"names":["startsWith","endsWith","stringIncludes","isRealNaN","arrayIncludes","str","searchString","position","substr","length","index","lastI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AA0B;AACxB,QAAMI,UAAUN,MAAMK,aAAN,CAAhB;AACA,QAAIC,YAAYL,aAAhB,EAA+B,OAAO,IAAP;AAC/B,QAAIG,gBAAgBjB,UAAUmB,OAAV,CAApB,EAAwC,OAAO,IAAP;AACzC;;AAED,SAAO,KAAP;AACD","file":"compat.js","sourcesContent":["/*\n We don't want to include babel-polyfill in our project.\n - Library authors should be using babel-runtime for non-global polyfilling\n - Adding babel-polyfill/-runtime increases bundle size significantly\n\n We will include our polyfill instance methods as regular functions.\n*/\n\nexport function startsWith (str, searchString, position) {\n return str.substr(position || 0, searchString.length) === searchString\n}\n\nexport function endsWith (str, searchString, position) {\n const index = (position || str.length) - searchString.length\n const lastIndex = str.lastIndexOf(searchString, index)\n return lastIndex !== -1 && lastIndex === index\n}\n\nexport function stringIncludes (str, searchString, position) {\n return str.indexOf(searchString, position || 0) !== -1\n}\n\nexport function isRealNaN (x) {\n return typeof x === 'number' && isNaN(x)\n}\n\nexport function arrayIncludes (array, searchElement, position) {\n const len = array.length\n if (len === 0) return false\n\n const lookupIndex = position | 0\n const isNaNElement = isRealNaN(searchElement)\n let searchIndex = lookupIndex >= 0 ? lookupIndex : len + lookupIndex\n while (searchIndex < len) {\n const element = array[searchIndex++]\n if (element === searchElement) return true\n if (isNaNElement && isRealNaN(element)) return true\n }\n\n return false\n}\n"]} \ No newline at end of file diff --git a/node_modules/himalaya/lib/format.js b/node_modules/himalaya/lib/format.js deleted file mode 100644 index 9542964..0000000 --- a/node_modules/himalaya/lib/format.js +++ /dev/null @@ -1,50 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.splitHead = splitHead; -exports.unquote = unquote; -exports.format = format; -exports.formatAttributes = formatAttributes; -function splitHead(str, sep) { - var idx = str.indexOf(sep); - if (idx === -1) return [str]; - return [str.slice(0, idx), str.slice(idx + sep.length)]; -} - -function unquote(str) { - var car = str.charAt(0); - var end = str.length - 1; - var isQuoteStart = car === '"' || car === "'"; - if (isQuoteStart && car === str.charAt(end)) { - return str.slice(1, end); - } - return str; -} - -function format(nodes, options) { - return nodes.map(function (node) { - var type = node.type; - var outputNode = type === 'element' ? { - type: type, - tagName: node.tagName.toLowerCase(), - attributes: formatAttributes(node.attributes), - children: format(node.children, options) - } : { type: type, content: node.content }; - if (options.includePositions) { - outputNode.position = node.position; - } - return outputNode; - }); -} - -function formatAttributes(attributes) { - return attributes.map(function (attribute) { - var parts = splitHead(attribute.trim(), '='); - var key = parts[0]; - var value = typeof parts[1] === 'string' ? unquote(parts[1]) : null; - return { key: key, value: value }; - }); -} -//# sourceMappingURL=format.js.map diff --git a/node_modules/himalaya/lib/format.js.map b/node_modules/himalaya/lib/format.js.map deleted file mode 100644 index c7cc00a..0000000 --- a/node_modules/himalaya/lib/format.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["format.js"],"names":["splitHead","unquote","format","formatAttributes","str","sep","idx","indexOf","slice","length","car","charAt","end","isQuoteStart","nodes","options","map","type","node","outputNode","tagName","toLowerCase","attributes","children","content","includePositions","position","parts","attribute","trim","key","value"],"mappings":";;;;;QAAgBA,S,GAAAA,S;QAMAC,O,GAAAA,O;QAUAC,M,GAAAA,M;QAkBAC,gB,GAAAA,gB;AAlCT,SAASH,SAAT,CAAoBI,GAApB,EAAyBC,GAAzB,EAA8B;AACnC,MAAMC,MAAMF,IAAIG,OAAJ,CAAYF,GAAZ,CAAZ;AACA,MAAIC,QAAQ,CAAC,CAAb,EAAgB,OAAO,CAACF,GAAD,CAAP;AAChB,SAAO,CAACA,IAAII,KAAJ,CAAU,CAAV,EAAaF,GAAb,CAAD,EAAoBF,IAAII,KAAJ,CAAUF,MAAMD,IAAII,MAApB,CAApB,CAAP;AACD;;AAEM,SAASR,OAAT,CAAkBG,GAAlB,EAAuB;AAC5B,MAAMM,MAAMN,IAAIO,MAAJ,CAAW,CAAX,CAAZ;AACA,MAAMC,MAAMR,IAAIK,MAAJ,GAAa,CAAzB;AACA,MAAMI,eAAeH,QAAQ,GAAR,IAAeA,QAAQ,GAA5C;AACA,MAAIG,gBAAgBH,QAAQN,IAAIO,MAAJ,CAAWC,GAAX,CAA5B,EAA6C;AAC3C,WAAOR,IAAII,KAAJ,CAAU,CAAV,EAAaI,GAAb,CAAP;AACD;AACD,SAAOR,GAAP;AACD;;AAEM,SAASF,MAAT,CAAiBY,KAAjB,EAAwBC,OAAxB,EAAiC;AACtC,SAAOD,MAAME,GAAN,CAAU,gBAAQ;AACvB,QAAMC,OAAOC,KAAKD,IAAlB;AACA,QAAME,aAAaF,SAAS,SAAT,GACf;AACAA,gBADA;AAEAG,eAASF,KAAKE,OAAL,CAAaC,WAAb,EAFT;AAGAC,kBAAYnB,iBAAiBe,KAAKI,UAAtB,CAHZ;AAIAC,gBAAUrB,OAAOgB,KAAKK,QAAZ,EAAsBR,OAAtB;AAJV,KADe,GAOf,EAAEE,UAAF,EAAQO,SAASN,KAAKM,OAAtB,EAPJ;AAQA,QAAIT,QAAQU,gBAAZ,EAA8B;AAC5BN,iBAAWO,QAAX,GAAsBR,KAAKQ,QAA3B;AACD;AACD,WAAOP,UAAP;AACD,GAdM,CAAP;AAeD;;AAEM,SAAShB,gBAAT,CAA2BmB,UAA3B,EAAuC;AAC5C,SAAOA,WAAWN,GAAX,CAAe,qBAAa;AACjC,QAAMW,QAAQ3B,UAAU4B,UAAUC,IAAV,EAAV,EAA4B,GAA5B,CAAd;AACA,QAAMC,MAAMH,MAAM,CAAN,CAAZ;AACA,QAAMI,QAAQ,OAAOJ,MAAM,CAAN,CAAP,KAAoB,QAApB,GACV1B,QAAQ0B,MAAM,CAAN,CAAR,CADU,GAEV,IAFJ;AAGA,WAAO,EAACG,QAAD,EAAMC,YAAN,EAAP;AACD,GAPM,CAAP;AAQD","file":"format.js","sourcesContent":["export function splitHead (str, sep) {\n const idx = str.indexOf(sep)\n if (idx === -1) return [str]\n return [str.slice(0, idx), str.slice(idx + sep.length)]\n}\n\nexport function unquote (str) {\n const car = str.charAt(0)\n const end = str.length - 1\n const isQuoteStart = car === '\"' || car === \"'\"\n if (isQuoteStart && car === str.charAt(end)) {\n return str.slice(1, end)\n }\n return str\n}\n\nexport function format (nodes, options) {\n return nodes.map(node => {\n const type = node.type\n const outputNode = type === 'element'\n ? {\n type,\n tagName: node.tagName.toLowerCase(),\n attributes: formatAttributes(node.attributes),\n children: format(node.children, options)\n }\n : { type, content: node.content }\n if (options.includePositions) {\n outputNode.position = node.position\n }\n return outputNode\n })\n}\n\nexport function formatAttributes (attributes) {\n return attributes.map(attribute => {\n const parts = splitHead(attribute.trim(), '=')\n const key = parts[0]\n const value = typeof parts[1] === 'string'\n ? unquote(parts[1])\n : null\n return {key, value}\n })\n}\n"]} \ No newline at end of file diff --git a/node_modules/himalaya/lib/index.js b/node_modules/himalaya/lib/index.js deleted file mode 100644 index 18c5a85..0000000 --- a/node_modules/himalaya/lib/index.js +++ /dev/null @@ -1,47 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.parseDefaults = undefined; -exports.parse = parse; -exports.stringify = stringify; - -var _lexer = require('./lexer'); - -var _lexer2 = _interopRequireDefault(_lexer); - -var _parser = require('./parser'); - -var _parser2 = _interopRequireDefault(_parser); - -var _format = require('./format'); - -var _stringify = require('./stringify'); - -var _tags = require('./tags'); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var parseDefaults = exports.parseDefaults = { - voidTags: _tags.voidTags, - closingTags: _tags.closingTags, - childlessTags: _tags.childlessTags, - closingTagAncestorBreakers: _tags.closingTagAncestorBreakers, - includePositions: false -}; - -function parse(str) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : parseDefaults; - - var tokens = (0, _lexer2.default)(str, options); - var nodes = (0, _parser2.default)(tokens, options); - return (0, _format.format)(nodes, options); -} - -function stringify(ast) { - var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : parseDefaults; - - return (0, _stringify.toHTML)(ast, options); -} -//# sourceMappingURL=index.js.map diff --git a/node_modules/himalaya/lib/index.js.map b/node_modules/himalaya/lib/index.js.map deleted file mode 100644 index 8ed8a09..0000000 --- a/node_modules/himalaya/lib/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["index.js"],"names":["parse","stringify","parseDefaults","voidTags","closingTags","childlessTags","closingTagAncestorBreakers","includePositions","str","options","tokens","nodes","ast"],"mappings":";;;;;;QAmBgBA,K,GAAAA,K;QAMAC,S,GAAAA,S;;AAzBhB;;;;AACA;;;;AACA;;AACA;;AACA;;;;AAOO,IAAMC,wCAAgB;AAC3BC,0BAD2B;AAE3BC,gCAF2B;AAG3BC,oCAH2B;AAI3BC,8DAJ2B;AAK3BC,oBAAkB;AALS,CAAtB;;AAQA,SAASP,KAAT,CAAgBQ,GAAhB,EAA8C;AAAA,MAAzBC,OAAyB,uEAAfP,aAAe;;AACnD,MAAMQ,SAAS,qBAAMF,GAAN,EAAWC,OAAX,CAAf;AACA,MAAME,QAAQ,sBAAOD,MAAP,EAAeD,OAAf,CAAd;AACA,SAAO,oBAAOE,KAAP,EAAcF,OAAd,CAAP;AACD;;AAEM,SAASR,SAAT,CAAoBW,GAApB,EAAkD;AAAA,MAAzBH,OAAyB,uEAAfP,aAAe;;AACvD,SAAO,uBAAOU,GAAP,EAAYH,OAAZ,CAAP;AACD","file":"index.js","sourcesContent":["import lexer from './lexer'\nimport parser from './parser'\nimport {format} from './format'\nimport {toHTML} from './stringify'\nimport {\n voidTags,\n closingTags,\n childlessTags,\n closingTagAncestorBreakers\n} from './tags'\n\nexport const parseDefaults = {\n voidTags,\n closingTags,\n childlessTags,\n closingTagAncestorBreakers,\n includePositions: false\n}\n\nexport function parse (str, options = parseDefaults) {\n const tokens = lexer(str, options)\n const nodes = parser(tokens, options)\n return format(nodes, options)\n}\n\nexport function stringify (ast, options = parseDefaults) {\n return toHTML(ast, options)\n}\n"]} \ No newline at end of file diff --git a/node_modules/himalaya/lib/lexer.js b/node_modules/himalaya/lib/lexer.js deleted file mode 100644 index 1e690e9..0000000 --- a/node_modules/himalaya/lib/lexer.js +++ /dev/null @@ -1,344 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.feedPosition = feedPosition; -exports.jumpPosition = jumpPosition; -exports.makeInitialPosition = makeInitialPosition; -exports.copyPosition = copyPosition; -exports.default = lexer; -exports.lex = lex; -exports.findTextEnd = findTextEnd; -exports.lexText = lexText; -exports.lexComment = lexComment; -exports.lexTag = lexTag; -exports.isWhitespaceChar = isWhitespaceChar; -exports.lexTagName = lexTagName; -exports.lexTagAttributes = lexTagAttributes; -exports.lexSkipTag = lexSkipTag; - -var _compat = require('./compat'); - -function feedPosition(position, str, len) { - var start = position.index; - var end = position.index = start + len; - for (var i = start; i < end; i++) { - var char = str.charAt(i); - if (char === '\n') { - position.line++; - position.column = 0; - } else { - position.column++; - } - } -} - -function jumpPosition(position, str, end) { - var len = end - position.index; - return feedPosition(position, str, len); -} - -function makeInitialPosition() { - return { - index: 0, - column: 0, - line: 0 - }; -} - -function copyPosition(position) { - return { - index: position.index, - line: position.line, - column: position.column - }; -} - -function lexer(str, options) { - var state = { - str: str, - options: options, - position: makeInitialPosition(), - tokens: [] - }; - lex(state); - return state.tokens; -} - -function lex(state) { - var str = state.str, - childlessTags = state.options.childlessTags; - - var len = str.length; - while (state.position.index < len) { - var start = state.position.index; - lexText(state); - if (state.position.index === start) { - var isComment = (0, _compat.startsWith)(str, '!--', start + 1); - if (isComment) { - lexComment(state); - } else { - var tagName = lexTag(state); - var safeTag = tagName.toLowerCase(); - if ((0, _compat.arrayIncludes)(childlessTags, safeTag)) { - lexSkipTag(tagName, state); - } - } - } - } -} - -var alphanumeric = /[A-Za-z0-9]/; -function findTextEnd(str, index) { - while (true) { - var textEnd = str.indexOf('<', index); - if (textEnd === -1) { - return textEnd; - } - var char = str.charAt(textEnd + 1); - if (char === '/' || char === '!' || alphanumeric.test(char)) { - return textEnd; - } - index = textEnd + 1; - } -} - -function lexText(state) { - var type = 'text'; - var str = state.str, - position = state.position; - - var textEnd = findTextEnd(str, position.index); - if (textEnd === position.index) return; - if (textEnd === -1) { - textEnd = str.length; - } - - var start = copyPosition(position); - var content = str.slice(position.index, textEnd); - jumpPosition(position, str, textEnd); - var end = copyPosition(position); - state.tokens.push({ type: type, content: content, position: { start: start, end: end } }); -} - -function lexComment(state) { - var str = state.str, - position = state.position; - - var start = copyPosition(position); - feedPosition(position, str, 4); // "', position.index); - var commentEnd = contentEnd + 3; // "-->".length - if (contentEnd === -1) { - contentEnd = commentEnd = str.length; - } - - var content = str.slice(position.index, contentEnd); - jumpPosition(position, str, commentEnd); - state.tokens.push({ - type: 'comment', - content: content, - position: { - start: start, - end: copyPosition(position) - } - }); -} - -function lexTag(state) { - var str = state.str, - position = state.position; - - { - var secondChar = str.charAt(position.index + 1); - var close = secondChar === '/'; - var start = copyPosition(position); - feedPosition(position, str, close ? 2 : 1); - state.tokens.push({ type: 'tag-start', close: close, position: { start: start } }); - } - var tagName = lexTagName(state); - lexTagAttributes(state); - { - var firstChar = str.charAt(position.index); - var _close = firstChar === '/'; - feedPosition(position, str, _close ? 2 : 1); - var end = copyPosition(position); - state.tokens.push({ type: 'tag-end', close: _close, position: { end: end } }); - } - return tagName; -} - -// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-white-space -var whitespace = /\s/; -function isWhitespaceChar(char) { - return whitespace.test(char); -} - -function lexTagName(state) { - var str = state.str, - position = state.position; - - var len = str.length; - var start = position.index; - while (start < len) { - var char = str.charAt(start); - var isTagChar = !(isWhitespaceChar(char) || char === '/' || char === '>'); - if (isTagChar) break; - start++; - } - - var end = start + 1; - while (end < len) { - var _char = str.charAt(end); - var _isTagChar = !(isWhitespaceChar(_char) || _char === '/' || _char === '>'); - if (!_isTagChar) break; - end++; - } - - jumpPosition(position, str, end); - var tagName = str.slice(start, end); - state.tokens.push({ - type: 'tag', - content: tagName - }); - return tagName; -} - -function lexTagAttributes(state) { - var str = state.str, - position = state.position, - tokens = state.tokens; - - var cursor = position.index; - var quote = null; // null, single-, or double-quote - var wordBegin = cursor; // index of word start - var words = []; // "key", "key=value", "key='value'", etc - var len = str.length; - while (cursor < len) { - var char = str.charAt(cursor); - if (quote) { - var isQuoteEnd = char === quote; - if (isQuoteEnd) { - quote = null; - } - cursor++; - continue; - } - - var isTagEnd = char === '/' || char === '>'; - if (isTagEnd) { - if (cursor !== wordBegin) { - words.push(str.slice(wordBegin, cursor)); - } - break; - } - - var isWordEnd = isWhitespaceChar(char); - if (isWordEnd) { - if (cursor !== wordBegin) { - words.push(str.slice(wordBegin, cursor)); - } - wordBegin = cursor + 1; - cursor++; - continue; - } - - var isQuoteStart = char === '\'' || char === '"'; - if (isQuoteStart) { - quote = char; - cursor++; - continue; - } - - cursor++; - } - jumpPosition(position, str, cursor); - - var wLen = words.length; - var type = 'attribute'; - for (var i = 0; i < wLen; i++) { - var word = words[i]; - var isNotPair = word.indexOf('=') === -1; - if (isNotPair) { - var secondWord = words[i + 1]; - if (secondWord && (0, _compat.startsWith)(secondWord, '=')) { - if (secondWord.length > 1) { - var newWord = word + secondWord; - tokens.push({ type: type, content: newWord }); - i += 1; - continue; - } - var thirdWord = words[i + 2]; - i += 1; - if (thirdWord) { - var _newWord = word + '=' + thirdWord; - tokens.push({ type: type, content: _newWord }); - i += 1; - continue; - } - } - } - if ((0, _compat.endsWith)(word, '=')) { - var _secondWord = words[i + 1]; - if (_secondWord && !(0, _compat.stringIncludes)(_secondWord, '=')) { - var _newWord3 = word + _secondWord; - tokens.push({ type: type, content: _newWord3 }); - i += 1; - continue; - } - - var _newWord2 = word.slice(0, -1); - tokens.push({ type: type, content: _newWord2 }); - continue; - } - - tokens.push({ type: type, content: word }); - } -} - -var push = [].push; - -function lexSkipTag(tagName, state) { - var str = state.str, - position = state.position, - tokens = state.tokens; - - var safeTagName = tagName.toLowerCase(); - var len = str.length; - var index = position.index; - while (index < len) { - var nextTag = str.indexOf('', position.index)\n let commentEnd = contentEnd + 3 // \"-->\".length\n if (contentEnd === -1) {\n contentEnd = commentEnd = str.length\n }\n\n const content = str.slice(position.index, contentEnd)\n jumpPosition(position, str, commentEnd)\n state.tokens.push({\n type: 'comment',\n content,\n position: {\n start,\n end: copyPosition(position)\n }\n })\n}\n\nexport function lexTag (state) {\n const {str, position} = state\n {\n const secondChar = str.charAt(position.index + 1)\n const close = secondChar === '/'\n const start = copyPosition(position)\n feedPosition(position, str, close ? 2 : 1)\n state.tokens.push({type: 'tag-start', close, position: {start}})\n }\n const tagName = lexTagName(state)\n lexTagAttributes(state)\n {\n const firstChar = str.charAt(position.index)\n const close = firstChar === '/'\n feedPosition(position, str, close ? 2 : 1)\n const end = copyPosition(position)\n state.tokens.push({type: 'tag-end', close, position: {end}})\n }\n return tagName\n}\n\n// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#special-white-space\nconst whitespace = /\\s/\nexport function isWhitespaceChar (char) {\n return whitespace.test(char)\n}\n\nexport function lexTagName (state) {\n const {str, position} = state\n const len = str.length\n let start = position.index\n while (start < len) {\n const char = str.charAt(start)\n const isTagChar = !(isWhitespaceChar(char) || char === '/' || char === '>')\n if (isTagChar) break\n start++\n }\n\n let end = start + 1\n while (end < len) {\n const char = str.charAt(end)\n const isTagChar = !(isWhitespaceChar(char) || char === '/' || char === '>')\n if (!isTagChar) break\n end++\n }\n\n jumpPosition(position, str, end)\n const tagName = str.slice(start, end)\n state.tokens.push({\n type: 'tag',\n content: tagName\n })\n return tagName\n}\n\nexport function lexTagAttributes (state) {\n const {str, position, tokens} = state\n let cursor = position.index\n let quote = null // null, single-, or double-quote\n let wordBegin = cursor // index of word start\n const words = [] // \"key\", \"key=value\", \"key='value'\", etc\n const len = str.length\n while (cursor < len) {\n const char = str.charAt(cursor)\n if (quote) {\n const isQuoteEnd = char === quote\n if (isQuoteEnd) {\n quote = null\n }\n cursor++\n continue\n }\n\n const isTagEnd = char === '/' || char === '>'\n if (isTagEnd) {\n if (cursor !== wordBegin) {\n words.push(str.slice(wordBegin, cursor))\n }\n break\n }\n\n const isWordEnd = isWhitespaceChar(char)\n if (isWordEnd) {\n if (cursor !== wordBegin) {\n words.push(str.slice(wordBegin, cursor))\n }\n wordBegin = cursor + 1\n cursor++\n continue\n }\n\n const isQuoteStart = char === '\\'' || char === '\"'\n if (isQuoteStart) {\n quote = char\n cursor++\n continue\n }\n\n cursor++\n }\n jumpPosition(position, str, cursor)\n\n const wLen = words.length\n const type = 'attribute'\n for (let i = 0; i < wLen; i++) {\n const word = words[i]\n const isNotPair = word.indexOf('=') === -1\n if (isNotPair) {\n const secondWord = words[i + 1]\n if (secondWord && startsWith(secondWord, '=')) {\n if (secondWord.length > 1) {\n const newWord = word + secondWord\n tokens.push({type, content: newWord})\n i += 1\n continue\n }\n const thirdWord = words[i + 2]\n i += 1\n if (thirdWord) {\n const newWord = word + '=' + thirdWord\n tokens.push({type, content: newWord})\n i += 1\n continue\n }\n }\n }\n if (endsWith(word, '=')) {\n const secondWord = words[i + 1]\n if (secondWord && !stringIncludes(secondWord, '=')) {\n const newWord = word + secondWord\n tokens.push({type, content: newWord})\n i += 1\n continue\n }\n\n const newWord = word.slice(0, -1)\n tokens.push({type, content: newWord})\n continue\n }\n\n tokens.push({type, content: word})\n }\n}\n\nconst push = [].push\n\nexport function lexSkipTag (tagName, state) {\n const {str, position, tokens} = state\n const safeTagName = tagName.toLowerCase()\n const len = str.length\n let index = position.index\n while (index < len) {\n const nextTag = str.indexOf('= 0) { - var parentTagName = stack[currentIndex].tagName; - if (parentTagName === tagName) { - break; - } - if ((0, _compat.arrayIncludes)(tagParents, parentTagName)) { - return true; - } - currentIndex--; - } - } - return false; -} - -function rewindStack(stack, newLength, childrenEndPosition, endPosition) { - stack[newLength].position.end = endPosition; - for (var i = newLength + 1, len = stack.length; i < len; i++) { - stack[i].position.end = childrenEndPosition; - } - stack.splice(newLength); -} - -function parse(state) { - var tokens = state.tokens, - options = state.options; - var stack = state.stack; - - var nodes = stack[stack.length - 1].children; - var len = tokens.length; - var cursor = state.cursor; - - while (cursor < len) { - var token = tokens[cursor]; - if (token.type !== 'tag-start') { - nodes.push(token); - cursor++; - continue; - } - - var tagToken = tokens[++cursor]; - cursor++; - var tagName = tagToken.content.toLowerCase(); - if (token.close) { - var index = stack.length; - var shouldRewind = false; - while (--index > -1) { - if (stack[index].tagName === tagName) { - shouldRewind = true; - break; - } - } - while (cursor < len) { - var endToken = tokens[cursor]; - if (endToken.type !== 'tag-end') break; - cursor++; - } - if (shouldRewind) { - rewindStack(stack, index, token.position.start, tokens[cursor - 1].position.end); - break; - } else { - continue; - } - } - - var isClosingTag = (0, _compat.arrayIncludes)(options.closingTags, tagName); - var shouldRewindToAutoClose = isClosingTag; - if (shouldRewindToAutoClose) { - var terminals = options.closingTagAncestorBreakers; - - shouldRewindToAutoClose = !hasTerminalParent(tagName, stack, terminals); - } - - if (shouldRewindToAutoClose) { - // rewind the stack to just above the previous - // closing tag of the same name - var currentIndex = stack.length - 1; - while (currentIndex > 0) { - if (tagName === stack[currentIndex].tagName) { - rewindStack(stack, currentIndex, token.position.start, token.position.start); - var previousIndex = currentIndex - 1; - nodes = stack[previousIndex].children; - break; - } - currentIndex = currentIndex - 1; - } - } - - var attributes = []; - var attrToken = void 0; - while (cursor < len) { - attrToken = tokens[cursor]; - if (attrToken.type === 'tag-end') break; - attributes.push(attrToken.content); - cursor++; - } - - cursor++; - var children = []; - var position = { - start: token.position.start, - end: attrToken.position.end - }; - var elementNode = { - type: 'element', - tagName: tagToken.content, - attributes: attributes, - children: children, - position: position - }; - nodes.push(elementNode); - - var hasChildren = !(attrToken.close || (0, _compat.arrayIncludes)(options.voidTags, tagName)); - if (hasChildren) { - var size = stack.push({ tagName: tagName, children: children, position: position }); - var innerState = { tokens: tokens, options: options, cursor: cursor, stack: stack }; - parse(innerState); - cursor = innerState.cursor; - var rewoundInElement = stack.length === size; - if (rewoundInElement) { - elementNode.position.end = tokens[cursor - 1].position.end; - } - } - } - state.cursor = cursor; -} -//# sourceMappingURL=parser.js.map diff --git a/node_modules/himalaya/lib/parser.js.map b/node_modules/himalaya/lib/parser.js.map deleted file mode 100644 index 760306d..0000000 --- a/node_modules/himalaya/lib/parser.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["parser.js"],"names":["parser","hasTerminalParent","rewindStack","parse","tokens","options","root","tagName","children","state","cursor","stack","terminals","tagParents","currentIndex","length","parentTagName","newLength","childrenEndPosition","endPosition","position","end","i","len","splice","nodes","token","type","push","tagToken","content","toLowerCase","close","index","shouldRewind","endToken","start","isClosingTag","closingTags","shouldRewindToAutoClose","closingTagAncestorBreakers","previousIndex","attributes","attrToken","elementNode","hasChildren","voidTags","size","innerState","rewoundInElement"],"mappings":";;;;;kBAEwBA,M;QAORC,iB,GAAAA,iB;QAkBAC,W,GAAAA,W;QAQAC,K,GAAAA,K;;AAnChB;;AAEe,SAASH,MAAT,CAAiBI,MAAjB,EAAyBC,OAAzB,EAAkC;AAC/C,MAAMC,OAAO,EAACC,SAAS,IAAV,EAAgBC,UAAU,EAA1B,EAAb;AACA,MAAMC,QAAQ,EAACL,cAAD,EAASC,gBAAT,EAAkBK,QAAQ,CAA1B,EAA6BC,OAAO,CAACL,IAAD,CAApC,EAAd;AACAH,QAAMM,KAAN;AACA,SAAOH,KAAKE,QAAZ;AACD;;AAEM,SAASP,iBAAT,CAA4BM,OAA5B,EAAqCI,KAArC,EAA4CC,SAA5C,EAAuD;AAC5D,MAAMC,aAAaD,UAAUL,OAAV,CAAnB;AACA,MAAIM,UAAJ,EAAgB;AACd,QAAIC,eAAeH,MAAMI,MAAN,GAAe,CAAlC;AACA,WAAOD,gBAAgB,CAAvB,EAA0B;AACxB,UAAME,gBAAgBL,MAAMG,YAAN,EAAoBP,OAA1C;AACA,UAAIS,kBAAkBT,OAAtB,EAA+B;AAC7B;AACD;AACD,UAAI,2BAAcM,UAAd,EAA0BG,aAA1B,CAAJ,EAA8C;AAC5C,eAAO,IAA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C;AAClCe,iBAAWd,IAAX,CAAgBe,UAAUb,OAA1B;AACApB;AACD;;AAEDA;AACA,QAAMF,WAAW,EAAjB;AACA,QAAMY,WAAW;AACfgB,aAAOV,MAAMN,QAAN,CAAegB,KADP;AAEff,WAAKsB,UAAUvB,QAAV,CAAmBC;AAFT,KAAjB;AAIA,QAAMuB,cAAc;AAClBjB,YAAM,SADY;AAElBpB,eAASsB,SAASC,OAFA;AAGlBY,4BAHkB;AAIlBlC,wBAJkB;AAKlBY;AALkB,KAApB;AAOAK,UAAMG,IAAN,CAAWgB,WAAX;;AAEA,QAAMC,cAAc,EAAEF,UAAUX,KAAV,IAAmB,2BAAc3B,QAAQyC,QAAtB,EAAgCvC,OAAhC,CAArB,CAApB;AACA,QAAIsC,WAAJ,EAAiB;AACf,UAAME,OAAOpC,MAAMiB,IAAN,CAAW,EAACrB,gBAAD,EAAUC,kBAAV,EAAoBY,kBAApB,EAAX,CAAb;AACA,UAAM4B,aAAa,EAAC5C,cAAD,EAASC,gBAAT,EAAkBK,cAAlB,EAA0BC,YAA1B,EAAnB;AACAR,YAAM6C,UAAN;AACAtC,eAASsC,WAAWtC,MAApB;AACA,UAAMuC,mBAAmBtC,MAAMI,MAAN,KAAiBgC,IAA1C;AACA,UAAIE,gBAAJ,EAAsB;AACpBL,oBAAYxB,QAAZ,CAAqBC,GAArB,GAA2BjB,OAAOM,SAAS,CAAhB,EAAmBU,QAAnB,CAA4BC,GAAvD;AACD;AACF;AACF;AACDZ,QAAMC,MAAN,GAAeA,MAAf;AACD","file":"parser.js","sourcesContent":["import {arrayIncludes} from './compat'\n\nexport default function parser (tokens, options) {\n const root = {tagName: null, children: []}\n const state = {tokens, options, cursor: 0, stack: [root]}\n parse(state)\n return root.children\n}\n\nexport function hasTerminalParent (tagName, stack, terminals) {\n const tagParents = terminals[tagName]\n if (tagParents) {\n let currentIndex = stack.length - 1\n while (currentIndex >= 0) {\n const parentTagName = stack[currentIndex].tagName\n if (parentTagName === tagName) {\n break\n }\n if (arrayIncludes(tagParents, parentTagName)) {\n return true\n }\n currentIndex--\n }\n }\n return false\n}\n\nexport function rewindStack (stack, newLength, childrenEndPosition, endPosition) {\n stack[newLength].position.end = endPosition\n for (let i = newLength + 1, len = stack.length; i < len; i++) {\n stack[i].position.end = childrenEndPosition\n }\n stack.splice(newLength)\n}\n\nexport function parse (state) {\n const {tokens, options} = state\n let {stack} = state\n let nodes = stack[stack.length - 1].children\n const len = tokens.length\n let {cursor} = state\n while (cursor < len) {\n const token = tokens[cursor]\n if (token.type !== 'tag-start') {\n nodes.push(token)\n cursor++\n continue\n }\n\n const tagToken = tokens[++cursor]\n cursor++\n const tagName = tagToken.content.toLowerCase()\n if (token.close) {\n let index = stack.length\n let shouldRewind = false\n while (--index > -1) {\n if (stack[index].tagName === tagName) {\n shouldRewind = true\n break\n }\n }\n while (cursor < len) {\n const endToken = tokens[cursor]\n if (endToken.type !== 'tag-end') break\n cursor++\n }\n if (shouldRewind) {\n rewindStack(stack, index, token.position.start, tokens[cursor - 1].position.end)\n break\n } else {\n continue\n }\n }\n\n const isClosingTag = arrayIncludes(options.closingTags, tagName)\n let shouldRewindToAutoClose = isClosingTag\n if (shouldRewindToAutoClose) {\n const { closingTagAncestorBreakers: terminals } = options\n shouldRewindToAutoClose = !hasTerminalParent(tagName, stack, terminals)\n }\n\n if (shouldRewindToAutoClose) {\n // rewind the stack to just above the previous\n // closing tag of the same name\n let currentIndex = stack.length - 1\n while (currentIndex > 0) {\n if (tagName === stack[currentIndex].tagName) {\n rewindStack(stack, currentIndex, token.position.start, token.position.start)\n const previousIndex = currentIndex - 1\n nodes = stack[previousIndex].children\n break\n }\n currentIndex = currentIndex - 1\n }\n }\n\n let attributes = []\n let attrToken\n while (cursor < len) {\n attrToken = tokens[cursor]\n if (attrToken.type === 'tag-end') break\n attributes.push(attrToken.content)\n cursor++\n }\n\n cursor++\n const children = []\n const position = {\n start: token.position.start,\n end: attrToken.position.end\n }\n const elementNode = {\n type: 'element',\n tagName: tagToken.content,\n attributes,\n children,\n position\n }\n nodes.push(elementNode)\n\n const hasChildren = !(attrToken.close || arrayIncludes(options.voidTags, tagName))\n if (hasChildren) {\n const size = stack.push({tagName, children, position})\n const innerState = {tokens, options, cursor, stack}\n parse(innerState)\n cursor = innerState.cursor\n const rewoundInElement = stack.length === size\n if (rewoundInElement) {\n elementNode.position.end = tokens[cursor - 1].position.end\n }\n }\n }\n state.cursor = cursor\n}\n"]} \ No newline at end of file diff --git a/node_modules/himalaya/lib/stringify.js b/node_modules/himalaya/lib/stringify.js deleted file mode 100644 index f550906..0000000 --- a/node_modules/himalaya/lib/stringify.js +++ /dev/null @@ -1,43 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.formatAttributes = formatAttributes; -exports.toHTML = toHTML; - -var _compat = require('./compat'); - -function formatAttributes(attributes) { - return attributes.reduce(function (attrs, attribute) { - var key = attribute.key, - value = attribute.value; - - if (value === null) { - return attrs + ' ' + key; - } - var quoteEscape = value.indexOf('\'') !== -1; - var quote = quoteEscape ? '"' : '\''; - return attrs + ' ' + key + '=' + quote + value + quote; - }, ''); -} - -function toHTML(tree, options) { - return tree.map(function (node) { - if (node.type === 'text') { - return node.content; - } - if (node.type === 'comment') { - return ''; - } - var tagName = node.tagName, - attributes = node.attributes, - children = node.children; - - var isSelfClosing = (0, _compat.arrayIncludes)(options.voidTags, tagName.toLowerCase()); - return isSelfClosing ? '<' + tagName + formatAttributes(attributes) + '>' : '<' + tagName + formatAttributes(attributes) + '>' + toHTML(children, options) + ''; - }).join(''); -} - -exports.default = { toHTML: toHTML }; -//# sourceMappingURL=stringify.js.map diff --git a/node_modules/himalaya/lib/stringify.js.map b/node_modules/himalaya/lib/stringify.js.map deleted file mode 100644 index ecc4847..0000000 --- a/node_modules/himalaya/lib/stringify.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"sources":["stringify.js"],"names":["formatAttributes","toHTML","attributes","reduce","attrs","attribute","key","value","quoteEscape","indexOf","quote","tree","options","map","node","type","content","tagName","children","isSelfClosing","voidTags","toLowerCase","join"],"mappings":";;;;;QAEgBA,gB,GAAAA,gB;QAYAC,M,GAAAA,M;;AAdhB;;AAEO,SAASD,gBAAT,CAA2BE,UAA3B,EAAuC;AAC5C,SAAOA,WAAWC,MAAX,CAAkB,UAACC,KAAD,EAAQC,SAAR,EAAsB;AAAA,QACtCC,GADsC,GACxBD,SADwB,CACtCC,GADsC;AAAA,QACjCC,KADiC,GACxBF,SADwB,CACjCE,KADiC;;AAE7C,QAAIA,UAAU,IAAd,EAAoB;AAClB,aAAUH,KAAV,SAAmBE,GAAnB;AACD;AACD,QAAME,cAAcD,MAAME,OAAN,CAAc,IAAd,MAAwB,CAAC,CAA7C;AACA,QAAMC,QAAQF,cAAc,GAAd,GAAoB,IAAlC;AACA,WAAUJ,KAAV,SAAmBE,GAAnB,SAA0BI,KAA1B,GAAkCH,KAAlC,GAA0CG,KAA1C;AACD,GARM,EAQJ,EARI,CAAP;AASD;;AAEM,SAAST,MAAT,CAAiBU,IAAjB,EAAuBC,OAAvB,EAAgC;AACrC,SAAOD,KAAKE,GAAL,CAAS,gBAAQ;AACtB,QAAIC,KAAKC,IAAL,KAAc,MAAlB,EAA0B;AACxB,aAAOD,KAAKE,OAAZ;AACD;AACD,QAAIF,KAAKC,IAAL,KAAc,SAAlB,EAA6B;AAC3B,sBAAcD,KAAKE,OAAnB;AACD;AANqB,QAOfC,OAPe,GAOkBH,IAPlB,CAOfG,OAPe;AAAA,QAONf,UAPM,GAOkBY,IAPlB,CAONZ,UAPM;AAAA,QAOMgB,QAPN,GAOkBJ,IAPlB,CAOMI,QAPN;;AAQtB,QAAMC,gBAAgB,2BAAcP,QAAQQ,QAAtB,EAAgCH,QAAQI,WAAR,EAAhC,CAAtB;AACA,WAAOF,sBACCF,OADD,GACWjB,iBAAiBE,UAAjB,CADX,eAECe,OAFD,GAEWjB,iBAAiBE,UAAjB,CAFX,SAE2CD,OAAOiB,QAAP,EAAiBN,OAAjB,CAF3C,UAEyEK,OAFzE,MAAP;AAGD,GAZM,EAYJK,IAZI,CAYC,EAZD,CAAP;AAaD;;kBAEc,EAACrB,cAAD,E","file":"stringify.js","sourcesContent":["import {arrayIncludes} from './compat'\n\nexport function formatAttributes (attributes) {\n return attributes.reduce((attrs, attribute) => {\n const {key, value} = attribute\n if (value === null) {\n return `${attrs} ${key}`\n }\n const quoteEscape = value.indexOf('\\'') !== -1\n const quote = quoteEscape ? '\"' : '\\''\n return `${attrs} ${key}=${quote}${value}${quote}`\n }, '')\n}\n\nexport function toHTML (tree, options) {\n return tree.map(node => {\n if (node.type === 'text') {\n return node.content\n }\n if (node.type === 'comment') {\n return ``\n }\n const {tagName, attributes, children} = node\n const isSelfClosing = arrayIncludes(options.voidTags, tagName.toLowerCase())\n return isSelfClosing\n ? `<${tagName}${formatAttributes(attributes)}>`\n : `<${tagName}${formatAttributes(attributes)}>${toHTML(children, options)}`\n }).join('')\n}\n\nexport default {toHTML}\n"]} \ No newline at end of file diff --git a/node_modules/himalaya/lib/tags.js b/node_modules/himalaya/lib/tags.js deleted file mode 100644 index 4f9d33b..0000000 --- a/node_modules/himalaya/lib/tags.js +++ /dev/null @@ -1,41 +0,0 @@ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -/* - Tags which contain arbitary non-parsed content - For example: ' - const state = {str, position: ps(8), tokens: []} - lexSkipTag('script', state) - t.is(state.position.index, str.length) - t.deepEqual(state.tokens, [ - {type: 'text', content: 'proving ', position: {start: ps(8), end: ps(26)}}, - {type: 'tag-start', close: true, position: {start: ps(26)}}, - {type: 'tag', content: 'script'}, - {type: 'tag-end', close: false, position: {end: ps(str.length)}} - ]) -}) - -test('lexSkipTag should not add an empty inner text node', t => { - const str = '' - const state = {str, position: ps(8), tokens: []} - lexSkipTag('script', state) - t.is(state.position.index, str.length) - t.deepEqual(state.tokens, [ - {type: 'tag-start', close: true, position: {start: ps(8)}}, - {type: 'tag', content: 'script'}, - {type: 'tag-end', close: false, position: {end: ps(str.length)}} - ]) -}) - -test('isWhitespace should work', t => { - t.is(isWhitespaceChar(' '), true) - t.is(isWhitespaceChar('\n'), true) - t.is(isWhitespaceChar('\t'), true) - t.is(isWhitespaceChar('x'), false) -}) diff --git a/node_modules/himalaya/test/parser.js b/node_modules/himalaya/test/parser.js deleted file mode 100644 index 6ceebde..0000000 --- a/node_modules/himalaya/test/parser.js +++ /dev/null @@ -1,775 +0,0 @@ -import test from 'ava' -import parser from '../lib/parser' -import lexer from '../lib/lexer' - -function ps (index) { - return { index, line: 0, column: index } -} - -const lexerOptions = { childlessTags: [] } -const parserOptions = { - voidTags: [], - closingTags: [], - closingTagAncestorBreakers: {} -} - -test('parser() should return nodes', t => { - const str = '

Hello world

' - const tokens = lexer(str, lexerOptions) - const nodes = parser(tokens, parserOptions) - t.deepEqual(nodes, [ - { - type: 'element', - tagName: 'h1', - attributes: [], - children: [ - { - type: 'text', - content: 'Hello world', - position: { - start: ps(4), - end: ps(15) - } - } - ], - position: { - start: ps(0), - end: ps(str.length) - } - } - ]) -}) - -test('parser() should not nest within void tags', t => { - const str = '
abcdef
' - const tokens = lexer(str, lexerOptions) - const nodes = parser(tokens, { voidTags: 'img', closingTags: [] }) - t.deepEqual(nodes, [ - { - type: 'element', - tagName: 'div', - attributes: [], - children: [ - { - type: 'text', - content: 'abc', - position: { - start: ps(5), - end: ps(8) - } - }, - { - type: 'element', - tagName: 'img', - attributes: [], - children: [], - position: { - start: ps(8), - end: ps(14) - } - }, - { - type: 'text', - content: 'def', - position: { - start: ps(14), - end: ps(17) - } - } - ], - position: { - start: ps(0), - end: ps(str.length) - } - } - ]) -}) - -test('parser() should handle optional-close tags', t => { - { - const parserOptions = { - voidTags: [], - closingTags: ['p'], - closingTagAncestorBreakers: {} - } - const str = '

This is one

This is two

' - const tokens = lexer(str, lexerOptions) - const nodes = parser(tokens, parserOptions) - t.deepEqual(nodes, [ - { - type: 'element', - tagName: 'p', - attributes: [], - children: [ - { - type: 'text', - content: 'This is one', - position: { - start: ps(3), - end: ps(14) - } - } - ], - position: { - start: ps(0), - end: ps(14) - } - }, - { - type: 'element', - tagName: 'p', - attributes: [], - children: [ - { - type: 'text', - content: 'This is two', - position: { - start: ps(17), - end: ps(28) - } - } - ], - position: { - start: ps(14), - end: ps(str.length) - } - } - ]) - } - - { - const parserOptions = { - voidTags: [], - closingTags: ['p', 'span'], - closingTagAncestorBreakers: {} - } - const str = '

This is one okay

This is two

' - const tokens = lexer(str, lexerOptions) - const nodes = parser(tokens, parserOptions) - t.deepEqual(nodes, [ - { - type: 'element', - tagName: 'p', - attributes: [], - children: [ - { - type: 'text', - content: 'This is one ', - position: { - start: ps(3), - end: ps(15) - } - }, - { - type: 'element', - tagName: 'span', - attributes: [], - children: [ - { - type: 'text', - content: 'okay', - position: { - start: ps(21), - end: ps(25) - } - } - ], - position: { - start: ps(15), - end: ps(25) - } - } - ], - position: { - start: ps(0), - end: ps(25) - } - }, - { - type: 'element', - tagName: 'p', - attributes: [], - children: [ - { - type: 'text', - content: 'This is two', - position: { - start: ps(28), - end: ps(39) - } - } - ], - position: { - start: ps(25), - end: ps(43) - } - } - ]) - } -}) - -test('parser() should auto-close unmatched child tags', t => { - const parserOptions = { - voidTags: [], - closingTags: [], - closingTagAncestorBreakers: {} - } - const str = '
This is one okay
' - const tokens = lexer(str, lexerOptions) - const nodes = parser(tokens, parserOptions) - t.deepEqual(nodes, [ - { - type: 'element', - tagName: 'div', - attributes: [], - position: { - start: ps(0), - end: ps(36) - }, - children: [ - { - type: 'text', - content: 'This is ', - position: { - start: ps(5), - end: ps(13) - } - }, - { - type: 'element', - tagName: 'b', - attributes: [], - position: { - start: ps(13), - end: ps(30) - }, - children: [ - { - type: 'text', - content: 'one ', - position: { - start: ps(16), - end: ps(20) - } - }, - { - type: 'element', - tagName: 'span', - attributes: [], - position: { - start: ps(20), - end: ps(30) - }, - children: [ - { - type: 'text', - content: 'okay', - position: { - start: ps(26), - end: ps(30) - } - } - ] - } - ] - } - ] - } - ]) -}) - -test('parser() should handle empty token arrays', t => { - const tokens = [] - const nodes = parser(tokens, parserOptions) - t.deepEqual(nodes, []) -}) - -test('parser() should report the element attributes', t => { - const str = '
' - const tokens = lexer(str, lexerOptions) - const nodes = parser(tokens, parserOptions) - t.deepEqual(nodes, [ - { - type: 'element', - tagName: 'div', - attributes: ['class="cake"', 'data-key="abc"', 'disabled'], - position: { - start: ps(0), - end: ps(48) - }, - children: [] - } - ]) -}) - -test('parser() should handle unclosed elements', t => { - const str = '
abc' - const tokens = lexer(str, lexerOptions) - const nodes = parser(tokens, parserOptions) - t.deepEqual(nodes, [ - { - type: 'element', - tagName: 'div', - attributes: [], - position: { - start: ps(0), - end: ps(str.length) - }, - children: [ - { - type: 'text', - content: 'abc', - position: { - start: ps(5), - end: ps(str.length) - } - } - ] - } - ]) -}) - -test('parser() should preserve case-sensitive tag names', t => { - const str = '' - const tokens = lexer(str, lexerOptions) - const nodes = parser(tokens, parserOptions) - t.deepEqual(nodes, [ - { - type: 'element', - tagName: 'You-Know-8', - attributes: [], - position: { - start: ps(0), - end: ps(str.length) - }, - children: [] - } - ]) -}) - -test('parser() should match by case-insensitive tags', t => { - const str = '
abc
def' - const tokens = lexer(str, lexerOptions) - const nodes = parser(tokens, parserOptions) - t.deepEqual(nodes, [ - { - type: 'element', - tagName: 'div', - attributes: [], - position: { - start: ps(0), - end: ps(14) - }, - children: [ - { - type: 'text', - content: 'abc', - position: { - start: ps(5), - end: ps(8) - } - } - ] - }, - { - type: 'text', - content: 'def', - position: { - start: ps(14), - end: ps(17) - } - } - ]) -}) - -test('parser() should handle ancestor breaker special case (#39)', t => { - /* - To summarize, this special case is where a is - encountered within an
  • . The default behavior for
  • s - as closing tags is to rewind up and auto-close the previous -
  • . However,
  • may contain before being - closed so we should not rewind the stack in those cases. - - This edge-case also applies to in
    s. - */ - - { - const str = '
    • abc
      • def
    ' - const tokens = lexer(str, lexerOptions) - const nodes = parser(tokens, { - voidTags: [], - closingTags: ['li'], - closingTagAncestorBreakers: { - li: ['ul'] - } - }) - - t.deepEqual(nodes, [ - { - type: 'element', - tagName: 'ul', - attributes: [], - position: { - start: ps(0), - end: ps(42) - }, - children: [ - { - type: 'element', - tagName: 'li', - attributes: [], - position: { - start: ps(4), - end: ps(37) - }, - children: [ - { - type: 'text', - content: 'abc', - position: { - start: ps(8), - end: ps(11) - } - }, - { - type: 'element', - tagName: 'ul', - attributes: [], - position: { - start: ps(11), - end: ps(32) - }, - children: [ - { - type: 'element', - tagName: 'li', - attributes: [], - position: { - start: ps(15), - end: ps(27) - }, - children: [ - { - type: 'text', - content: 'def', - position: { - start: ps(19), - end: ps(22) - } - } - ] - } - ] - } - ] - } - ] - } - ]) - } - - { - const str = '
    • abc
      • def
    ' - const tokens = lexer(str, lexerOptions) - const nodes = parser(tokens, { - voidTags: [], - closingTags: ['li'], - closingTagAncestorBreakers: { - li: ['ul'] - } - }) - - t.deepEqual(nodes, [ - { - type: 'element', - tagName: 'ul', - attributes: [], - position: { - start: ps(0), - end: ps(55) - }, - children: [ - { - type: 'element', - tagName: 'li', - attributes: [], - position: { - start: ps(4), - end: ps(50) - }, - children: [ - { - type: 'text', - content: 'abc', - position: { - start: ps(8), - end: ps(11) - } - }, - { - type: 'element', - tagName: 'ul', - attributes: [], - position: { - start: ps(11), - end: ps(45) - }, - children: [ - { - type: 'element', - tagName: 'span', - attributes: [], - position: { - start: ps(15), - end: ps(40) - }, - children: [ - { - type: 'element', - tagName: 'li', - attributes: [], - position: { - start: ps(21), - end: ps(33) - }, - children: [ - { - type: 'text', - content: 'def', - position: { - start: ps(25), - end: ps(28) - } - } - ] - } - ] - } - ] - } - ] - } - ] - } - ]) - } - - { - const str = '
    • abc
      • def
      • ghi
    ' - const tokens = lexer(str, lexerOptions) - const nodes = parser(tokens, { - voidTags: [], - closingTags: ['li'], - closingTagAncestorBreakers: { - li: ['ul'] - } - }) - - t.deepEqual(nodes, [ - { - type: 'element', - tagName: 'ul', - attributes: [], - position: { - start: ps(0), - end: ps(49) - }, - children: [ - { - type: 'element', - tagName: 'li', - attributes: [], - position: { - start: ps(4), - end: ps(44) - }, - children: [ - { - type: 'text', - content: 'abc', - position: { - start: ps(8), - end: ps(11) - } - }, - { - type: 'element', - tagName: 'ul', - attributes: [], - position: { - start: ps(11), - end: ps(39) - }, - children: [ - { - type: 'element', - tagName: 'li', - attributes: [], - position: { - start: ps(15), - end: ps(22) - }, - children: [ - { - type: 'text', - content: 'def', - position: { - start: ps(19), - end: ps(22) - } - } - ] - }, - { - type: 'element', - tagName: 'li', - attributes: [], - position: { - start: ps(22), - end: ps(34) - }, - children: [ - { - type: 'text', - content: 'ghi', - position: { - start: ps(26), - end: ps(29) - } - } - ] - } - ] - } - ] - } - ] - } - ]) - } -}) - -test('parser() should handle nested tables', t => { - const str = - '
    ' - const tokens = lexer(str, lexerOptions) - const nodes = parser(tokens, { - voidTags: [], - closingTags: ['tbody'], - closingTagAncestorBreakers: { - tbody: ['table'], - tr: ['table'], - td: ['table'] - } - }) - - t.deepEqual(nodes, [ - { - type: 'element', - tagName: 'table', - attributes: [], - position: { - start: ps(0), - end: ps(96) - }, - children: [ - { - type: 'element', - tagName: 'tbody', - attributes: [], - position: { - start: ps(7), - end: ps(88) - }, - children: [ - { - type: 'element', - tagName: 'tr', - attributes: [], - position: { - start: ps(14), - end: ps(80) - }, - children: [ - { - type: 'element', - tagName: 'td', - attributes: [], - position: { - start: ps(18), - end: ps(75) - }, - children: [ - { - type: 'element', - tagName: 'table', - attributes: [], - position: { - start: ps(22), - end: ps(70) - }, - children: [ - { - type: 'element', - tagName: 'tbody', - attributes: [], - position: { - start: ps(29), - end: ps(62) - }, - children: [ - { - type: 'element', - tagName: 'tr', - attributes: [], - position: { - start: ps(36), - end: ps(54) - }, - children: [ - { - type: 'element', - tagName: 'td', - attributes: [], - position: { - start: ps(40), - end: ps(49) - }, - children: [] - } - ] - } - ] - } - ] - } - ] - } - ] - } - ] - } - ] - } - ]) -}) - -test('parser() should ignore unnecessary closing tags', t => { - /* - In this case the bit is unnecessary and should - not be represented in the output nor interfere with the stack. - */ - const str = 'x' - const tokens = lexer(str, lexerOptions) - const nodes = parser(tokens, parserOptions) - t.deepEqual(nodes, [ - { - type: 'text', - content: 'x', - position: { - start: ps(4), - end: ps(str.length) - } - } - ]) -}) diff --git a/node_modules/himalaya/test/stringify.js b/node_modules/himalaya/test/stringify.js deleted file mode 100644 index f9e63f4..0000000 --- a/node_modules/himalaya/test/stringify.js +++ /dev/null @@ -1,63 +0,0 @@ -import test from 'ava' -import {parse, stringify} from '../lib' -import {formatAttributes} from '../lib/stringify' - -test('stringify() should handle simple conversions', t => { - const str1 = '

    Text

    ' - t.is(stringify(parse(str1)), str1) - - const str2 = 'Text' - t.is(stringify(parse(str2)), str2) - - const str3 = '' - t.is(stringify(parse(str3)), str3) -}) - -test('stringify() should work for void elements', t => { - const meta = "" - t.is(stringify(parse(meta)), meta) - - const link = "" - t.is(stringify(parse(link)), link) -}) - -test('stringify() should build the class attribute properly', t => { - const elem = "
    " - t.is(stringify(parse(elem)), elem) -}) - -test('stringify() should build data-* attributes properly', t => { - const elem = "
    " - t.is(stringify(parse(elem)), elem) -}) - -test('stringify() should build the style attribute properly', t => { - const elem = "
    " - t.is(stringify(parse(elem)), elem) -}) - -test('stringify() should do basic escaping if a value contains either single or double quotes', t => { - const html = '
    ' - t.is(stringify(parse(html)), html) -}) - -test('stringify() should preserve whitespace', t => { - const html = [ - ' ', - '

    Document

    ', - ' ' - ].join('\n') - t.is(stringify(parse(html)), html) -}) - -test('formatAttributes should stringify attribute lists correctly', t => { - t.is(formatAttributes([]), '') - t.is(formatAttributes([{ - key: 'disabled', - value: null - }]), ' disabled') - t.is(formatAttributes([{ - key: 'data-key', - value: '123' - }]), " data-key='123'") -}) diff --git a/node_modules/himalaya/text/ast-spec-v0.md b/node_modules/himalaya/text/ast-spec-v0.md deleted file mode 100644 index 3e30364..0000000 --- a/node_modules/himalaya/text/ast-spec-v0.md +++ /dev/null @@ -1,79 +0,0 @@ -# Himalaya AST Specification - Version 0 - -This document describes the abstract syntax tree output of Himalaya's parsing. This specification aims to provide context as to what may be expected as valid output from Himalaya. - -## Node - -```js -interface Node { - type: string; -} -``` - -All nodes are represented as `Node` objects. These object all have a property called `type` that designate what type of node it is. - -```js -enum Type { - "Element" | "Comment" | "Text" -} -``` - -Nodes can be of `type`: - -- `Element`, which are tags such as ``, `
    `, `